Debian Codegraph @

s4cmd.py

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