forked from s3tools/s3cmd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3cmd
executable file
·1823 lines (1570 loc) · 81.4 KB
/
s3cmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
## Amazon S3 manager
## Author: Michal Ludvig <michal@logix.cz>
## http://www.logix.cz/michal
## License: GPL Version 2
import sys
if float("%d.%d" %(sys.version_info[0], sys.version_info[1])) < 2.4:
sys.stderr.write("ERROR: Python 2.4 or higher required, sorry.\n")
sys.exit(1)
import logging
import time
import os
import re
import errno
import glob
import traceback
import codecs
import locale
import subprocess
import htmlentitydefs
import socket
from copy import copy
from optparse import OptionParser, Option, OptionValueError, IndentedHelpFormatter
from logging import debug, info, warning, error
from distutils.spawn import find_executable
def output(message):
sys.stdout.write(message + "\n")
def check_args_type(args, type, verbose_type):
for arg in args:
if S3Uri(arg).type != type:
raise ParameterError("Expecting %s instead of '%s'" % (verbose_type, arg))
def cmd_du(args):
s3 = S3(Config())
if len(args) > 0:
uri = S3Uri(args[0])
if uri.type == "s3" and uri.has_bucket():
subcmd_bucket_usage(s3, uri)
return
subcmd_bucket_usage_all(s3)
def subcmd_bucket_usage_all(s3):
response = s3.list_all_buckets()
buckets_size = 0
for bucket in response["list"]:
size = subcmd_bucket_usage(s3, S3Uri("s3://" + bucket["Name"]))
if size != None:
buckets_size += size
total_size, size_coeff = formatSize(buckets_size, Config().human_readable_sizes)
total_size_str = str(total_size) + size_coeff
output(u"".rjust(8, "-"))
output(u"%s Total" % (total_size_str.ljust(8)))
def subcmd_bucket_usage(s3, uri):
bucket = uri.bucket()
object = uri.object()
if object.endswith('*'):
object = object[:-1]
try:
response = s3.bucket_list(bucket, prefix = object, recursive = True)
except S3Error, e:
if S3.codes.has_key(e.info["Code"]):
error(S3.codes[e.info["Code"]] % bucket)
return
else:
raise
bucket_size = 0
for object in response["list"]:
size, size_coeff = formatSize(object["Size"], False)
bucket_size += size
total_size, size_coeff = formatSize(bucket_size, Config().human_readable_sizes)
total_size_str = str(total_size) + size_coeff
output(u"%s %s" % (total_size_str.ljust(8), uri))
return bucket_size
def cmd_ls(args):
s3 = S3(Config())
if len(args) > 0:
uri = S3Uri(args[0])
if uri.type == "s3" and uri.has_bucket():
subcmd_bucket_list(s3, uri)
return
subcmd_buckets_list_all(s3)
def cmd_buckets_list_all_all(args):
s3 = S3(Config())
response = s3.list_all_buckets()
for bucket in response["list"]:
subcmd_bucket_list(s3, S3Uri("s3://" + bucket["Name"]))
output(u"")
def subcmd_buckets_list_all(s3):
response = s3.list_all_buckets()
for bucket in response["list"]:
output(u"%s s3://%s" % (
formatDateTime(bucket["CreationDate"]),
bucket["Name"],
))
def subcmd_bucket_list(s3, uri):
bucket = uri.bucket()
prefix = uri.object()
debug(u"Bucket 's3://%s':" % bucket)
if prefix.endswith('*'):
prefix = prefix[:-1]
try:
response = s3.bucket_list(bucket, prefix = prefix)
except S3Error, e:
if S3.codes.has_key(e.info["Code"]):
error(S3.codes[e.info["Code"]] % bucket)
return
else:
raise
if cfg.list_md5:
format_string = u"%(timestamp)16s %(size)9s%(coeff)1s %(md5)32s %(uri)s"
else:
format_string = u"%(timestamp)16s %(size)9s%(coeff)1s %(uri)s"
for prefix in response['common_prefixes']:
output(format_string % {
"timestamp": "",
"size": "DIR",
"coeff": "",
"md5": "",
"uri": uri.compose_uri(bucket, prefix["Prefix"])})
for object in response["list"]:
size, size_coeff = formatSize(object["Size"], Config().human_readable_sizes)
output(format_string % {
"timestamp": formatDateTime(object["LastModified"]),
"size" : str(size),
"coeff": size_coeff,
"md5" : object['ETag'].strip('"'),
"uri": uri.compose_uri(bucket, object["Key"]),
})
def cmd_bucket_create(args):
s3 = S3(Config())
for arg in args:
uri = S3Uri(arg)
if not uri.type == "s3" or not uri.has_bucket() or uri.has_object():
raise ParameterError("Expecting S3 URI with just the bucket name set instead of '%s'" % arg)
try:
response = s3.bucket_create(uri.bucket(), cfg.bucket_location)
output(u"Bucket '%s' created" % uri.uri())
except S3Error, e:
if S3.codes.has_key(e.info["Code"]):
error(S3.codes[e.info["Code"]] % uri.bucket())
return
else:
raise
def cmd_website_info(args):
s3 = S3(Config())
for arg in args:
uri = S3Uri(arg)
if not uri.type == "s3" or not uri.has_bucket() or uri.has_object():
raise ParameterError("Expecting S3 URI with just the bucket name set instead of '%s'" % arg)
try:
response = s3.website_info(uri, cfg.bucket_location)
if response:
output(u"Bucket %s: Website configuration" % uri.uri())
output(u"Website endpoint: %s" % response['website_endpoint'])
output(u"Index document: %s" % response['index_document'])
output(u"Error document: %s" % response['error_document'])
else:
output(u"Bucket %s: Unable to receive website configuration." % (uri.uri()))
except S3Error, e:
if S3.codes.has_key(e.info["Code"]):
error(S3.codes[e.info["Code"]] % uri.bucket())
return
else:
raise
def cmd_website_create(args):
s3 = S3(Config())
for arg in args:
uri = S3Uri(arg)
if not uri.type == "s3" or not uri.has_bucket() or uri.has_object():
raise ParameterError("Expecting S3 URI with just the bucket name set instead of '%s'" % arg)
try:
response = s3.website_create(uri, cfg.bucket_location)
output(u"Bucket '%s': website configuration created." % (uri.uri()))
except S3Error, e:
if S3.codes.has_key(e.info["Code"]):
error(S3.codes[e.info["Code"]] % uri.bucket())
return
else:
raise
def cmd_website_delete(args):
s3 = S3(Config())
for arg in args:
uri = S3Uri(arg)
if not uri.type == "s3" or not uri.has_bucket() or uri.has_object():
raise ParameterError("Expecting S3 URI with just the bucket name set instead of '%s'" % arg)
try:
response = s3.website_delete(uri, cfg.bucket_location)
output(u"Bucket '%s': website configuration deleted." % (uri.uri()))
except S3Error, e:
if S3.codes.has_key(e.info["Code"]):
error(S3.codes[e.info["Code"]] % uri.bucket())
return
else:
raise
def cmd_bucket_delete(args):
def _bucket_delete_one(uri):
try:
response = s3.bucket_delete(uri.bucket())
except S3Error, e:
if e.info['Code'] == 'BucketNotEmpty' and (cfg.force or cfg.recursive):
warning(u"Bucket is not empty. Removing all the objects from it first. This may take some time...")
subcmd_object_del_uri(uri.uri(), recursive = True)
return _bucket_delete_one(uri)
elif S3.codes.has_key(e.info["Code"]):
error(S3.codes[e.info["Code"]] % uri.bucket())
return
else:
raise
s3 = S3(Config())
for arg in args:
uri = S3Uri(arg)
if not uri.type == "s3" or not uri.has_bucket() or uri.has_object():
raise ParameterError("Expecting S3 URI with just the bucket name set instead of '%s'" % arg)
_bucket_delete_one(uri)
output(u"Bucket '%s' removed" % uri.uri())
def cmd_object_put(args):
cfg = Config()
s3 = S3(cfg)
if len(args) == 0:
raise ParameterError("Nothing to upload. Expecting a local file or directory and a S3 URI destination.")
## Normalize URI to convert s3://bkt to s3://bkt/ (trailing slash)
destination_base_uri = S3Uri(args.pop())
if destination_base_uri.type != 's3':
raise ParameterError("Destination must be S3Uri. Got: %s" % destination_base_uri)
destination_base = str(destination_base_uri)
if len(args) == 0:
raise ParameterError("Nothing to upload. Expecting a local file or directory.")
local_list, single_file_local = fetch_local_list(args)
local_list, exclude_list = filter_exclude_include(local_list)
local_count = len(local_list)
info(u"Summary: %d local files to upload" % local_count)
if local_count > 0:
if not destination_base.endswith("/"):
if not single_file_local:
raise ParameterError("Destination S3 URI must end with '/' (ie must refer to a directory on the remote side).")
local_list[local_list.keys()[0]]['remote_uri'] = unicodise(destination_base)
else:
for key in local_list:
local_list[key]['remote_uri'] = unicodise(destination_base + key)
if cfg.dry_run:
for key in exclude_list:
output(u"exclude: %s" % unicodise(key))
for key in local_list:
output(u"upload: %s -> %s" % (local_list[key]['full_name_unicode'], local_list[key]['remote_uri']))
warning(u"Exitting now because of --dry-run")
return
seq = 0
for key in local_list:
seq += 1
uri_final = S3Uri(local_list[key]['remote_uri'])
extra_headers = copy(cfg.extra_headers)
full_name_orig = local_list[key]['full_name']
full_name = full_name_orig
seq_label = "[%d of %d]" % (seq, local_count)
if Config().encrypt:
exitcode, full_name, extra_headers["x-amz-meta-s3tools-gpgenc"] = gpg_encrypt(full_name_orig)
try:
response = s3.object_put(full_name, uri_final, extra_headers, extra_label = seq_label)
except S3UploadError, e:
error(u"Upload of '%s' failed too many times. Skipping that file." % full_name_orig)
continue
except InvalidFileError, e:
warning(u"File can not be uploaded: %s" % e)
continue
speed_fmt = formatSize(response["speed"], human_readable = True, floating_point = True)
if not Config().progress_meter:
output(u"File '%s' stored as '%s' (%d bytes in %0.1f seconds, %0.2f %sB/s) %s" %
(unicodise(full_name_orig), uri_final, response["size"], response["elapsed"],
speed_fmt[0], speed_fmt[1], seq_label))
if Config().acl_public:
output(u"Public URL of the object is: %s" %
(uri_final.public_url()))
if Config().encrypt and full_name != full_name_orig:
debug(u"Removing temporary encrypted file: %s" % unicodise(full_name))
os.remove(full_name)
def cmd_object_get(args):
cfg = Config()
s3 = S3(cfg)
## Check arguments:
## if not --recursive:
## - first N arguments must be S3Uri
## - if the last one is S3 make current dir the destination_base
## - if the last one is a directory:
## - take all 'basenames' of the remote objects and
## make the destination name be 'destination_base'+'basename'
## - if the last one is a file or not existing:
## - if the number of sources (N, above) == 1 treat it
## as a filename and save the object there.
## - if there's more sources -> Error
## if --recursive:
## - first N arguments must be S3Uri
## - for each Uri get a list of remote objects with that Uri as a prefix
## - apply exclude/include rules
## - each list item will have MD5sum, Timestamp and pointer to S3Uri
## used as a prefix.
## - the last arg may be '-' (stdout)
## - the last arg may be a local directory - destination_base
## - if the last one is S3 make current dir the destination_base
## - if the last one doesn't exist check remote list:
## - if there is only one item and its_prefix==its_name
## download that item to the name given in last arg.
## - if there are more remote items use the last arg as a destination_base
## and try to create the directory (incl. all parents).
##
## In both cases we end up with a list mapping remote object names (keys) to local file names.
## Each item will be a dict with the following attributes
# {'remote_uri', 'local_filename'}
download_list = []
if len(args) == 0:
raise ParameterError("Nothing to download. Expecting S3 URI.")
if S3Uri(args[-1]).type == 'file':
destination_base = args.pop()
else:
destination_base = "."
if len(args) == 0:
raise ParameterError("Nothing to download. Expecting S3 URI.")
remote_list = fetch_remote_list(args, require_attribs = False)
remote_list, exclude_list = filter_exclude_include(remote_list)
remote_count = len(remote_list)
info(u"Summary: %d remote files to download" % remote_count)
if remote_count > 0:
if destination_base == "-":
## stdout is ok for multiple remote files!
for key in remote_list:
remote_list[key]['local_filename'] = "-"
elif not os.path.isdir(destination_base):
## We were either given a file name (existing or not)
if remote_count > 1:
raise ParameterError("Destination must be a directory or stdout when downloading multiple sources.")
remote_list[remote_list.keys()[0]]['local_filename'] = deunicodise(destination_base)
elif os.path.isdir(destination_base):
if destination_base[-1] != os.path.sep:
destination_base += os.path.sep
for key in remote_list:
remote_list[key]['local_filename'] = destination_base + key
else:
raise InternalError("WTF? Is it a dir or not? -- %s" % destination_base)
if cfg.dry_run:
for key in exclude_list:
output(u"exclude: %s" % unicodise(key))
for key in remote_list:
output(u"download: %s -> %s" % (remote_list[key]['object_uri_str'], remote_list[key]['local_filename']))
warning(u"Exitting now because of --dry-run")
return
seq = 0
for key in remote_list:
seq += 1
item = remote_list[key]
uri = S3Uri(item['object_uri_str'])
## Encode / Decode destination with "replace" to make sure it's compatible with current encoding
destination = unicodise_safe(item['local_filename'])
seq_label = "[%d of %d]" % (seq, remote_count)
start_position = 0
if destination == "-":
## stdout
dst_stream = sys.__stdout__
else:
## File
try:
file_exists = os.path.exists(destination)
try:
dst_stream = open(destination, "ab")
except IOError, e:
if e.errno == errno.ENOENT:
basename = destination[:destination.rindex(os.path.sep)]
info(u"Creating directory: %s" % basename)
os.makedirs(basename)
dst_stream = open(destination, "ab")
else:
raise
if file_exists:
if Config().get_continue:
start_position = dst_stream.tell()
elif Config().force:
start_position = 0L
dst_stream.seek(0L)
dst_stream.truncate()
elif Config().skip_existing:
info(u"Skipping over existing file: %s" % (destination))
continue
else:
dst_stream.close()
raise ParameterError(u"File %s already exists. Use either of --force / --continue / --skip-existing or give it a new name." % destination)
except IOError, e:
error(u"Skipping %s: %s" % (destination, e.strerror))
continue
response = s3.object_get(uri, dst_stream, start_position = start_position, extra_label = seq_label)
if response["headers"].has_key("x-amz-meta-s3tools-gpgenc"):
gpg_decrypt(destination, response["headers"]["x-amz-meta-s3tools-gpgenc"])
response["size"] = os.stat(destination)[6]
if not Config().progress_meter and destination != "-":
speed_fmt = formatSize(response["speed"], human_readable = True, floating_point = True)
output(u"File %s saved as '%s' (%d bytes in %0.1f seconds, %0.2f %sB/s)" %
(uri, destination, response["size"], response["elapsed"], speed_fmt[0], speed_fmt[1]))
def cmd_object_del(args):
for uri_str in args:
uri = S3Uri(uri_str)
if uri.type != "s3":
raise ParameterError("Expecting S3 URI instead of '%s'" % uri_str)
if not uri.has_object():
if Config().recursive and not Config().force:
raise ParameterError("Please use --force to delete ALL contents of %s" % uri_str)
elif not Config().recursive:
raise ParameterError("File name required, not only the bucket name. Alternatively use --recursive")
subcmd_object_del_uri(uri_str)
def subcmd_object_del_uri(uri_str, recursive = None):
s3 = S3(cfg)
if recursive is None:
recursive = cfg.recursive
remote_list = fetch_remote_list(uri_str, require_attribs = False, recursive = recursive)
remote_list, exclude_list = filter_exclude_include(remote_list)
remote_count = len(remote_list)
info(u"Summary: %d remote files to delete" % remote_count)
if cfg.dry_run:
for key in exclude_list:
output(u"exclude: %s" % unicodise(key))
for key in remote_list:
output(u"delete: %s" % remote_list[key]['object_uri_str'])
warning(u"Exitting now because of --dry-run")
return
for key in remote_list:
item = remote_list[key]
response = s3.object_delete(S3Uri(item['object_uri_str']))
output(u"File %s deleted" % item['object_uri_str'])
def subcmd_cp_mv(args, process_fce, action_str, message):
if len(args) < 2:
raise ParameterError("Expecting two or more S3 URIs for " + action_str)
dst_base_uri = S3Uri(args.pop())
if dst_base_uri.type != "s3":
raise ParameterError("Destination must be S3 URI. To download a file use 'get' or 'sync'.")
destination_base = dst_base_uri.uri()
remote_list = fetch_remote_list(args, require_attribs = False)
remote_list, exclude_list = filter_exclude_include(remote_list)
remote_count = len(remote_list)
info(u"Summary: %d remote files to %s" % (remote_count, action_str))
if cfg.recursive:
if not destination_base.endswith("/"):
destination_base += "/"
for key in remote_list:
remote_list[key]['dest_name'] = destination_base + key
else:
for key in remote_list:
if destination_base.endswith("/"):
remote_list[key]['dest_name'] = destination_base + key
else:
remote_list[key]['dest_name'] = destination_base
if cfg.dry_run:
for key in exclude_list:
output(u"exclude: %s" % unicodise(key))
for key in remote_list:
output(u"%s: %s -> %s" % (action_str, remote_list[key]['object_uri_str'], remote_list[key]['dest_name']))
warning(u"Exitting now because of --dry-run")
return
seq = 0
for key in remote_list:
seq += 1
seq_label = "[%d of %d]" % (seq, remote_count)
item = remote_list[key]
src_uri = S3Uri(item['object_uri_str'])
dst_uri = S3Uri(item['dest_name'])
extra_headers = copy(cfg.extra_headers)
response = process_fce(src_uri, dst_uri, extra_headers)
output(message % { "src" : src_uri, "dst" : dst_uri })
if Config().acl_public:
info(u"Public URL is: %s" % dst_uri.public_url())
def cmd_cp(args):
s3 = S3(Config())
subcmd_cp_mv(args, s3.object_copy, "copy", "File %(src)s copied to %(dst)s")
def cmd_mv(args):
s3 = S3(Config())
subcmd_cp_mv(args, s3.object_move, "move", "File %(src)s moved to %(dst)s")
def cmd_info(args):
s3 = S3(Config())
while (len(args)):
uri_arg = args.pop(0)
uri = S3Uri(uri_arg)
if uri.type != "s3" or not uri.has_bucket():
raise ParameterError("Expecting S3 URI instead of '%s'" % uri_arg)
try:
if uri.has_object():
info = s3.object_info(uri)
output(u"%s (object):" % uri.uri())
output(u" File size: %s" % info['headers']['content-length'])
output(u" Last mod: %s" % info['headers']['last-modified'])
output(u" MIME type: %s" % info['headers']['content-type'])
output(u" MD5 sum: %s" % info['headers']['etag'].strip('"'))
else:
info = s3.bucket_info(uri)
output(u"%s (bucket):" % uri.uri())
output(u" Location: %s" % info['bucket-location'])
acl = s3.get_acl(uri)
acl_grant_list = acl.getGrantList()
for grant in acl_grant_list:
output(u" ACL: %s: %s" % (grant['grantee'], grant['permission']))
if acl.isAnonRead():
output(u" URL: %s" % uri.public_url())
except S3Error, e:
if S3.codes.has_key(e.info["Code"]):
error(S3.codes[e.info["Code"]] % uri.bucket())
return
else:
raise
def cmd_sync_remote2remote(args):
s3 = S3(Config())
# Normalise s3://uri (e.g. assert trailing slash)
destination_base = unicode(S3Uri(args[-1]))
src_list = fetch_remote_list(args[:-1], recursive = True, require_attribs = True)
dst_list = fetch_remote_list(destination_base, recursive = True, require_attribs = True)
src_count = len(src_list)
dst_count = len(dst_list)
info(u"Found %d source files, %d destination files" % (src_count, dst_count))
src_list, exclude_list = filter_exclude_include(src_list)
src_list, dst_list, existing_list = compare_filelists(src_list, dst_list, src_remote = True, dst_remote = True)
src_count = len(src_list)
dst_count = len(dst_list)
print(u"Summary: %d source files to copy, %d files at destination to delete" % (src_count, dst_count))
if src_count > 0:
### Populate 'remote_uri' only if we've got something to sync from src to dst
for key in src_list:
src_list[key]['target_uri'] = destination_base + key
if cfg.dry_run:
for key in exclude_list:
output(u"exclude: %s" % unicodise(key))
if cfg.delete_removed:
for key in dst_list:
output(u"delete: %s" % dst_list[key]['object_uri_str'])
for key in src_list:
output(u"Sync: %s -> %s" % (src_list[key]['object_uri_str'], src_list[key]['target_uri']))
warning(u"Exitting now because of --dry-run")
return
# Delete items in destination that are not in source
if cfg.delete_removed:
if cfg.dry_run:
for key in dst_list:
output(u"delete: %s" % dst_list[key]['object_uri_str'])
else:
for key in dst_list:
uri = S3Uri(dst_list[key]['object_uri_str'])
s3.object_delete(uri)
output(u"deleted: '%s'" % uri)
# Perform the synchronization of files
timestamp_start = time.time()
seq = 0
file_list = src_list.keys()
file_list.sort()
for file in file_list:
seq += 1
item = src_list[file]
src_uri = S3Uri(item['object_uri_str'])
dst_uri = S3Uri(item['target_uri'])
seq_label = "[%d of %d]" % (seq, src_count)
extra_headers = copy(cfg.extra_headers)
try:
response = s3.object_copy(src_uri, dst_uri, extra_headers)
output("File %(src)s copied to %(dst)s" % { "src" : src_uri, "dst" : dst_uri })
except S3Error, e:
error("File %(src)s could not be copied: %(e)s" % { "src" : src_uri, "e" : e })
total_elapsed = time.time() - timestamp_start
outstr = "Done. Copied %d files in %0.1f seconds, %0.2f files/s" % (seq, total_elapsed, seq/total_elapsed)
if seq > 0:
output(outstr)
else:
info(outstr)
def cmd_sync_remote2local(args):
def _parse_attrs_header(attrs_header):
attrs = {}
for attr in attrs_header.split("/"):
key, val = attr.split(":")
attrs[key] = val
return attrs
s3 = S3(Config())
destination_base = args[-1]
local_list, single_file_local = fetch_local_list(destination_base, recursive = True)
remote_list = fetch_remote_list(args[:-1], recursive = True, require_attribs = True)
local_count = len(local_list)
remote_count = len(remote_list)
info(u"Found %d remote files, %d local files" % (remote_count, local_count))
remote_list, exclude_list = filter_exclude_include(remote_list)
remote_list, local_list, existing_list = compare_filelists(remote_list, local_list, src_remote = True, dst_remote = False)
local_count = len(local_list)
remote_count = len(remote_list)
info(u"Summary: %d remote files to download, %d local files to delete" % (remote_count, local_count))
if not os.path.isdir(destination_base):
## We were either given a file name (existing or not) or want STDOUT
if remote_count > 1:
raise ParameterError("Destination must be a directory when downloading multiple sources.")
remote_list[remote_list.keys()[0]]['local_filename'] = deunicodise(destination_base)
else:
if destination_base[-1] != os.path.sep:
destination_base += os.path.sep
for key in remote_list:
local_filename = destination_base + key
if os.path.sep != "/":
local_filename = os.path.sep.join(local_filename.split("/"))
remote_list[key]['local_filename'] = deunicodise(local_filename)
if cfg.dry_run:
for key in exclude_list:
output(u"exclude: %s" % unicodise(key))
if cfg.delete_removed:
for key in local_list:
output(u"delete: %s" % local_list[key]['full_name_unicode'])
for key in remote_list:
output(u"download: %s -> %s" % (remote_list[key]['object_uri_str'], remote_list[key]['local_filename']))
warning(u"Exitting now because of --dry-run")
return
if cfg.delete_removed:
for key in local_list:
os.unlink(local_list[key]['full_name'])
output(u"deleted: %s" % local_list[key]['full_name_unicode'])
total_size = 0
total_elapsed = 0.0
timestamp_start = time.time()
seq = 0
dir_cache = {}
file_list = remote_list.keys()
file_list.sort()
for file in file_list:
seq += 1
item = remote_list[file]
uri = S3Uri(item['object_uri_str'])
dst_file = item['local_filename']
seq_label = "[%d of %d]" % (seq, remote_count)
try:
dst_dir = os.path.dirname(dst_file)
if not dir_cache.has_key(dst_dir):
dir_cache[dst_dir] = Utils.mkdir_with_parents(dst_dir)
if dir_cache[dst_dir] == False:
warning(u"%s: destination directory not writable: %s" % (file, dst_dir))
continue
try:
open_flags = os.O_CREAT
open_flags |= os.O_TRUNC
# open_flags |= os.O_EXCL
debug(u"dst_file=%s" % unicodise(dst_file))
# This will have failed should the file exist
os.close(os.open(dst_file, open_flags))
# Yeah I know there is a race condition here. Sadly I don't know how to open() in exclusive mode.
dst_stream = open(dst_file, "wb")
response = s3.object_get(uri, dst_stream, extra_label = seq_label)
dst_stream.close()
if response['headers'].has_key('x-amz-meta-s3cmd-attrs') and cfg.preserve_attrs:
attrs = _parse_attrs_header(response['headers']['x-amz-meta-s3cmd-attrs'])
if attrs.has_key('mode'):
os.chmod(dst_file, int(attrs['mode']))
if attrs.has_key('mtime') or attrs.has_key('atime'):
mtime = attrs.has_key('mtime') and int(attrs['mtime']) or int(time.time())
atime = attrs.has_key('atime') and int(attrs['atime']) or int(time.time())
os.utime(dst_file, (atime, mtime))
## FIXME: uid/gid / uname/gname handling comes here! TODO
except OSError, e:
try: dst_stream.close()
except: pass
if e.errno == errno.EEXIST:
warning(u"%s exists - not overwriting" % (dst_file))
continue
if e.errno in (errno.EPERM, errno.EACCES):
warning(u"%s not writable: %s" % (dst_file, e.strerror))
continue
if e.errno == errno.EISDIR:
warning(u"%s is a directory - skipping over" % dst_file)
continue
raise e
except KeyboardInterrupt:
try: dst_stream.close()
except: pass
warning(u"Exiting after keyboard interrupt")
return
except Exception, e:
try: dst_stream.close()
except: pass
error(u"%s: %s" % (file, e))
continue
# We have to keep repeating this call because
# Python 2.4 doesn't support try/except/finally
# construction :-(
try: dst_stream.close()
except: pass
except S3DownloadError, e:
error(u"%s: download failed too many times. Skipping that file." % file)
continue
speed_fmt = formatSize(response["speed"], human_readable = True, floating_point = True)
if not Config().progress_meter:
output(u"File '%s' stored as '%s' (%d bytes in %0.1f seconds, %0.2f %sB/s) %s" %
(uri, unicodise(dst_file), response["size"], response["elapsed"], speed_fmt[0], speed_fmt[1],
seq_label))
total_size += response["size"]
total_elapsed = time.time() - timestamp_start
speed_fmt = formatSize(total_size/total_elapsed, human_readable = True, floating_point = True)
# Only print out the result if any work has been done or
# if the user asked for verbose output
outstr = "Done. Downloaded %d bytes in %0.1f seconds, %0.2f %sB/s" % (total_size, total_elapsed, speed_fmt[0], speed_fmt[1])
if total_size > 0:
output(outstr)
else:
info(outstr)
def cmd_sync_local2remote(args):
def _build_attr_header(src):
import pwd, grp
attrs = {}
src = deunicodise(src)
try:
st = os.stat_result(os.stat(src))
except OSError, e:
raise InvalidFileError(u"%s: %s" % (unicodise(src), e.strerror))
for attr in cfg.preserve_attrs_list:
if attr == 'uname':
try:
val = pwd.getpwuid(st.st_uid).pw_name
except KeyError:
attr = "uid"
val = st.st_uid
warning(u"%s: Owner username not known. Storing UID=%d instead." % (unicodise(src), val))
elif attr == 'gname':
try:
val = grp.getgrgid(st.st_gid).gr_name
except KeyError:
attr = "gid"
val = st.st_gid
warning(u"%s: Owner groupname not known. Storing GID=%d instead." % (unicodise(src), val))
else:
val = getattr(st, 'st_' + attr)
attrs[attr] = val
result = ""
for k in attrs: result += "%s:%s/" % (k, attrs[k])
return { 'x-amz-meta-s3cmd-attrs' : result[:-1] }
s3 = S3(cfg)
if cfg.encrypt:
error(u"S3cmd 'sync' doesn't yet support GPG encryption, sorry.")
error(u"Either use unconditional 's3cmd put --recursive'")
error(u"or disable encryption with --no-encrypt parameter.")
sys.exit(1)
## Normalize URI to convert s3://bkt to s3://bkt/ (trailing slash)
destination_base_uri = S3Uri(args[-1])
if destination_base_uri.type != 's3':
raise ParameterError("Destination must be S3Uri. Got: %s" % destination_base_uri)
destination_base = str(destination_base_uri)
local_list, single_file_local = fetch_local_list(args[:-1], recursive = True)
remote_list = fetch_remote_list(destination_base, recursive = True, require_attribs = True)
local_count = len(local_list)
remote_count = len(remote_list)
info(u"Found %d local files, %d remote files" % (local_count, remote_count))
local_list, exclude_list = filter_exclude_include(local_list)
if single_file_local and len(local_list) == 1 and len(remote_list) == 1:
## Make remote_key same as local_key for comparison if we're dealing with only one file
remote_list_entry = remote_list[remote_list.keys()[0]]
# Flush remote_list, by the way
remote_list = { local_list.keys()[0] : remote_list_entry }
local_list, remote_list, existing_list = compare_filelists(local_list, remote_list, src_remote = False, dst_remote = True)
local_count = len(local_list)
remote_count = len(remote_list)
info(u"Summary: %d local files to upload, %d remote files to delete" % (local_count, remote_count))
if local_count > 0:
## Populate 'remote_uri' only if we've got something to upload
if not destination_base.endswith("/"):
if not single_file_local:
raise ParameterError("Destination S3 URI must end with '/' (ie must refer to a directory on the remote side).")
local_list[local_list.keys()[0]]['remote_uri'] = unicodise(destination_base)
else:
for key in local_list:
local_list[key]['remote_uri'] = unicodise(destination_base + key)
if cfg.dry_run:
for key in exclude_list:
output(u"exclude: %s" % unicodise(key))
if cfg.delete_removed:
for key in remote_list:
output(u"delete: %s" % remote_list[key]['object_uri_str'])
for key in local_list:
output(u"upload: %s -> %s" % (local_list[key]['full_name_unicode'], local_list[key]['remote_uri']))
warning(u"Exitting now because of --dry-run")
return
if cfg.delete_removed:
for key in remote_list:
uri = S3Uri(remote_list[key]['object_uri_str'])
s3.object_delete(uri)
output(u"deleted: '%s'" % uri)
uploaded_objects_list = []
total_size = 0
total_elapsed = 0.0
timestamp_start = time.time()
seq = 0
file_list = local_list.keys()
file_list.sort()
for file in file_list:
seq += 1
item = local_list[file]
src = item['full_name']
uri = S3Uri(item['remote_uri'])
seq_label = "[%d of %d]" % (seq, local_count)
extra_headers = copy(cfg.extra_headers)
try:
if cfg.preserve_attrs:
attr_header = _build_attr_header(src)
debug(u"attr_header: %s" % attr_header)
extra_headers.update(attr_header)
response = s3.object_put(src, uri, extra_headers, extra_label = seq_label)
except InvalidFileError, e:
warning(u"File can not be uploaded: %s" % e)
continue
except S3UploadError, e:
error(u"%s: upload failed too many times. Skipping that file." % item['full_name_unicode'])
continue
speed_fmt = formatSize(response["speed"], human_readable = True, floating_point = True)
if not cfg.progress_meter:
output(u"File '%s' stored as '%s' (%d bytes in %0.1f seconds, %0.2f %sB/s) %s" %
(item['full_name_unicode'], uri, response["size"], response["elapsed"],
speed_fmt[0], speed_fmt[1], seq_label))
total_size += response["size"]
uploaded_objects_list.append(uri.object())
total_elapsed = time.time() - timestamp_start
total_speed = total_elapsed and total_size/total_elapsed or 0.0
speed_fmt = formatSize(total_speed, human_readable = True, floating_point = True)
# Only print out the result if any work has been done or
# if the user asked for verbose output
outstr = "Done. Uploaded %d bytes in %0.1f seconds, %0.2f %sB/s" % (total_size, total_elapsed, speed_fmt[0], speed_fmt[1])
if total_size > 0:
output(outstr)
else:
info(outstr)
if cfg.invalidate_on_cf:
if len(uploaded_objects_list) == 0:
info("Nothing to invalidate in CloudFront")
else:
# 'uri' from the last iteration is still valid at this point
cf = CloudFront(cfg)
result = cf.InvalidateObjects(uri, uploaded_objects_list)
if result['status'] == 201:
output("Created invalidation request for %d paths" % len(uploaded_objects_list))
output("Check progress with: s3cmd cfinvalinfo cf://%s/%s" % (result['dist_id'], result['request_id']))
def cmd_sync(args):
if (len(args) < 2):
raise ParameterError("Too few parameters! Expected: %s" % commands['sync']['param'])
if S3Uri(args[0]).type == "file" and S3Uri(args[-1]).type == "s3":
return cmd_sync_local2remote(args)
if S3Uri(args[0]).type == "s3" and S3Uri(args[-1]).type == "file":
return cmd_sync_remote2local(args)
if S3Uri(args[0]).type == "s3" and S3Uri(args[-1]).type == "s3":
return cmd_sync_remote2remote(args)
raise ParameterError("Invalid source/destination: '%s'" % "' '".join(args))
def cmd_setacl(args):
def _update_acl(uri, seq_label = ""):
something_changed = False
acl = s3.get_acl(uri)
debug(u"acl: %s - %r" % (uri, acl.grantees))
if cfg.acl_public == True:
if acl.isAnonRead():
info(u"%s: already Public, skipping %s" % (uri, seq_label))
else:
acl.grantAnonRead()
something_changed = True
elif cfg.acl_public == False: # we explicitely check for False, because it could be None
if not acl.isAnonRead():
info(u"%s: already Private, skipping %s" % (uri, seq_label))
else:
acl.revokeAnonRead()
something_changed = True
# update acl with arguments
# grant first and revoke later, because revoke has priority
if cfg.acl_grants:
something_changed = True
for grant in cfg.acl_grants:
acl.grant(**grant);
if cfg.acl_revokes:
something_changed = True
for revoke in cfg.acl_revokes:
acl.revoke(**revoke);