Debian Codegraph @

s4cmd.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python
2
3 #
4 # Copyright 2012-2018 BloomReach, Inc.
5 # Portions Copyright 2014 Databricks
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18 #
19
20 """
21 Super S3 command line tool.
22 """
23
24 import sys, os, re, optparse, multiprocessing, fnmatch, time, hashlib, errno, pytz
25 import logging, traceback, types, threading, random, socket, shlex, datetime, json
26
27 IS_PYTHON2 = sys.version_info[0] == 2
28
29 if IS_PYTHON2:
30 from cStringIO import StringIO
31 import Queue
32 import ConfigParser
33 else:
34 from io import BytesIO as StringIO
35 import queue as Queue
36 import configparser as ConfigParser
37
38 def cmp(a, b):
39 return (a > b) - (a < b)
40
41 if sys.version_info < (2, 7):
42 # Python < 2.7 doesn't have the cmp_to_key function.
43 from utils import cmp_to_key
44 else:
45 from functools import cmp_to_key
46
47 ##
48 ## Global constants
49 ##
50
51 S4CMD_VERSION = "2.1.0"
52
53 PATH_SEP = '/'
54 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S UTC'
55 TIMESTAMP_FORMAT = '%04d-%02d-%02d %02d:%02d'
56 SOCKET_TIMEOUT = 5 * 60 # in sec(s) (timeout if we don't receive any recv() callback)
57 socket.setdefaulttimeout(SOCKET_TIMEOUT)
58
59 # Global list for temp files.
60 TEMP_FILES = set()
61
62 # Environment variable names for S3 credentials.
63 S3_ACCESS_KEY_NAME = "S3_ACCESS_KEY"
64 S3_SECRET_KEY_NAME = "S3_SECRET_KEY"
65 S4CMD_ENV_KEY = "S4CMD_OPTS"
66
67
68 ##
69 ## Utility classes
70 ##
71
72 class Failure(RuntimeError):
73 '''Exception for runtime failures'''
74 pass
75
76 class InvalidArgument(RuntimeError):
77 '''Exception for invalid input parameters'''
78 pass
79
80 class RetryFailure(Exception):
81 '''Runtime failure that can be retried'''
82 pass
83
84
85 class S4cmdLoggingClass:
86 def __init__(self):
87 self.log = logging.Logger("s4cmd")
88 self.log.stream = sys.stderr
89 self.log_handler = logging.StreamHandler(self.log.stream)
90 self.log.addHandler(self.log_handler)
91
92
93 def configure(self, opt):
94 'Configure the logger based on command-line arguments'''
95
96 self.log_handler.setFormatter(logging.Formatter('%(message)s', DATETIME_FORMAT))
97 if opt.debug:
98 self.log.verbosity = 3
99 self.log_handler.setFormatter(logging.Formatter(
100 ' (%(levelname).1s)%(filename)s:%(lineno)-4d %(message)s',
101 DATETIME_FORMAT))
102 self.log.setLevel(logging.DEBUG)
103 elif opt.verbose:
104 self.log.verbosity = 2
105 self.log.setLevel(logging.INFO)
106 else:
107 self.log.verbosity = 1
108 self.log.setLevel(logging.ERROR)
109
110
111 def get_loggers(self):
112 '''Return a list of the logger methods: (debug, info, warn, error)'''
113
114 return self.log.debug, self.log.info, self.log.warn, self.log.error
115
116 s4cmd_logging = S4cmdLoggingClass()
117 debug, info, warn, error = s4cmd_logging.get_loggers()
118
119
120 def get_default_thread_count():
121 return int(os.getenv('S4CMD_NUM_THREADS', multiprocessing.cpu_count() * 4))
122
123
124 def log_calls(func):
125 '''Decorator to log function calls.'''
126 def wrapper(*args, **kargs):
127 callStr = "%s(%s)" % (func.__name__, ", ".join([repr(p) for p in args] + ["%s=%s" % (k, repr(v)) for (k, v) in list(kargs.items())]))
128 debug(">> %s", callStr)
129 ret = func(*args, **kargs)
130 debug("<< %s: %s", callStr, repr(ret))
131 return ret
132 return wrapper
133
134 ##
135 ## Utility functions
136 ##
137
138 def synchronized(func):
139 '''Decorator to synchronize function.'''
140 func.__lock__ = threading.Lock()
141 def synced_func(*args, **kargs):
142 with func.__lock__:
143 return func(*args, **kargs)
144 return synced_func
145
146 def clear_progress():
147 '''Clear previous progress message, if any.'''
148 progress('')
149
150 @synchronized
151 def progress(msg, *args):
152 '''Show current progress message to stderr.
153 This function will remember the previous message so that next time,
154 it will clear the previous message before showing next one.
155 '''
156 # Don't show any progress if the output is directed to a file.
157 if not (sys.stdout.isatty() and sys.stderr.isatty()):
158 return
159
160 text = (msg % args)
161 if progress.prev_message:
162 sys.stderr.write(' ' * len(progress.prev_message) + '\r')
163 sys.stderr.write(text + '\r')
164 progress.prev_message = text
165
166 progress.prev_message = None
167
168 @synchronized
169 def message(msg, *args):
170 '''Program message output.'''
171 clear_progress()
172 text = (msg % args)
173 sys.stdout.write(text + '\n')
174
175 def fail(message, exc_info=None, status=1, stacktrace=False):
176 '''Utility function to handle runtime failures gracefully.
177 Show concise information if possible, then terminate program.
178 '''
179 text = message
180 if exc_info:
181 text += str(exc_info)
182 error(text)
183 if stacktrace:
184 error(traceback.format_exc())
185 clean_tempfiles()
186 if __name__ == '__main__':
187 sys.exit(status)
188 else:
189 raise RuntimeError(status)
190
191 @synchronized
192 def tempfile_get(target):
193 '''Get a temp filename for atomic download.'''
194 fn = '%s-%s.tmp' % (target, ''.join(random.Random().sample("0123456789abcdefghijklmnopqrstuvwxyz", 15)))
195 TEMP_FILES.add(fn)
196 return fn
197
198 @synchronized
199 def tempfile_set(tempfile, target):
200 '''Atomically rename and clean tempfile'''
201 if target:
202 os.rename(tempfile, target)
203 else:
204 os.unlink(tempfile)
205
206 if target in TEMP_FILES:
207 TEMP_FILES.remove(tempfile)
208
209 def clean_tempfiles():
210 '''Clean up temp files'''
211 for fn in TEMP_FILES:
212 if os.path.exists(fn):
213 os.unlink(fn)
214
215 class S3URL:
216 '''Simple wrapper for S3 URL.
217 This class parses a S3 URL and provides accessors to each component.
218 '''
219 S3URL_PATTERN = re.compile(r'(s3[n]?)://([^/]+)[/]?(.*)')
220
221 def __init__(self, uri):
222 '''Initialization, parse S3 URL'''
223 try:
224 self.proto, self.bucket, self.path = S3URL.S3URL_PATTERN.match(uri).groups()
225 self.proto = 's3' # normalize s3n => s3
226 except:
227 raise InvalidArgument('Invalid S3 URI: %s' % uri)
228
229 def __str__(self):
230 '''Return the original S3 URL'''
231 return S3URL.combine(self.proto, self.bucket, self.path)
232
233 def get_fixed_path(self):
234 '''Get the fixed part of the path without wildcard'''
235 pi = self.path.split(PATH_SEP)
236 fi = []
237 for p in pi:
238 if '*' in p or '?' in p:
239 break
240 fi.append(p)
241 return PATH_SEP.join(fi)
242
243 @staticmethod
244 def combine(proto, bucket, path):
245 '''Combine each component and general a S3 url string, no path normalization
246 here. The path should not start with slash.
247 '''
248 return '%s://%s/%s' % (proto, bucket, path)
249
250 @staticmethod
251 def is_valid(uri):
252 '''Check if given uri is a valid S3 URL'''
253 return S3URL.S3URL_PATTERN.match(uri) != None
254
255 class BotoClient(object):
256 '''This is a bridge between s4cmd and boto3 library. All S3 method calls should go through this class.
257 The white list ALLOWED_CLIENT_METHODS lists those methods that are allowed. Also, EXTRA_CLIENT_PARAMS
258 is the list of S3 parameters that we can take from command-line argument and pass through to the API.
259 '''
260
261 # Encapsulate boto3 interface intercept all API calls.
262 boto3 = __import__('boto3') # version >= 1.3.1
263 botocore = __import__('botocore')
264
265 # Exported exceptions.
266 BotoError = boto3.exceptions.Boto3Error
267 ClientError = botocore.exceptions.ClientError
268 NoCredentialsError = botocore.exceptions.NoCredentialsError
269
270 # Exceptions that retries may work. May change in the future.
271 S3RetryableErrors = (
272 socket.timeout,
273 socket.error if IS_PYTHON2 else ConnectionError,
274 botocore.vendored.requests.packages.urllib3.exceptions.ReadTimeoutError,
275 botocore.exceptions.IncompleteReadError
276 )
277
278 # List of API functions we use in s4cmd.
279 ALLOWED_CLIENT_METHODS = [
280 'list_buckets',
281 'get_paginator',
282 'head_object',
283 'put_object',
284 'create_bucket',
285 'create_multipart_upload',
286 'upload_part',
287 'complete_multipart_upload',
288 'abort_multipart_upload',
289 'get_object',
290 'copy_object',
291 'delete_object',
292 'delete_objects',
293 'upload_part_copy'
294 ]
295
296 # List of parameters grabbed from http://boto3.readthedocs.io/en/latest/reference/services/s3.html
297 # Pass those parameters directly to boto3 low level API. Most of the parameters are not tested.
298 EXTRA_CLIENT_PARAMS = [
299 ("ACL", "string",
300 "The canned ACL to apply to the object."),
301 ("CacheControl", "string",
302 "Specifies caching behavior along the request/reply chain."),
303 ("ContentDisposition", "string",
304 "Specifies presentational information for the object."),
305 ("ContentEncoding", "string",
306 "Specifies what content encodings have been applied to the object and thus what decoding mechanisms must be applied to obtain the media-type referenced by the Content-Type header field."),
307 ("ContentLanguage", "string",
308 "The language the content is in."),
309 ("ContentMD5", "string",
310 "The base64-encoded 128-bit MD5 digest of the part data."),
311 ("ContentType", "string",
312 "A standard MIME type describing the format of the object data."),
313 ("CopySourceIfMatch", "string",
314 "Copies the object if its entity tag (ETag) matches the specified tag."),
315 ("CopySourceIfModifiedSince", "datetime",
316 "Copies the object if it has been modified since the specified time."),
317 ("CopySourceIfNoneMatch", "string",
318 "Copies the object if its entity tag (ETag) is different than the specified ETag."),
319 ("CopySourceIfUnmodifiedSince", "datetime",
320 "Copies the object if it hasn't been modified since the specified time."),
321 ("CopySourceRange", "string",
322 "The range of bytes to copy from the source object. The range value must use the form bytes=first-last, where the first and last are the zero-based byte offsets to copy. For example, bytes=0-9 indicates that you want to copy the first ten bytes of the source. You can copy a range only if the source object is greater than 5 GB."),
323 ("CopySourceSSECustomerAlgorithm", "string",
324 "Specifies the algorithm to use when decrypting the source object (e.g., AES256)."),
325 ("CopySourceSSECustomerKeyMD5", "string",
326 "Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. Amazon S3 uses this header for a message integrity check to ensure the encryption key was transmitted without error. Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required"),
327 ("CopySourceSSECustomerKey", "string",
328 "Specifies the customer-provided encryption key for Amazon S3 to use to decrypt the source object. The encryption key provided in this header must be one that was used when the source object was created."),
329 ("ETag", "string",
330 "Entity tag returned when the part was uploaded."),
331 ("Expires", "datetime",
332 "The date and time at which the object is no longer cacheable."),
333 ("GrantFullControl", "string",
334 "Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object."),
335 ("GrantReadACP", "string",
336 "Allows grantee to read the object ACL."),
337 ("GrantRead", "string",
338 "Allows grantee to read the object data and its metadata."),
339 ("GrantWriteACP", "string",
340 "Allows grantee to write the ACL for the applicable object."),
341 ("IfMatch", "string",
342 "Return the object only if its entity tag (ETag) is the same as the one specified, otherwise return a 412 (precondition failed)."),
343 ("IfModifiedSince", "datetime",
344 "Return the object only if it has been modified since the specified time, otherwise return a 304 (not modified)."),
345 ("IfNoneMatch", "string",
346 "Return the object only if its entity tag (ETag) is different from the one specified, otherwise return a 304 (not modified)."),
347 ("IfUnmodifiedSince", "datetime",
348 "Return the object only if it has not been modified since the specified time, otherwise return a 412 (precondition failed)."),
349 ("Metadata", "dict",
350 "A map (in json string) of metadata to store with the object in S3"),
351 ("MetadataDirective", "string",
352 "Specifies whether the metadata is copied from the source object or replaced with metadata provided in the request."),
353 ("MFA", "string",
354 "The concatenation of the authentication device's serial number, a space, and the value that is displayed on your authentication device."),
355 ("RequestPayer", "string",
356 "Confirms that the requester knows that she or he will be charged for the request. Bucket owners need not specify this parameter in their requests. Documentation on downloading objects from requester pays buckets can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html"),
357 ("ServerSideEncryption", "string",
358 "The Server-side encryption algorithm used when storing this object in S3 (e.g., AES256, aws:kms)."),
359 ("SSECustomerAlgorithm", "string",
360 "Specifies the algorithm to use to when encrypting the object (e.g., AES256)."),
361 ("SSECustomerKeyMD5", "string",
362 "Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. Amazon S3 uses this header for a message integrity check to ensure the encryption key was transmitted without error. Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required"),
363 ("SSECustomerKey", "string",
364 "Specifies the customer-provided encryption key for Amazon S3 to use in encrypting data. This value is used to store the object and then it is discarded; Amazon does not store the encryption key. The key must be appropriate for use with the algorithm specified in the x-amz-server-side-encryption-customer-algorithm header."),
365 ("SSEKMSKeyId", "string",
366 "Specifies the AWS KMS key ID to use for object encryption. All GET and PUT requests for an object protected by AWS KMS will fail if not made via SSL or using SigV4. Documentation on configuring any of the officially supported AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version"),
367 ("StorageClass", "string",
368 "The type of storage to use for the object. Defaults to 'STANDARD'."),
369 ("VersionId", "string",
370 "VersionId used to reference a specific version of the object."),
371 ("WebsiteRedirectLocation", "string",
372 "If the bucket is configured as a website, redirects requests for this object to another object in the same bucket or to an external URL. Amazon S3 stores the value of this header in the object metadata."),
373 ]
374
375 def __init__(self, opt, aws_access_key_id=None, aws_secret_access_key=None):
376 '''Initialize boto3 API bridge class. Calculate and cache all legal parameters
377 for each method we are going to call.
378 '''
379 self.opt = opt
380 if (aws_access_key_id is not None) and (aws_secret_access_key is not None):
381 self.client = self.boto3.client('s3',
382 aws_access_key_id=aws_access_key_id,
383 aws_secret_access_key=aws_secret_access_key,
384 endpoint_url=opt.endpoint_url)
385 else:
386 self.client = self.boto3.client('s3', endpoint_url=opt.endpoint_url)
387
388 # Cache the result so we don't have to recalculate.
389 self.legal_params = {}
390 for method in BotoClient.ALLOWED_CLIENT_METHODS:
391 self.legal_params[method] = self.get_legal_params(method)
392
393 def __getattribute__(self, method):
394 '''Intercept boto3 API call to inject our extra options.'''
395
396 if method in BotoClient.ALLOWED_CLIENT_METHODS:
397
398 def wrapped_method(*args, **kargs):
399 merged_kargs = self.merge_opt_params(method, kargs)
400 callStr = "%s(%s)" % ("S3APICALL " + method, ", ".join([repr(p) for p in args] + ["%s=%s" % (k, repr(v)) for (k, v) in list(kargs.items())]))
401 debug(">> %s", callStr)
402 ret = getattr(self.client, method)(*args, **merged_kargs)
403 debug("<< %s: %s", callStr, repr(ret))
404 return ret
405
406 return wrapped_method
407
408 return super(BotoClient, self).__getattribute__(method)
409
410 def get_legal_params(self, method):
411 '''Given a API name, list all legal parameters using boto3 service model.'''
412 if method not in self.client.meta.method_to_api_mapping:
413 # Injected methods. Ignore.
414 return []
415 api = self.client.meta.method_to_api_mapping[method]
416 shape = self.client.meta.service_model.operation_model(api).input_shape
417 if shape is None:
418 # No params needed for this API.
419 return []
420 return shape.members.keys()
421
422 def merge_opt_params(self, method, kargs):
423 '''Combine existing parameters with extra options supplied from command line
424 options. Carefully merge special type of parameter if needed.
425 '''
426 for key in self.legal_params[method]:
427 if not hasattr(self.opt, key) or getattr(self.opt, key) is None:
428 continue
429 if key in kargs and type(kargs[key]) == dict:
430 assert(type(getattr(self.opt, key)) == dict)
431 # Merge two dictionaries.
432 for k, v in getattr(self.opt, key).iteritems():
433 kargs[key][k] = v
434 else:
435 # Overwrite values.
436 kargs[key] = getattr(self.opt, key)
437
438 return kargs
439
440 @staticmethod
441 def add_options(parser):
442 '''Add the whole list of API parameters into optparse.'''
443 for param, param_type, param_doc in BotoClient.EXTRA_CLIENT_PARAMS:
444 parser.add_option('--API-' + param, help=param_doc, type=param_type, dest=param)
445
446 def close(self):
447 '''Close this client.'''
448 self.client = None
449
450 class TaskQueue(Queue.Queue):
451 '''Wrapper class to Queue.
452 Since we need to ensure that main thread is not blocked by child threads
453 and cannot be wake up by Ctrl-C interrupt, we have to override join()
454 method.
455 '''
456 def __init__(self):
457 Queue.Queue.__init__(self)
458 self.exc_info = None
459
460 def join(self):
461 '''Override original join() with a timeout and handle keyboard interrupt.'''
462 self.all_tasks_done.acquire()
463 try:
464 while self.unfinished_tasks:
465 self.all_tasks_done.wait(1000)
466
467 # Child thread has exceptions, fail main thread too.
468 if self.exc_info:
469 fail('[Thread Failure] ', exc_info=self.exc_info)
470 except KeyboardInterrupt:
471 raise Failure('Interrupted by user')
472 finally:
473 self.all_tasks_done.release()
474
475 def terminate(self, exc_info=None):
476 '''Terminate all threads by deleting the queue and forcing the child threads
477 to quit.
478 '''
479 if exc_info:
480 self.exc_info = exc_info
481 try:
482 while self.get_nowait():
483 self.task_done()
484 except Queue.Empty:
485 pass
486
487 class ThreadPool(object):
488 '''Utility class for thread pool.
489 This class needs to work with a utility class, which is derived from Worker.
490 '''
491
492 class Worker(threading.Thread):
493 '''Utility thread worker class.
494 This class handles all items in task queue and execute them. It also
495 handles runtime errors gracefully, and provides automatic retry.
496 '''
497 def __init__(self, pool):
498 '''Thread worker initalization.
499 Setup values and start threads right away.
500 '''
501 threading.Thread.__init__(self)
502 self.pool = pool
503 self.opt = pool.opt
504 self.daemon = True
505 self.start()
506
507 def run(self):
508 '''Main thread worker execution.
509 This function extract items from task queue and execute them accordingly.
510 It will retry tasks when encounter exceptions by putting the same item
511 back to the work queue.
512 '''
513 while True:
514 item = self.pool.tasks.get()
515 if not item:
516 break
517
518 try:
519 func_name, retry, args, kargs = item
520 self.__class__.__dict__[func_name](self, *args, **kargs)
521 except InvalidArgument as e:
522 self.pool.tasks.terminate(e)
523 fail('[Invalid Argument] ', exc_info=e)
524 except Failure as e:
525 self.pool.tasks.terminate(e)
526 fail('[Runtime Failure] ', exc_info=e)
527 except OSError as e:
528 self.pool.tasks.terminate(e)
529 fail('[OSError] %d: %s' % (e.errno, e.strerror))
530 except BotoClient.S3RetryableErrors as e:
531 if retry >= self.opt.retry:
532 self.pool.tasks.terminate(e)
533 fail('[Runtime Exception] ', exc_info=e, stacktrace=True)
534 else:
535 # Show content of exceptions.
536 error(e)
537
538 time.sleep(self.opt.retry_delay)
539 self.pool.tasks.put((func_name, retry + 1, args, kargs))
540 except Exception as e:
541 self.pool.tasks.terminate(e)
542 fail('[Exception] ', exc_info=e)
543 finally:
544 self.pool.processed()
545 self.pool.tasks.task_done()
546
547 def __init__(self, thread_class, opt):
548 '''Constructor of ThreadPool.
549 Create workers and pool will automatically inherit all methods from
550 thread_class by redirecting calls through __getattribute__().
551 '''
552 self.opt = opt
553 self.tasks = TaskQueue()
554 self.processed_tasks = 0
555 self.thread_class = thread_class
556 self.workers = []
557 for i in range(opt.num_threads):
558 self.workers.append(thread_class(self))
559
560 def __enter__(self):
561 '''Utility function for with statement'''
562 return self
563
564 def __exit__(self, exc_type, exc_value, traceback):
565 '''Utility function for with statement, wait for completion'''
566 self.join()
567 return isinstance(exc_value, TypeError)
568
569 def __getattribute__(self, name):
570 '''Special attribute accessor to add tasks into task queue.
571 Here if we found a function not in ThreadPool, we will try
572 to see if we have a function in the utility class. If so, we
573 add the function call into task queue.
574 '''
575 try:
576 attr = super(ThreadPool, self).__getattribute__(name)
577 except AttributeError as e:
578 if name in self.thread_class.__dict__:
579 # Here we masquerade the original function with add_task(). So the
580 # function call will be put into task queue.
581 def deferred_task(*args, **kargs):
582 self.add_task(name, *args, **kargs)
583 attr = deferred_task
584 else:
585 raise AttributeError('Unable to resolve %s' % name)
586 return attr
587
588 def add_task(self, func_name, *args, **kargs):
589 '''Utility function to add a single task into task queue'''
590 self.tasks.put((func_name, 0, args, kargs))
591
592 def join(self):
593 '''Utility function to wait all tasks to complete'''
594 self.tasks.join()
595
596 # Force each thread to break loop.
597 for worker in self.workers:
598 self.tasks.put(None)
599
600 # Wait for all thread to terminate.
601 for worker in self.workers:
602 worker.join()
603 worker.s3 = None
604
605 @synchronized
606 def processed(self):
607 '''Increase the processed task counter and show progress message'''
608 self.processed_tasks += 1
609 qsize = self.tasks.qsize()
610 if qsize > 0:
611 progress('[%d task(s) completed, %d remaining, %d thread(s)]', self.processed_tasks, qsize, len(self.workers))
612 else:
613 progress('[%d task(s) completed, %d thread(s)]', self.processed_tasks, len(self.workers))
614
615 class S3Handler(object):
616 '''Core S3 class.
617 This class provide the functions for all operations. It will start thread
618 pool to execute tasks generated by each operation. See ThreadUtil for
619 more details about the tasks.
620 '''
621
622 S3_KEYS = None
623
624 @staticmethod
625 def s3_keys_from_env():
626 '''Retrieve S3 access keys from the environment, or None if not present.'''
627 env = os.environ
628 if S3_ACCESS_KEY_NAME in env and S3_SECRET_KEY_NAME in env:
629 keys = (env[S3_ACCESS_KEY_NAME], env[S3_SECRET_KEY_NAME])
630 debug("read S3 keys from environment")
631 return keys
632 else:
633 return None
634
635 @staticmethod
636 def s3_keys_from_cmdline(opt):
637 '''Retrieve S3 access keys from the command line, or None if not present.'''
638 if opt.access_key != None and opt.secret_key != None:
639 keys = (opt.access_key, opt.secret_key)
640 debug("read S3 keys from commandline")
641 return keys
642 else:
643 return None
644
645 @staticmethod
646 def s3_keys_from_s3cfg(opt):
647 '''Retrieve S3 access key settings from s3cmd's config file, if present; otherwise return None.'''
648 try:
649 if opt.s3cfg != None:
650 s3cfg_path = "%s" % opt.s3cfg
651 else:
652 s3cfg_path = "%s/.s3cfg" % os.environ["HOME"]
653 if not os.path.exists(s3cfg_path):
654 return None
655 config = ConfigParser.ConfigParser()
656 config.read(s3cfg_path)
657 keys = config.get("default", "access_key"), config.get("default", "secret_key")
658 debug("read S3 keys from $HOME/.s3cfg file")
659 return keys
660 except Exception as e:
661 info("could not read S3 keys from %s file; skipping (%s)", s3cfg_path, e)
662 return None
663
664 @staticmethod
665 def init_s3_keys(opt):
666 '''Initialize s3 access keys from environment variable or s3cfg config file.'''
667 S3Handler.S3_KEYS = S3Handler.s3_keys_from_cmdline(opt) or S3Handler.s3_keys_from_env() \
668 or S3Handler.s3_keys_from_s3cfg(opt)
669
670 def __init__(self, opt):
671 '''Constructor, connect to S3 store'''
672 self.s3 = None
673 self.opt = opt
674 self.connect()
675
676 def __del__(self):
677 '''Destructor, stop s3 connection'''
678 self.s3 = None
679
680 def connect(self):
681 '''Connect to S3 storage'''
682 try:
683 if S3Handler.S3_KEYS:
684 self.s3 = BotoClient(self.opt, S3Handler.S3_KEYS[0], S3Handler.S3_KEYS[1])
685 else:
686 self.s3 = BotoClient(self.opt)
687 except Exception as e:
688 raise RetryFailure('Unable to connect to s3: %s' % e)
689
690 @log_calls
691 def list_buckets(self):
692 '''List all buckets'''
693 result = []
694 for bucket in self.s3.list_buckets().get('Buckets') or []:
695 result.append({
696 'name': S3URL.combine('s3', bucket['Name'], ''),
697 'is_dir': True,
698 'size': 0,
699 'last_modified': bucket['CreationDate']
700 })
701 return result
702
703 @log_calls
704 def s3walk(self, basedir, show_dir=None):
705 '''Walk through a S3 directory. This function initiate a walk with a basedir.
706 It also supports multiple wildcards.
707 '''
708 # Provide the default value from command line if no override.
709 if not show_dir:
710 show_dir = self.opt.show_dir
711
712 # trailing slash normalization, this is for the reason that we want
713 # ls 's3://foo/bar/' has the same result as 's3://foo/bar'. Since we
714 # call partial_match() to check wildcards, we need to ensure the number
715 # of slashes stays the same when we do this.
716 if basedir[-1] == PATH_SEP:
717 basedir = basedir[0:-1]
718
719 s3url = S3URL(basedir)
720 result = []
721
722 pool = ThreadPool(ThreadUtil, self.opt)
723 pool.s3walk(s3url, s3url.get_fixed_path(), s3url.path, result)
724 pool.join()
725
726 # automatic directory detection
727 if not show_dir and len(result) == 1 and result[0]['is_dir']:
728 path = result[0]['name']
729 s3url = S3URL(path)
730 result = []
731 pool = ThreadPool(ThreadUtil, self.opt)
732 pool.s3walk(s3url, s3url.get_fixed_path(), s3url.path, result)
733 pool.join()
734
735 def compare(x, y):
736 '''Comparator for ls output'''
737 result = -cmp(x['is_dir'], y['is_dir'])
738 if result != 0:
739 return result
740 return cmp(x['name'], y['name'])
741 return sorted(result, key=cmp_to_key(compare))
742
743 @log_calls
744 def local_walk(self, basedir):
745 '''Walk through local directories from root basedir'''
746 result = []
747
748 for root, dirs, files in os.walk(basedir):
749 for f in files:
750 result.append(os.path.join(root, f))
751 return result
752
753 @log_calls
754 def get_basename(self, path):
755 '''Unix style basename.
756 This fuction will return 'bar' for '/foo/bar/' instead of empty string.
757 It is used to normalize the input trailing slash.
758 '''
759 if path[-1] == PATH_SEP:
760 path = path[0:-1]
761 return os.path.basename(path)
762
763 def source_expand(self, source):
764 '''Expand the wildcards for an S3 path. This emulates the shall expansion
765 for wildcards if the input is local path.
766 '''
767 result = []
768
769 if not isinstance(source, list):
770 source = [source]
771
772 for src in source:
773 # XXX Hacky: We need to disable recursive when we expand the input
774 # parameters, need to pass this as an override parameter if
775 # provided.
776 tmp = self.opt.recursive
777 self.opt.recursive = False
778 result += [f['name'] for f in self.s3walk(src, True)]
779 self.opt.recursive = tmp
780
781 if (len(result) == 0) and (not self.opt.ignore_empty_source):
782 fail("[Runtime Failure] Source doesn't exist.")
783
784 return result
785
786 @log_calls
787 def put_single_file(self, pool, source, target):
788 '''Upload a single file or a directory by adding a task into queue'''
789 if os.path.isdir(source):
790 if self.opt.recursive:
791 for f in (f for f in self.local_walk(source) if not os.path.isdir(f)):
792 target_url = S3URL(target)
793 # deal with ./ or ../ here by normalizing the path.
794 joined_path = os.path.normpath(os.path.join(target_url.path, os.path.relpath(f, source)))
795 pool.upload(f, S3URL.combine('s3', target_url.bucket, joined_path))
796 else:
797 message('omitting directory "%s".' % source)
798 else:
799 pool.upload(source, target)
800
801 @log_calls
802 def put_files(self, source, target):
803 '''Upload files to S3.
804 This function can handle multiple file upload if source is a list.
805 Also, it works for recursive mode which copy all files and keep the
806 directory structure under the given source directory.
807 '''
808 pool = ThreadPool(ThreadUtil, self.opt)
809 if not isinstance(source, list):
810 source = [source]
811
812 if target[-1] == PATH_SEP:
813 for src in source:
814 self.put_single_file(pool, src, os.path.join(target, self.get_basename(src)))
815 else:
816 if len(source) == 1:
817 self.put_single_file(pool, source[0], target)
818 else:
819 raise Failure('Target "%s" is not a directory (with a trailing slash).' % target)
820
821 pool.join()
822
823 @log_calls
824 def create_bucket(self, source):
825 '''Use the create_bucket API to create a new bucket'''
826 s3url = S3URL(source)
827
828 message('Creating %s', source)
829 if not self.opt.dry_run:
830 resp = self.s3.create_bucket(Bucket=s3url.bucket)
831 if resp['ResponseMetadata']["HTTPStatusCode"] == 200:
832 message('Done.')
833 else:
834 raise Failure('Unable to create bucket %s' % source)
835
836
837 @log_calls
838 def update_privilege(self, obj, target):
839 '''Get privileges from metadata of the source in s3, and apply them to target'''
840 if 'privilege' in obj['Metadata']:
841 os.chmod(target, int(obj['Metadata']['privilege'], 8))
842
843 @log_calls
844 def print_files(self, source):
845 '''Print out a series of files'''
846 sources = self.source_expand(source)
847
848 for source in sources:
849 s3url = S3URL(source)
850 response = self.s3.get_object(Bucket=s3url.bucket, Key=s3url.path)
851 message('%s', response['Body'].read())
852
853 @log_calls
854 def get_single_file(self, pool, source, target):
855 '''Download a single file or a directory by adding a task into queue'''
856 if source[-1] == PATH_SEP:
857 if self.opt.recursive:
858 basepath = S3URL(source).path
859 for f in (f for f in self.s3walk(source) if not f['is_dir']):
860 pool.download(f['name'], os.path.join(target, os.path.relpath(S3URL(f['name']).path, basepath)))
861 else:
862 message('omitting directory "%s".' % source)
863 else:
864 pool.download(source, target)
865
866 @log_calls
867 def get_files(self, source, target):
868 '''Download files.
869 This function can handle multiple files if source S3 URL has wildcard
870 characters. It also handles recursive mode by download all files and
871 keep the directory structure.
872 '''
873 pool = ThreadPool(ThreadUtil, self.opt)
874 source = self.source_expand(source)
875
876 if os.path.isdir(target):
877 for src in source:
878 self.get_single_file(pool, src, os.path.join(target, self.get_basename(S3URL(src).path)))
879 else:
880 if len(source) > 1:
881 raise Failure('Target "%s" is not a directory.' % target)
882 # Get file if it exists on s3 otherwise do nothing
883 elif len(source) == 1:
884 self.get_single_file(pool, source[0], target)
885 else:
886 #Source expand may return empty list only if ignore-empty-source is set to true
887 pass
888
889 pool.join()
890
891 @log_calls
892 def delete_removed_files(self, source, target):
893 '''Remove remote files that are not present in the local source.
894 (Obsolete) It is used for old sync command now.
895 '''
896 message("Deleting files found in %s and not in %s", source, target)
897 if os.path.isdir(source):
898 unecessary = []
899 basepath = S3URL(target).path
900 for f in [f for f in self.s3walk(target) if not f['is_dir']]:
901 local_name = os.path.join(source, os.path.relpath(S3URL(f['name']).path, basepath))
902 if not os.path.isfile(local_name):
903 message("%s not found locally, adding to delete queue", local_name)
904 unecessary.append(f['name'])
905 if len(unecessary) > 0:
906 pool = ThreadPool(ThreadUtil, self.opt)
907 for del_file in unecessary:
908 pool.delete(del_file)
909 pool.join()
910 else:
911 raise Failure('Source "%s" is not a directory.' % target)
912
913 @log_calls
914 def cp_single_file(self, pool, source, target, delete_source):
915 '''Copy a single file or a directory by adding a task into queue'''
916 if source[-1] == PATH_SEP:
917 if self.opt.recursive:
918 basepath = S3URL(source).path
919 for f in (f for f in self.s3walk(source) if not f['is_dir']):
920 pool.copy(f['name'], os.path.join(target, os.path.relpath(S3URL(f['name']).path, basepath)), delete_source=delete_source)
921 else:
922 message('omitting directory "%s".' % source)
923 else:
924 pool.copy(source, target, delete_source=delete_source)
925
926 @log_calls
927 def cp_files(self, source, target, delete_source=False):
928 '''Copy files
929 This function can handle multiple files if source S3 URL has wildcard
930 characters. It also handles recursive mode by copying all files and
931 keep the directory structure.
932 '''
933 pool = ThreadPool(ThreadUtil, self.opt)
934 source = self.source_expand(source)
935
936 if target[-1] == PATH_SEP:
937 for src in source:
938 self.cp_single_file(pool, src, os.path.join(target, self.get_basename(S3URL(src).path)), delete_source)
939 else:
940 if len(source) > 1:
941 raise Failure('Target "%s" is not a directory (with a trailing slash).' % target)
942 # Copy file if it exists otherwise do nothing
943 elif len(source) == 1:
944 self.cp_single_file(pool, source[0], target, delete_source)
945 else:
946 # Source expand may return empty list only if ignore-empty-source is set to true
947 pass
948
949 pool.join()
950
951 @log_calls
952 def del_files(self, source):
953 '''Delete files on S3'''
954 src_files = []
955 for obj in self.s3walk(source):
956 if not obj['is_dir']: # ignore directories
957 src_files.append(obj['name'])
958
959 pool = ThreadPool(ThreadUtil, self.opt)
960 pool.batch_delete(src_files)
961 pool.join()
962
963 @log_calls
964 def relative_dir_walk(self, dir):
965 '''Generic version of directory walk. Return file list without base path
966 for comparison.
967 '''
968 result = []
969
970 if S3URL.is_valid(dir):
971 basepath = S3URL(dir).path
972 for f in (f for f in self.s3walk(dir) if not f['is_dir']):
973 result.append(os.path.relpath(S3URL(f['name']).path, basepath))
974 else:
975 for f in (f for f in self.local_walk(dir) if not os.path.isdir(f)):
976 result.append(os.path.relpath(f, dir))
977
978 return result
979
980 @log_calls
981 def dsync_files(self, source, target):
982 '''Sync directory to directory.'''
983 src_s3_url = S3URL.is_valid(source)
984 dst_s3_url = S3URL.is_valid(target)
985
986 source_list = self.relative_dir_walk(source)
987 if len(source_list) == 0 or '.' in source_list:
988 raise Failure('Sync command need to sync directory to directory.')
989
990 sync_list = [(os.path.join(source, f), os.path.join(target, f)) for f in source_list]
991
992 pool = ThreadPool(ThreadUtil, self.opt)
993 if src_s3_url and not dst_s3_url:
994 for src, dest in sync_list:
995 pool.download(src, dest)
996 elif not src_s3_url and dst_s3_url:
997 for src, dest in sync_list:
998 pool.upload(src, dest)
999 elif src_s3_url and dst_s3_url:
1000 for src, dest in sync_list:
1001 pool.copy(src, dest)
1002 else:
1003 raise InvalidArgument('Cannot sync two local directories.')
1004 pool.join()
1005
1006 if self.opt.delete_removed:
1007 target_list = self.relative_dir_walk(target)
1008 remove_list = [os.path.join(target, f) for f in (set(target_list) - set(source_list))]
1009
1010 if S3URL.is_valid(target):
1011 pool = ThreadPool(ThreadUtil, self.opt)
1012 pool.batch_delete(remove_list)
1013 pool.join()
1014 else:
1015 for f in remove_list:
1016 try:
1017 os.unlink(f)
1018 message('Delete %s', f)
1019 except:
1020 pass
1021
1022 @log_calls
1023 def sync_files(self, source, target):
1024 '''Sync files to S3. Does implement deletions if syncing TO s3.
1025 Currently identical to get/put -r -f --sync-check with exception of deletions.
1026 '''
1027 src_s3_url = S3URL.is_valid(source)
1028 dst_s3_url = S3URL.is_valid(target)
1029
1030 if src_s3_url and not dst_s3_url:
1031 self.get_files(source, target)
1032 elif not src_s3_url and dst_s3_url:
1033 self.put_files(source, target)
1034 if self.opt.delete_removed:
1035 self.delete_removed_files(source, target)
1036 elif src_s3_url and dst_s3_url:
1037 self.cp_files(source, target)
1038 else:
1039 raise InvalidArgument('No S3 URI provided')
1040
1041 @log_calls
1042 def size(self, source):
1043 '''Get the size component of the given s3url. If it is a
1044 directory, combine the sizes of all the files under
1045 that directory. Subdirectories will not be counted unless
1046 --recursive option is set.
1047 '''
1048 result = []
1049 for src in self.source_expand(source):
1050 size = 0
1051 for f in self.s3walk(src):
1052 size += f['size']
1053 result.append((src, size))
1054
1055 return result
1056
1057 class LocalMD5Cache(object):
1058 '''Stub class to provide lazy evaluation MD5.'''
1059
1060 def __init__(self, filename):
1061 '''Initialize md5 cache object.'''
1062 self.filename = filename
1063 self.md5 = None
1064
1065 def file_hash(self, filename, block_size=2**20):
1066 '''Calculate MD5 hash code for a local file'''
1067 m = hashlib.md5()
1068 with open(filename, 'rb') as f:
1069 while True:
1070 data = f.read(block_size)
1071 if not data:
1072 break
1073 m.update(data)
1074 return m.hexdigest()
1075
1076 def get_md5(self):
1077 '''Get or calculate MD5 value of the local file.'''
1078 if self.md5 is None:
1079 self.md5 = self.file_hash(self.filename)
1080 return self.md5
1081
1082 class ThreadUtil(S3Handler, ThreadPool.Worker):
1083 '''Thread workers for S3 operations.
1084 This class contains all thread workers for S3 operations.
1085
1086 1) Expand source into [source] list if it contains wildcard characters '*' or '?'.
1087 This is done by shell, but we need to do this ourselves for S3 path.
1088 Basically we see [source] as the first-class source list.
1089
1090 2) Run the following algorithm:
1091 if target is directory? (S3 path uses trailing slash to determine this)
1092 for src in source:
1093 copy src to target/src.basename
1094 else
1095 if source has only one element?
1096 copy src to target
1097 else
1098 error "target should be a directory"!
1099
1100 3) Copy operations should work for both single file and directory:
1101 def copy(src, target)
1102 if src is a directory?
1103 copy the whole directory recursively to target
1104 else
1105 copy the file src to target
1106 '''
1107
1108 def __init__(self, pool):
1109 '''Constructor'''
1110 S3Handler.__init__(self, pool.opt)
1111 ThreadPool.Worker.__init__(self, pool)
1112
1113 @log_calls
1114 def mkdirs(self, target):
1115 '''Ensure all directories are created for a given target file.'''
1116 path = os.path.dirname(target)
1117 if path and path != PATH_SEP and not os.path.isdir(path):
1118 # Multi-threading means there will be intervleaved execution
1119 # between the check and creation of the directory.
1120 try:
1121 os.makedirs(path)
1122 except OSError as ose:
1123 if ose.errno != errno.EEXIST:
1124 raise Failure('Unable to create directory (%s)' % (path,))
1125
1126 @log_calls
1127 def sync_check(self, md5cache, remoteKey):
1128 '''Check MD5 for a local file and a remote file.
1129 Return True if they have the same md5 hash, otherwise False.
1130 '''
1131 if not remoteKey:
1132 return False
1133 if not os.path.exists(md5cache.filename):
1134 return False
1135 localmd5 = md5cache.get_md5()
1136
1137 # check multiple md5 locations
1138 return ('ETag' in remoteKey and remoteKey['ETag'] == '"%s"' % localmd5) or \
1139 ('md5' in remoteKey and remoteKey['md5'] == localmd5) or \
1140 ('md5' in remoteKey['Metadata'] and remoteKey['Metadata']['md5'] == localmd5)
1141
1142 @log_calls
1143 def partial_match(self, path, filter_path):
1144 '''Partially match a path and a filter_path with wildcards.
1145 This function will return True if this path partially match a filter path.
1146 This is used for walking through directories with multiple level wildcard.
1147 '''
1148 if not path or not filter_path:
1149 return True
1150
1151 # trailing slash normalization
1152 if path[-1] == PATH_SEP:
1153 path = path[0:-1]
1154 if filter_path[-1] == PATH_SEP:
1155 filter_path += '*'
1156
1157 pi = path.split(PATH_SEP)
1158 fi = filter_path.split(PATH_SEP)
1159
1160 # Here, if we are in recursive mode, we allow the pi to be longer than fi.
1161 # Otherwise, length of pi should be equal or less than the lenght of fi.
1162 min_len = min(len(pi), len(fi))
1163 matched = fnmatch.fnmatch(PATH_SEP.join(pi[0:min_len]), PATH_SEP.join(fi[0:min_len]))
1164 return matched and (self.opt.recursive or len(pi) <= len(fi))
1165
1166 @log_calls
1167 def s3walk(self, s3url, s3dir, filter_path, result):
1168 '''Thread worker for s3walk.
1169 Recursively walk into all subdirectories if they still match the filter
1170 path partially.
1171 '''
1172
1173 paginator = self.s3.get_paginator('list_objects')
1174 filter_path_level = filter_path.count(PATH_SEP)
1175
1176 for page in paginator.paginate(Bucket=s3url.bucket, Prefix=s3dir, Delimiter=PATH_SEP, PaginationConfig={'PageSize': 1000}):
1177 # Get subdirectories first.
1178 for obj in page.get('CommonPrefixes') or []:
1179 obj_name = obj['Prefix']
1180
1181 if not self.partial_match(obj_name, filter_path):
1182 continue
1183
1184 if self.opt.recursive or (obj_name.count(PATH_SEP) != filter_path_level + 1):
1185 self.pool.s3walk(s3url, obj_name, filter_path, result)
1186 else:
1187 self.conditional(result, {
1188 'name': S3URL.combine(s3url.proto, s3url.bucket, obj_name),
1189 'is_dir': True,
1190 'size': 0,
1191 'last_modified': None
1192 })
1193
1194 # Then get all items in this folder.
1195 for obj in page.get('Contents') or []:
1196 obj_name = obj['Key']
1197 if not self.partial_match(obj_name, filter_path):
1198 continue
1199
1200 if self.opt.recursive or obj_name.count(PATH_SEP) == filter_path_level:
1201 self.conditional(result, {
1202 'name': S3URL.combine(s3url.proto, s3url.bucket, obj_name),
1203 'is_dir': False,
1204 'size': obj['Size'],
1205 'last_modified': obj['LastModified']
1206 })
1207
1208 def conditional(self, result, obj):
1209 '''Check all file item with given conditions.'''
1210 fileonly = (self.opt.last_modified_before is not None) or (self.opt.last_modified_after is not None)
1211
1212 if obj['is_dir']:
1213 if not fileonly:
1214 result.append(obj)
1215 return
1216
1217 if (self.opt.last_modified_before is not None) and obj['last_modified'] >= self.opt.last_modified_before:
1218 return
1219
1220 if (self.opt.last_modified_after is not None) and obj['last_modified'] <= self.opt.last_modified_after:
1221 return
1222
1223 result.append(obj)
1224
1225 class MultipartItem:
1226 '''Utility class for multiple part upload/download.
1227 This class is used to keep track of a single upload/download file, so
1228 that we can initialize/finalize a file when needed.
1229 '''
1230 def __init__(self, id):
1231 '''Constructor.
1232 An unique identify for a single donwload/upload file.
1233 - Download: the temporary file name.
1234 - Upload: the id of multipart upload provided by S3.
1235 '''
1236 self.id = id
1237 self.parts = []
1238 self.total = -1
1239
1240 @synchronized
1241 def complete(self, part):
1242 '''Increase the parts list, and see if the file is completely
1243 uploaded or downloaded.
1244 '''
1245 self.parts.append(part)
1246 return (len(self.parts) == self.total)
1247
1248 @synchronized
1249 def sorted_parts(self):
1250 '''Obtain a sorted part list'''
1251 # Sort part list based on AWS requirement when completed.
1252 # See InvalidPartOrder in http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadComplete.html
1253 def compare(x, y):
1254 '''Comparator for part list'''
1255 return cmp(x['PartNumber'], y['PartNumber'])
1256
1257 return sorted(self.parts, key=cmp_to_key(compare))
1258
1259 @log_calls
1260 def get_file_splits(self, id, source, target, fsize, splitsize):
1261 '''Get file splits for upload/download/copy operation.'''
1262 pos = 0
1263 part = 1 # S3 part id starts from 1
1264 mpi = ThreadUtil.MultipartItem(id)
1265 splits = []
1266
1267 while pos < fsize:
1268 chunk = min(splitsize, fsize - pos)
1269 assert(chunk > 0)
1270 splits.append((source, target, mpi, pos, chunk, part))
1271 part += 1
1272 pos += chunk
1273 mpi.total = len(splits)
1274
1275 return splits
1276
1277 @log_calls
1278 def get_file_privilege(self, source):
1279 '''Get privileges of a local file'''
1280 try:
1281 return str(oct(os.stat(source).st_mode)[-3:])
1282 except Exception as e:
1283 raise Failure('Could not get stat for %s, error_message = %s', source, e)
1284
1285 @log_calls
1286 def lookup(self, s3url):
1287 '''Get the s3 object with the S3 URL. Return None if not exist.'''
1288 try:
1289 return self.s3.head_object(Bucket=s3url.bucket, Key=s3url.path)
1290 except BotoClient.ClientError as e:
1291 if e.response['ResponseMetadata']['HTTPStatusCode'] == 404:
1292 return None
1293 else:
1294 raise e
1295
1296 @log_calls
1297 def read_file_chunk(self, source, pos, chunk):
1298 '''Read local file chunk'''
1299 if chunk==0:
1300 return StringIO()
1301 data = None
1302 with open(source, 'rb') as f:
1303 f.seek(pos)
1304 data = f.read(chunk)
1305 if not data:
1306 raise Failure('Unable to read data from source: %s' % source)
1307 return StringIO(data)
1308
1309 @log_calls
1310 def upload(self, source, target, mpi=None, pos=0, chunk=0, part=0):
1311 '''Thread worker for upload operation.'''
1312 s3url = S3URL(target)
1313 obj = self.lookup(s3url)
1314
1315 # Initialization: Set up multithreaded uploads.
1316 if not mpi:
1317 fsize = os.path.getsize(source)
1318 md5cache = LocalMD5Cache(source)
1319
1320 # optional checks
1321 if self.opt.dry_run:
1322 message('%s => %s', source, target)
1323 return
1324 elif self.opt.sync_check and self.sync_check(md5cache, obj):
1325 message('%s => %s (synced)', source, target)
1326 return
1327 elif not self.opt.force and obj:
1328 raise Failure('File already exists: %s' % target)
1329
1330 if fsize < self.opt.max_singlepart_upload_size:
1331 data = self.read_file_chunk(source, 0, fsize)
1332 self.s3.put_object(Bucket=s3url.bucket,
1333 Key=s3url.path,
1334 Body=data,
1335 Metadata={'md5': md5cache.get_md5(),
1336 'privilege': self.get_file_privilege(source)})
1337 message('%s => %s', source, target)
1338 return
1339
1340 # Here we need to have our own md5 value because multipart upload calculates
1341 # different md5 values.
1342 response = self.s3.create_multipart_upload(Bucket=s3url.bucket,
1343 Key=s3url.path,
1344 Metadata={'md5': md5cache.get_md5(),
1345 'privilege': self.get_file_privilege(source)})
1346 upload_id = response['UploadId']
1347
1348 for args in self.get_file_splits(upload_id, source, target, fsize, self.opt.multipart_split_size):
1349 self.pool.upload(*args)
1350 return
1351
1352 data = self.read_file_chunk(source, pos, chunk)
1353 response = self.s3.upload_part(Bucket=s3url.bucket, Key=s3url.path, UploadId=mpi.id, Body=data, PartNumber=part)
1354
1355 # Finalize
1356 if mpi.complete({'ETag': response['ETag'], 'PartNumber': part}):
1357 try:
1358 self.s3.complete_multipart_upload(Bucket=s3url.bucket, Key=s3url.path, UploadId=mpi.id, MultipartUpload={'Parts': mpi.sorted_parts()})
1359 message('%s => %s', source, target)
1360 except Exception as e:
1361 message('Unable to complete upload: %s', str(e))
1362 self.s3.abort_multipart_upload(Bucket=s3url.bucket, Key=s3url.path, UploadId=mpi.id)
1363 raise RetryFailure('Upload failed: Unable to complete upload %s.' % source)
1364
1365 @log_calls
1366 def _verify_file_size(self, obj, downloaded_file):
1367 '''Verify the file size of the downloaded file.'''
1368 file_size = os.path.getsize(downloaded_file)
1369 if int(obj['ContentLength']) != file_size:
1370 raise RetryFailure('Downloaded file size inconsistent: %s' % (repr(obj)))
1371
1372 @log_calls
1373 def write_file_chunk(self, target, pos, chunk, body):
1374 '''Write local file chunk'''
1375 fd = os.open(target, os.O_CREAT | os.O_WRONLY)
1376 try:
1377 os.lseek(fd, pos, os.SEEK_SET)
1378 data = body.read(chunk)
1379 num_bytes_written = os.write(fd, data)
1380 if(num_bytes_written != len(data)):
1381 raise RetryFailure('Number of bytes written inconsistent: %s != %s' % (num_bytes_written, sys.getsizeof(data)))
1382 finally:
1383 os.close(fd)
1384
1385 @log_calls
1386 def download(self, source, target, mpi=None, pos=0, chunk=0, part=0):
1387 '''Thread worker for download operation.'''
1388 s3url = S3URL(source)
1389 obj = self.lookup(s3url)
1390 if obj is None:
1391 raise Failure('The obj "%s" does not exists.' % (s3url.path,))
1392
1393 # Initialization: Set up multithreaded downloads.
1394 if not mpi:
1395 # optional checks
1396 if self.opt.dry_run:
1397 message('%s => %s', source, target)
1398 return
1399 elif self.opt.sync_check and self.sync_check(LocalMD5Cache(target), obj):
1400 message('%s => %s (synced)', source, target)
1401 return
1402 elif not self.opt.force and os.path.exists(target):
1403 raise Failure('File already exists: %s' % target)
1404
1405 fsize = int(obj['ContentLength'])
1406
1407 # Small file optimization.
1408 if fsize < self.opt.max_singlepart_download_size:
1409 # Create a single part to chain back main download operation.
1410 mpi = ThreadUtil.MultipartItem(tempfile_get(target))
1411 mpi.total = 1
1412 pos = 0
1413 chunk = fsize
1414 # Continue as one part download.
1415 else:
1416 # Here we use temp filename as the id of mpi.
1417 for args in self.get_file_splits(tempfile_get(target), source, target, fsize, self.opt.multipart_split_size):
1418 self.pool.download(*args)
1419 return
1420
1421 tempfile = mpi.id
1422 if self.opt.recursive:
1423 self.mkdirs(tempfile)
1424
1425 # Download part of the file, range is inclusive.
1426 response = self.s3.get_object(Bucket=s3url.bucket, Key=s3url.path, Range='bytes=%d-%d' % (pos, pos + chunk - 1))
1427 self.write_file_chunk(tempfile, pos, chunk, response['Body'])
1428
1429 # Finalize
1430 if mpi.complete({'PartNumber': part}):
1431 try:
1432 self.update_privilege(obj, tempfile)
1433 self._verify_file_size(obj, tempfile)
1434 tempfile_set(tempfile, target)
1435 message('%s => %s', source, target)
1436 except Exception as e:
1437 # Note that we don't retry in this case, because
1438 # We are going to remove the temp file, and if we
1439 # retry here with original parameters (wrapped in
1440 # the task item), it would fail anyway
1441 tempfile_set(tempfile, None)
1442 raise Failure('Download Failure: %s, Source: %s.' % (e.message, source))
1443
1444 @log_calls
1445 def copy(self, source, target, mpi=None, pos=0, chunk=0, part=0, delete_source=False):
1446 '''Copy a single file from source to target using boto S3 library.'''
1447
1448 if self.opt.dry_run:
1449 message('%s => %s' % (source, target))
1450 return
1451
1452 source_url = S3URL(source)
1453 target_url = S3URL(target)
1454
1455 if not mpi:
1456 obj = self.lookup(source_url)
1457 fsize = int(obj['ContentLength'])
1458
1459 if fsize < self.opt.max_singlepart_copy_size:
1460 self.s3.copy_object(Bucket=target_url.bucket, Key=target_url.path,
1461 CopySource={'Bucket': source_url.bucket, 'Key': source_url.path})
1462
1463 message('%s => %s' % (source, target))
1464 if delete_source:
1465 self.delete(source)
1466
1467 return
1468
1469 response = self.s3.create_multipart_upload(Bucket=target_url.bucket,
1470 Key=target_url.path,
1471 Metadata=obj['Metadata'])
1472 upload_id = response['UploadId']
1473
1474 for args in self.get_file_splits(upload_id, source, target, fsize, self.opt.multipart_split_size):
1475 self.pool.copy(*args, delete_source=delete_source)
1476 return
1477
1478 response = self.s3.upload_part_copy(Bucket=target_url.bucket,
1479 Key=target_url.path,
1480 CopySource={'Bucket': source_url.bucket, 'Key': source_url.path},
1481 CopySourceRange='bytes=%d-%d' % (pos, pos + chunk - 1),
1482 UploadId=mpi.id,
1483 PartNumber=part)
1484
1485 if mpi.complete({'ETag': response['CopyPartResult']['ETag'], 'PartNumber': part}):
1486 try:
1487 # Finalize copy operation.
1488 self.s3.complete_multipart_upload(Bucket=target_url.bucket, Key=target_url.path, UploadId=mpi.id, MultipartUpload={'Parts': mpi.sorted_parts()})
1489
1490 if delete_source:
1491 self.delete(source)
1492
1493 message('%s => %s' % (source, target))
1494 except Exception as e:
1495 message('Unable to complete upload: %s', str(e))
1496 self.s3.abort_multipart_upload(Bucket=source_url.bucket, Key=source_url.path, UploadId=mpi.id)
1497 raise RetryFailure('Copy failed: Unable to complete copy %s.' % source)
1498
1499 @log_calls
1500 def delete(self, source):
1501 '''Thread worker for download operation.'''
1502 s3url = S3URL(source)
1503
1504 message('Delete %s', source)
1505 if not self.opt.dry_run:
1506 self.s3.delete_object(Bucket=s3url.bucket, Key=s3url.path)
1507
1508 @log_calls
1509 def batch_delete(self, sources):
1510 '''Delete a list of files in batch of batch_delete_size (default=1000).'''
1511 assert(type(sources) == list)
1512
1513 if len(sources) == 0:
1514 return
1515 elif len(sources) == 1:
1516 self.delete(sources[0])
1517 elif len(sources) > self.opt.batch_delete_size:
1518 for i in range(0, len(sources), self.opt.batch_delete_size):
1519 self.pool.batch_delete(sources[i:i+self.opt.batch_delete_size])
1520 else:
1521 bucket = S3URL(sources[0]).bucket
1522 deletes = []
1523 for source in sources:
1524 s3url = S3URL(source)
1525 if s3url.bucket != bucket:
1526 raise Failure('Unable to delete keys in different bucket %s and %s.' % (s3url.bucket, bucket))
1527 deletes.append({'Key': s3url.path})
1528
1529 response = self.s3.delete_objects(Bucket=bucket, Delete={'Objects': deletes})
1530
1531 # Output result of deletion.
1532 for res in response.get('Deleted') or []:
1533 message('Delete %s', S3URL.combine('s3', bucket, res['Key']))
1534
1535 for err in response.get('Errors') or []:
1536 message('Error deleting %s, code(%s) %s', S3URL.combine('s3', bucket, res['Key']), err['Code'], err['Message'])
1537
1538 if response.get('Errors') is not None:
1539 raise RetryFailure('Unable to complete deleting %d files.' % len(response.get('Errors')))
1540
1541 class CommandHandler(object):
1542 '''Main class to handle commands.
1543 This class is responsible for parameter validation and call the corresponding
1544 operations.
1545 '''
1546
1547 def __init__(self, opt):
1548 '''Constructor'''
1549 self.opt = opt
1550
1551 def run(self, args):
1552 '''Main entry to handle commands. Dispatch to individual command handler.'''
1553 if len(args) == 0:
1554 raise InvalidArgument('No command provided')
1555 cmd = args[0]
1556 if cmd + '_handler' in CommandHandler.__dict__:
1557 CommandHandler.__dict__[cmd + '_handler'](self, args)
1558 else:
1559 raise InvalidArgument('Unknown command %s' % cmd)
1560
1561 def s3handler(self):
1562 '''Create a S3Handler instances for multithread operations.'''
1563 return S3Handler(self.opt)
1564
1565 @log_calls
1566 def validate(self, format, args):
1567 '''Validate input parameters with given format.
1568 This function also checks for wildcards for recursive mode.
1569 '''
1570 fmtMap = {
1571 'cmd': 'Command',
1572 's3': 's3 path',
1573 'local': 'local path'
1574 }
1575 fmts = format.split('|')
1576 if len(fmts) != len(args):
1577 raise InvalidArgument('Invalid number of parameters')
1578
1579 for i, fmt in enumerate(fmts):
1580 valid = False
1581 for f in fmt.split(','):
1582 if f == 'cmd' and args[i] + '_handler' in CommandHandler.__dict__:
1583 valid = True
1584 if f == 's3' and S3URL.is_valid(args[i]):
1585 valid = True
1586 if f == 'local' and not S3URL.is_valid(args[i]):
1587 valid = True
1588 if not valid:
1589 raise InvalidArgument('Invalid parameter: %s, %s expected' % (args[i], fmtMap[fmt.split(',')[0]]))
1590
1591 @log_calls
1592 def pretty_print(self, objlist):
1593 '''Pretty print the result of s3walk. Here we calculate the maximum width
1594 of each column and align them.
1595 '''
1596
1597 def normalize_time(timestamp):
1598 '''Normalize the timestamp format for pretty print.'''
1599 if timestamp is None:
1600 return ' ' * 16
1601
1602 return TIMESTAMP_FORMAT % (timestamp.year, timestamp.month, timestamp.day, timestamp.hour, timestamp.minute)
1603
1604 cwidth = [0, 0, 0]
1605 format = '%%%ds %%%ds %%-%ds'
1606
1607 # Calculate maximum width for each column.
1608 result = []
1609 for obj in objlist:
1610 last_modified = normalize_time(obj['last_modified'])
1611 size = str(obj['size']) if not obj['is_dir'] else 'DIR'
1612 name = obj['name']
1613 item = (last_modified, size, name)
1614 for i, value in enumerate(item):
1615 if cwidth[i] < len(value):
1616 cwidth[i] = len(value)
1617 result.append(item)
1618
1619 # Format output.
1620 for item in result:
1621 text = (format % tuple(cwidth)) % item
1622 message('%s', text.rstrip())
1623
1624 @log_calls
1625 def ls_handler(self, args):
1626 '''Handler for ls command'''
1627 if len(args) == 1:
1628 self.pretty_print(self.s3handler().list_buckets())
1629 return
1630
1631 self.validate('cmd|s3', args)
1632 self.pretty_print(self.s3handler().s3walk(args[1]))
1633
1634 @log_calls
1635 def mb_handler(self, args):
1636 '''Handler for mb command'''
1637 if len(args) == 1:
1638 raise InvalidArgument('No s3 bucketname provided')
1639
1640 self.validate('cmd|s3', args)
1641 self.s3handler().create_bucket(args[1])
1642
1643 @log_calls
1644 def put_handler(self, args):
1645 '''Handler for put command'''
1646
1647 # Special check for shell expansion
1648 if len(args) < 3:
1649 raise InvalidArgument('Invalid number of parameters')
1650 self.validate('|'.join(['cmd'] + ['local'] * (len(args) - 2) + ['s3']), args)
1651
1652 source = args[1:-1] # shell expansion
1653 target = args[-1]
1654
1655 self.s3handler().put_files(source, target)
1656
1657 @log_calls
1658 def get_handler(self, args):
1659 '''Handler for get command'''
1660
1661 # Special case when we don't have target directory.
1662 if len(args) == 2:
1663 args += ['.']
1664
1665 self.validate('cmd|s3|local', args)
1666 source = args[1]
1667 target = args[2]
1668 self.s3handler().get_files(source, target)
1669
1670 @log_calls
1671 def cat_handler(self, args):
1672 '''Handler for cat command'''
1673
1674 self.validate('cmd|s3', args)
1675 source = args[1]
1676
1677 self.s3handler().print_files(source)
1678
1679 @log_calls
1680 def dsync_handler(self, args):
1681 '''Handler for dsync command.'''
1682 self.opt.recursive = True
1683 self.opt.sync_check = True
1684 self.opt.force = True
1685
1686 self.validate('cmd|s3,local|s3,local', args)
1687 source = args[1]
1688 target = args[2]
1689
1690 self.s3handler().dsync_files(source, target)
1691
1692 @log_calls
1693 def sync_handler(self, args):
1694 '''Handler for sync command.
1695 XXX Here we emulate sync command with get/put -r -f --sync-check. So
1696 it doesn't provide delete operation.
1697 '''
1698 self.opt.recursive = True
1699 self.opt.sync_check = True
1700 self.opt.force = True
1701
1702 self.validate('cmd|s3,local|s3,local', args)
1703 source = args[1]
1704 target = args[2]
1705
1706 self.s3handler().sync_files(source, target)
1707
1708 @log_calls
1709 def cp_handler(self, args):
1710 '''Handler for cp command'''
1711
1712 self.validate('cmd|s3|s3', args)
1713 source = args[1]
1714 target = args[2]
1715 self.s3handler().cp_files(source, target)
1716
1717 @log_calls
1718 def mv_handler(self, args):
1719 '''Handler for mv command'''
1720
1721 self.validate('cmd|s3|s3', args)
1722 source = args[1]
1723 target = args[2]
1724 self.s3handler().cp_files(source, target, delete_source=True)
1725
1726 @log_calls
1727 def del_handler(self, args):
1728 '''Handler for del command'''
1729 self.validate('cmd|s3', args)
1730 source = args[1]
1731 self.s3handler().del_files(source)
1732
1733 @log_calls
1734 def du_handler(self, args):
1735 '''Handler for size command'''
1736 for src, size in self.s3handler().size(args[1:]):
1737 message('%s\t%s' % (size, src))
1738
1739 @log_calls
1740 def _totalsize_handler(self, args):
1741 '''Handler of total_size command'''
1742 total_size = 0
1743 for src, size in self.s3handler().size(args[1:]):
1744 total_size += size
1745 message(str(total_size))
1746
1747 class ExtendedOptParser(optparse.Option):
1748 '''Specialized parser to handle new types such as datetim and dict'''
1749
1750 REGEX_DATE = re.compile(r'(\d{4})[/-](\d{1,2})[/-](\d{1,2})')
1751 REGEX_TIME = re.compile(r'(\d{1,2})\:(\d{2})')
1752 REGEX_DELTA = re.compile(r'(\d{1,3})\s+(minute|hour|day|week)s?\s+(ago|before|after)')
1753
1754 def match_date(self, value):
1755 '''Search for date information in the string'''
1756 m = self.REGEX_DATE.search(value)
1757 date = datetime.datetime.utcnow().date()
1758 if m:
1759 date = datetime.date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
1760 value = self.REGEX_DATE.sub('', value)
1761 return (date, value)
1762
1763 def match_time(self, value):
1764 '''Search for time information in the string'''
1765 m = self.REGEX_TIME.search(value)
1766 time = datetime.datetime.utcnow().time()
1767 if m:
1768 time = datetime.time(int(m.group(1)), int(m.group(2)))
1769 value = self.REGEX_TIME.sub('', value)
1770 return (time, value)
1771
1772 def match_delta(self, value):
1773 '''Search for timedelta information in the string'''
1774 m = self.REGEX_DELTA.search(value)
1775 delta = datetime.timedelta(days=0)
1776 if m:
1777 d = int(m.group(1))
1778 if m.group(3) == 'ago' or m.group(3) == 'before':
1779 d = -d
1780
1781 if m.group(2) == 'minute':
1782 delta = datetime.timedelta(minutes=d)
1783 elif m.group(2) == 'hour':
1784 delta = datetime.timedelta(hours=d)
1785 elif m.group(2) == 'day':
1786 delta = datetime.timedelta(days=d)
1787 elif m.group(2) == 'week':
1788 delta = datetime.timedelta(weeks=d)
1789 value = self.REGEX_DELTA.sub('', value)
1790 return (delta, value)
1791
1792 def check_datetime(self, opt, value):
1793 (current_date, value) = self.match_date(value.lower())
1794 (current_time, value) = self.match_time(value)
1795 (delta, value) = self.match_delta(value)
1796
1797 # We should be able to handle all stuff in value string.
1798 value = value.strip()
1799 if value != '':
1800 raise optparse.OptionValueError("Option %s: invalid datetime value: %r" % (opt, value))
1801
1802 # Make sure all datetime are timezone-aware. Use UTC for all datetime instances.
1803 return pytz.utc.localize(datetime.datetime.combine(current_date, current_time) + delta)
1804
1805 def check_dict(self, opt, value):
1806 '''Take json as dictionary parameter'''
1807 try:
1808 return json.loads(value)
1809 except:
1810 raise optparse.OptionValueError("Option %s: invalid dict value: %r" % (opt, value))
1811
1812 # Registration functions for option parser.
1813 TYPES = optparse.Option.TYPES + ('datetime', 'dict')
1814 TYPE_CHECKER = optparse.Option.TYPE_CHECKER.copy()
1815 TYPE_CHECKER['datetime'] = check_datetime
1816 TYPE_CHECKER['dict'] = check_dict
1817
1818 def main():
1819 try:
1820 if not sys.argv[0]: sys.argv[0] = '' # Workaround for running with optparse from egg
1821
1822 # Parser for command line options.
1823 parser = optparse.OptionParser(
1824 option_class=ExtendedOptParser,
1825 description='Super S3 command line tool. Version %s' % S4CMD_VERSION)
1826
1827 parser.add_option(
1828 '--version', help='print out version of s4cmd', dest='version',
1829 action='store_true', default=False)
1830 parser.add_option(
1831 '-p', '--config', help='path to s3cfg config file', dest='s3cfg',
1832 type='string', default=None)
1833 parser.add_option(
1834 '--access-key', help = 'use access_key for connection to S3', dest = 'access_key',
1835 type = 'string', default = None)
1836 parser.add_option(
1837 '--secret-key', help = 'use security key for connection to S3', dest = 'secret_key',
1838 type = 'string', default = None)
1839 parser.add_option(
1840 '-f', '--force', help='force overwrite files when download or upload',
1841 dest='force', action='store_true', default=False)
1842 parser.add_option(
1843 '-r', '--recursive', help='recursively checking subdirectories',
1844 dest='recursive', action='store_true', default=False)
1845 parser.add_option(
1846 '-s', '--sync-check', help='check file md5 before download or upload',
1847 dest='sync_check', action='store_true', default=False)
1848 parser.add_option(
1849 '-n', '--dry-run', help='trial run without actual download or upload',
1850 dest='dry_run', action='store_true', default=False)
1851 parser.add_option(
1852 '-t', '--retry', help='number of retries before giving up',
1853 dest='retry', type=int, default=3)
1854 parser.add_option(
1855 '--retry-delay', help='seconds to sleep between retries',
1856 type=int, default=10)
1857 parser.add_option(
1858 '-c', '--num-threads', help='number of concurrent threads',
1859 type=int, default=get_default_thread_count())
1860 parser.add_option(
1861 '-d', '--show-directory', help='show directory instead of its content',
1862 dest='show_dir', action='store_true', default=False)
1863 parser.add_option(
1864 '--ignore-empty-source', help='ignore empty source from s3',
1865 dest='ignore_empty_source', action='store_true', default=False)
1866 parser.add_option(
1867 '--endpoint-url', help='configure boto3 to use a different s3 endpoint',
1868 dest='endpoint_url', type='string', default=None)
1869 parser.add_option(
1870 '--use-ssl', help='(obsolete) use SSL connection to S3', dest='use_ssl',
1871 action='store_true', default=False)
1872 parser.add_option(
1873 '--verbose', help='verbose output', dest='verbose',
1874 action='store_true', default=False)
1875 parser.add_option(
1876 '--debug', help='debug output', dest='debug',
1877 action='store_true', default=False)
1878 parser.add_option(
1879 '--validate', help='(obsolete) validate lookup operation', dest='validate',
1880 action='store_true', default=False)
1881 parser.add_option(
1882 '-D', '--delete-removed',
1883 help='delete remote files that do not exist in source after sync',
1884 dest='delete_removed', action='store_true', default=False)
1885 parser.add_option(
1886 '--multipart-split-size',
1887 help='size in bytes to split multipart transfers', type=int,
1888 default=50 * 1024 * 1024)
1889 parser.add_option(
1890 '--max-singlepart-download-size',
1891 help='files with size (in bytes) greater than this will be downloaded in '
1892 'multipart transfers', type=int, default=50 * 1024 * 1024)
1893 parser.add_option(
1894 '--max-singlepart-upload-size',
1895 help='files with size (in bytes) greater than this will be uploaded in '
1896 'multipart transfers', type=int, default=4500 * 1024 * 1024)
1897 parser.add_option(
1898 '--max-singlepart-copy-size',
1899 help='files with size (in bytes) greater than this will be copied in '
1900 'multipart transfers', type=int, default=100 * 1024 * 1024)
1901 parser.add_option(
1902 '--batch-delete-size',
1903 help='Number of files (<1000) to be combined in batch delete.',
1904 type=int, default=1000)
1905 parser.add_option(
1906 '--last-modified-before',
1907 help='Condition on files where their last modified dates are before given parameter.',
1908 type='datetime', default=None)
1909 parser.add_option(
1910 '--last-modified-after',
1911 help='Condition on files where their last modified dates are after given parameter.',
1912 type='datetime', default=None)
1913
1914 # Extra S3 API arguments
1915 BotoClient.add_options(parser)
1916
1917 # Combine parameters from environment variable. This is useful for global settings.
1918 env_opts = (shlex.split(os.environ[S4CMD_ENV_KEY]) if S4CMD_ENV_KEY in os.environ else [])
1919 (opt, args) = parser.parse_args(sys.argv[1:] + env_opts)
1920 s4cmd_logging.configure(opt)
1921
1922 if opt.version:
1923 message('s4cmd version %s' % S4CMD_VERSION)
1924 else:
1925 # Initalize keys for S3.
1926 S3Handler.init_s3_keys(opt)
1927 try:
1928 CommandHandler(opt).run(args)
1929 except InvalidArgument as e:
1930 fail('[Invalid Argument] ', exc_info=e)
1931 except Failure as e:
1932 fail('[Runtime Failure] ', exc_info=e)
1933 except BotoClient.NoCredentialsError as e:
1934 fail('[Invalid Argument] ', exc_info=e)
1935 except BotoClient.BotoError as e:
1936 fail('[Boto3Error] %s: %s' % (e.error_code, e.error_message))
1937 except Exception as e:
1938 fail('[Runtime Exception] ', exc_info=e, stacktrace=True)
1939
1940 clean_tempfiles()
1941 progress('') # Clear progress message before exit.
1942 except Exception:
1943 if not opt.verbose:
1944 sys.exit(1)
1945
1946 if __name__ == '__main__':
1947 main()