-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrun.py
executable file
·2248 lines (2047 loc) · 102 KB
/
run.py
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
# -*- coding:utf-8 -*-
import Queue
import base64
import hashlib
import logging
import logging.config
import logging.handlers
import multiprocessing
import os
import sys
import threading
import time
import traceback
from optparse import OptionParser
import util
import obspycmd
import results
import myLib.cloghandler
from copy import deepcopy
from Queue import Empty
from constant import ConfigFile
from constant import LOCAL_SYS
from constant import SYS_ENCODING
from constant import CONTENT_TYPES
from util import Counter
from util import ThreadsStopFlag
from util import RangeFileWriter
from util import User
logging.handlers.ConcurrentRotatingFileHandler = myLib.cloghandler.ConcurrentRotatingFileHandler
VERSION = 'v4.6.7'
RETRY_TIMES = 3
UPLOAD_PART_MIN_SIZE = 5 * 1024 ** 2
UPLOAD_PART_MAX_SIZE = 5 * 1024 ** 3
TEST_CASES = {
201: 'PutObject;put_object',
202: 'GetObject;get_object',
206: 'CopyObject;copy_object'
}
OBJECTS_QUEUE_SIZE = 10 ** 5
END_MARKER = "END_MARKER"
user = None
# configurations
running_config = {}
# upload tasks
all_files_queue = multiprocessing.Queue()
# download tasks
all_objects_queue = multiprocessing.Queue()
# statistic tasks
results_queue = multiprocessing.Queue()
# lock for process workers
lock = multiprocessing.Lock()
# lock for process workers result
lock_re = multiprocessing.Lock()
# result file for object manifest
manifest_file = ''
# count for all workers' concurrency
current_concurrency = multiprocessing.Value('i', 0)
# data size of all tasks
total_data = multiprocessing.Value('f', 0)
total_data_upload = 0
total_data_download = 0
number_of_objects_to_put = 0
def read_config(options, config_file_name=ConfigFile.FILE_CONFIG):
global user
try:
print 'start read file \n'
f = open(config_file_name, 'rw')
lines = f.readlines()
for line in lines:
line = line.strip()
if line and line[0] != '#':
running_config[line[:line.find('=')].strip()] = line[line.find(
'=') + 1:].strip()
else:
continue
f.close()
if (options.localPath or options.remoteDir) and (
options.downloadTarget or options.savePath):
parser.error("options are mutually exclusive")
if options.operation:
running_config['Operation'] = options.operation
if options.localPath:
running_config['LocalPath'] = options.localPath
if options.remoteDir:
running_config['RemoteDir'] = options.remoteDir
if options.downloadTarget:
running_config['DownloadTarget'] = options.downloadTarget
if options.savePath:
running_config['SavePath'] = options.savePath
if options.bucketName:
running_config['BucketNameFixed'] = options.bucketName
if options.AK:
running_config['AK'] = options.AK
if options.SK:
running_config['SK'] = options.SK
if options.DomainName:
running_config['DomainName'] = options.DomainName
if options.Region:
running_config['Region'] = options.Region
running_config['AK'] = prompt_for_input('AK', 'your account')
running_config['SK'] = prompt_for_input('SK', 'your account')
user = User('obscmd', running_config['AK'], running_config['SK'])
# Don't show SK on screen display
del running_config['SK']
if running_config['IsHTTPs'].lower() == 'true':
running_config['IsHTTPs'] = True
else:
running_config['IsHTTPs'] = False
running_config['ConnectTimeout'] = int(running_config['ConnectTimeout'])
if int(running_config['ConnectTimeout']) < 5:
running_config['ConnectTimeout'] = 5
if running_config['RemoteDir']:
running_config['RemoteDir'] = running_config['RemoteDir'].replace(
'\\', '/').strip('/')
if running_config['RemoteDir']:
running_config['RemoteDir'] = running_config['RemoteDir'] + '/'
running_config['DownloadTarget'] = running_config[
'DownloadTarget'].lstrip('/')
if running_config['VirtualHost'].lower() == 'true':
running_config['VirtualHost'] = True
else:
running_config['VirtualHost'] = False
if running_config['RecordDetails'].lower() == 'true':
running_config['RecordDetails'] = True
else:
running_config['RecordDetails'] = False
if running_config['BadRequestCounted'].lower() == 'true':
running_config['BadRequestCounted'] = True
else:
running_config['BadRequestCounted'] = False
if running_config['PrintProgress'].lower() == 'true':
running_config['PrintProgress'] = True
else:
running_config['PrintProgress'] = False
if running_config['IgnoreExist'].lower() == 'true':
running_config['IgnoreExist'] = True
else:
running_config['IgnoreExist'] = False
if running_config['CompareETag'].lower() == 'true':
running_config['CompareETag'] = True
else:
running_config['CompareETag'] = False
if running_config['CheckFileChanging'].lower() == 'true':
running_config['CheckFileChanging'] = True
else:
running_config['CheckFileChanging'] = False
if running_config['ArchiveAfterUpload'].lower() == 'true':
running_config['ArchiveAfterUpload'] = True
else:
running_config['ArchiveAfterUpload'] = False
if running_config['CheckRoot'].lower() == 'true':
running_config['CheckRoot'] = True
else:
running_config['CheckRoot'] = False
if running_config['CheckSoftLinks'].lower() == 'true':
running_config['CheckSoftLinks'] = True
else:
running_config['CheckSoftLinks'] = False
if running_config['ProxyPort']:
running_config['ProxyPort'] = int(running_config['ProxyPort'])
# User's input
running_config['Operation'] = prompt_for_input('Operation',
'operation(upload/download/copy)')
if not running_config['Operation'].lower() == 'upload' and not \
running_config['Operation'].lower() == 'download'and not \
running_config['Operation'].lower() == 'copy':
print 'Operation must be upload or download or copy, exit...'
exit()
if running_config['Operation'].lower() == 'upload':
running_config['Testcase'] = 201
elif running_config['Operation'].lower() == 'download':
running_config['Testcase'] = 202
elif running_config['Operation'].lower() == 'copy':
running_config['Testcase'] = 206
if running_config.get('MultipartObjectSize'):
running_config['PartSize'] = prompt_for_input('PartSize',
'multipart size')
if running_config['Operation'].lower() == 'upload' and int(
running_config['PartSize']) < UPLOAD_PART_MIN_SIZE:
running_config['PartSize'] = str(UPLOAD_PART_MIN_SIZE)
if running_config['Operation'].lower() == 'upload' and int(
running_config['PartSize']) > UPLOAD_PART_MAX_SIZE:
running_config['PartSize'] = str(UPLOAD_PART_MAX_SIZE)
if int(running_config['PartSize']) > int(
running_config.get('MultipartObjectSize')):
print 'In order to cut object(s) to pieces, PartSize must be less than MultipartObjectSize'
exit()
else:
running_config['MultipartObjectSize'] = '0'
running_config['Concurrency'] = int(running_config['Concurrency']) if \
running_config['Concurrency'] else 1
running_config['LongConnection'] = False
running_config['ConnectionHeader'] = ''
running_config['CollectBasicData'] = False
running_config['LatencyRequestsNumber'] = False
running_config['LatencyPercentileMap'] = False
running_config['StatisticsInterval'] = 3
running_config['LatencySections'] = '500,1000,3000,10000'
# If server side encryption is on, set https + AWSV4 on.
if running_config['SrvSideEncryptType']:
if not running_config['IsHTTPs']:
running_config['IsHTTPs'] = True
logging.warn(
'change IsHTTPs to True while use SrvSideEncryptType')
if running_config['AuthAlgorithm'] != 'AWSV4' and running_config[
'SrvSideEncryptType'].lower() == 'sse-kms':
running_config['AuthAlgorithm'] = 'AWSV4'
logging.warn(
'change AuthAlgorithm to AWSV4 while use SrvSideEncryptType = SSE-KMS')
except IOError,data:
print '[ERROR] Read config file %s error: %s' % (config_file_name, data)
sys.exit()
def initialize_object_name(target_in_local, keys_already_exist_list):
global total_data_upload
global number_of_objects_to_put
remote_dir = running_config['RemoteDir']
multi_part_object_size = int(running_config.get('MultipartObjectSize'))
part_size = int(running_config['PartSize'])
def generate_task_tuple(file_path):
global total_data_upload
file_path = file_path.strip()
if not os.path.isfile(file_path):
print '{target} is not a file. Skip it.'.format(target=file_path)
else:
key = os.path.split(file_path)[1]
if remote_dir:
key = remote_dir + key
task_tuple = None
if key.decode(SYS_ENCODING) not in keys_already_exist_list:
size = int(os.path.getsize(file_path))
total_data_upload += size
if size >= multi_part_object_size:
parts = size / part_size + 1
if parts > 10000:
msg_t = 'PartSize({part_size}) is too small.\n' \
'You have a file({file}) cut to more than 10,000 parts.\n' \
'Please make sure every file is cut to less than or equal to 10,000 parts. Exit...' \
.format(part_size=running_config['PartSize'],
file=key)
print msg_t
logging.warn(msg_t)
exit()
task_tuple = (key, size, file_path)
return task_tuple
if ',' not in target_in_local:
if running_config['CheckSoftLinks'] and os.path.islink(target_in_local):
logging.error(
"the local path [%s] is link, now exit!" % target_in_local)
exit()
if os.path.isdir(target_in_local):
top_dir = running_config['LocalPath'].split('/')[-1]
files = []
try:
files = os.listdir(target_in_local)
except OSError:
pass
if not files:
object_to_put = target_in_local.replace(
running_config['LocalPath'], top_dir)
object_to_put = object_to_put.lstrip('/') + '/'
key = target_in_local + '/'
if remote_dir:
object_to_put = remote_dir + object_to_put
all_files_queue.put((object_to_put, 0, key))
logging.debug("=== object_to_put : %s, keyfile : %s ===" % (
object_to_put, key))
number_of_objects_to_put += 1
else:
for fi in files:
fi_d = os.path.join(target_in_local, fi)
if running_config['CheckSoftLinks'] and os.path.islink(fi_d):
logging.warning(
'skip the file[%s] because it is link!' % fi_d)
continue
if os.path.isdir(fi_d):
logging.debug('scanning dir: ' + fi_d)
initialize_object_name(fi_d, keys_already_exist_list)
elif os.path.isfile(fi_d):
object_to_put = fi_d.replace(
running_config['LocalPath'], top_dir)
object_to_put = object_to_put.lstrip('/')
if remote_dir:
object_to_put = remote_dir + object_to_put
if object_to_put.decode(
SYS_ENCODING) not in keys_already_exist_list:
object_size = int(os.path.getsize(fi_d))
total_data_upload += object_size
if object_size >= multi_part_object_size:
parts_count = object_size / part_size + 1
if parts_count > 10000:
msg = 'PartSize({part_size}) is too small.\n' \
'You have a file({file}) cut to more than 10,000 parts.\n' \
'Please make sure every file is cut to less than or equal to 10,000 parts.\n' \
'Exit...' \
.format(
part_size=running_config['PartSize'],
file=object_to_put)
print msg
logging.error(msg)
exit()
all_files_queue.put(
(object_to_put, object_size, fi_d))
number_of_objects_to_put += 1
elif os.path.isfile(target_in_local):
task_t = generate_task_tuple(target_in_local)
if task_t:
all_files_queue.put(task_t)
number_of_objects_to_put += 1
else:
targets = target_in_local.split(',')
targets = list(set(targets))
for target in targets:
task_t = generate_task_tuple(target)
if task_t:
all_files_queue.put(task_t)
number_of_objects_to_put += 1
''' old get bucket,limit in key numbers in bucket
def get_all_keys_in_bucket(bucket_name, ak, sk, target_in_bucket=''):
from xml.etree import ElementTree
m = 'getting keys in bucket...'
print m
logging.warn(m)
lists_objects = []
targets = list(set(target_in_bucket.split(',')))
for target in targets:
target = target.strip()
list_objects = []
marker = ''
while marker is not None:
conn = obspycmd.MyHTTPConnection(host=running_config['DomainName'],
is_secure=running_config[
'IsHTTPs'],
ssl_version=running_config[
'sslVersion'],
timeout=running_config[
'ConnectTimeout'],
long_connection=running_config[
'LongConnection'],
conn_header=running_config[
'ConnectionHeader'],
proxy_host=running_config[
'ProxyHost'],
proxy_port=running_config[
'ProxyPort'],
proxy_username=running_config[
'ProxyUserName'],
proxy_password=running_config[
'ProxyPassWord'])
rest = obspycmd.OBSRequestDescriptor(
request_type='ListObjectsInBucket',
ak=ak, sk=sk,
auth_algorithm=running_config['AuthAlgorithm'],
virtual_host=running_config['VirtualHost'],
domain_name=running_config['DomainName'],
region=running_config['Region'])
rest.bucket = bucket_name
# List a directory
if target.endswith('/'):
dir_prefix = target.strip('/')
if dir_prefix:
dir_prefix = dir_prefix + '/'
rest.query_args['prefix'] = dir_prefix
elif target.endswith('*'):
prefix = target.strip('/').rstrip('*')
if prefix:
rest.query_args['prefix'] = prefix
# List an object
elif target:
rest.query_args['prefix'] = target
if marker:
rest.query_args['marker'] = marker
resp = obspycmd.OBSRequestHandler(rest, conn).make_request()
marker = resp.return_data
xml_body = resp.recv_body
logging.debug("=== response body is %s ===" % xml_body)
if not xml_body:
print 'Error in http request, please see log/*.log'
exit()
if '<Code>NoSuchBucket</Code>' in xml_body:
print 'No such bucket(%s), exit...' % bucket_name
logging.error('No such bucket(%s), exit...' % bucket_name)
exit()
root = ElementTree.fromstring(xml_body)
logging.debug("=== the elementTree of xml_body is %s ===" % root)
if '<Contents>' in xml_body:
logging.debug("=== root[6:] is %s, and root[5:] is %s ===" % (
root[6:], root[5:]))
if '<NextMarker>' in xml_body:
for contents_element in root[6:]:
if contents_element[0].text[-1] != '/':
# list_objects.append((contents_element[0].text,
# int(contents_element[3].text)))
all_objects_queue.put((contents_element[0].text,
int(contents_element[3].text)))
else:
for contents_element in root[5:]:
logging.debug(
"=== contents_element is %s, contents_element[0] is %s, contents_element[3] is %s ===" % (
contents_element, contents_element[0].text,
contents_element[3].text))
if contents_element[0].text[-1] != '/' or int(
contents_element[3].text) == 0:
list_objects.append((contents_element[0].text,
int(contents_element[3].text)))
# If target is a single object, check if it's in the bucket.
if target and not target.endswith(('/', '*')):
find_flag = False
for one_tuple in list_objects:
if target == one_tuple[0].encode(SYS_ENCODING):
find_flag = True
break
if not find_flag:
list_objects = []
lists_objects.extend(list_objects)
logging.debug("=== lists_objects is %s ===" % lists_objects)
return list(set(lists_objects))
'''
def get_all_keys_in_bucket(bucket_name, ak, sk, target_in_bucket='', capacity_limitation=False, versions=False):
try:
from xml.etree import ElementTree
m = 'getting keys in bucket...'
logging.warn(m)
targets = list(set(target_in_bucket.split('\\')))
for target in targets:
target = target.strip()
marker = ''
if versions:
# 多版本暂不支持指定marker
marker = ('', '')
while marker is not None:
conn = obspycmd.MyHTTPConnection(host=running_config['DomainName'],
is_secure=running_config['IsHTTPs'],
ssl_version=running_config['sslVersion'],
timeout=running_config['ConnectTimeout'],
long_connection=running_config['LongConnection'],
conn_header=running_config['ConnectionHeader'])
rest = obspycmd.OBSRequestDescriptor(request_type='ListObjectsInBucket',
ak=ak, sk=sk,
auth_algorithm=running_config['AuthAlgorithm'],
virtual_host=running_config['VirtualHost'],
domain_name=running_config['DomainName'],
region=running_config['Region'])
rest.bucket = bucket_name
# rest.headers['x-hws-offline-migrate'] = True # sepcical use,don't care
rest.query_args['prefix'] = target
if versions:
rest.query_args['versions'] = None
if marker:
# rest.query_args['key-marker'] = marker[0]
rest.query_args['version-id-marker'] = marker[1]
else:
if marker:
rest.query_args['marker'] = marker
resp = obspycmd.OBSRequestHandler(rest, conn).make_request()
if resp.status != '200 OK':
# scan finished, put end marker without checking capacity limitation.
# all_objects_queue.put(END_MARKER)
print 'Failed to list objects[%s]' % resp.status
logging.error('Failed to list bucket(%s), err=[%s], exit...' % (bucket_name, resp.status))
exit()
marker = resp.return_data
xml_body = resp.recv_body
if not xml_body:
# scan finished, put end marker without checking capacity limitation.
# all_objects_queue.put(END_MARKER)
print 'Error in http request, please see log/*.log'
exit()
if '<Code>NoSuchBucket</Code>' in xml_body:
print 'No such bucket(%s), exit...' % bucket_name
logging.error('No such bucket(%s), exit...' % bucket_name)
exit()
logging.info('>>>>> response body: %s >>>>>' % xml_body)
root = ElementTree.fromstring(xml_body)
if versions:
# if '<Version>' in xml_body:
elements = root[8:] if marker else root[6:]
else:
# if '<Contents>' in xml_body:
elements = root[6:] if marker else root[5:]
for contents_element in elements:
if contents_element[0].text[-1] != '/':
if capacity_limitation:
# 如果队列已满,等待1s后再重试
while all_objects_queue.qsize() >= OBJECTS_QUEUE_SIZE:
logging.info(
"all_objects_queue is full[%d], wait 1s..." % all_objects_queue.qsize())
time.sleep(1)
if versions:
# (对象名,versionId,eTag,ContentLength)
all_objects_queue.put((contents_element[0].text, contents_element[1].text,
contents_element[4].text.strip('"'), int(contents_element[5].text)))
else:
# (对象名,None版本,eTag,ContentLength)
all_objects_queue.put((contents_element[0].text, None,
contents_element[2].text.strip('"'), int(contents_element[3].text)))
except KeyboardInterrupt, data:
logging.warn("list object exit...[%s]" % data)
return
finally:
# scan finished, put end marker without checking capacity limitation.
all_objects_queue.put(END_MARKER)
def JudgeObjectIsExist(object_tuple,bucketname,conn,worker_id):
rest = obspycmd.OBSRequestDescriptor(request_type='HeadObject',
ak=user.ak, sk=user.sk,
auth_algorithm=running_config['AuthAlgorithm'],
virtual_host=running_config['VirtualHost'],
domain_name=running_config['DomainName'],
region=running_config['Region'])
rest.bucket = bucketname
rest.key = object_tuple[0].encode('utf8')
# 如果是带版本列举,则需要带版本拷贝
if object_tuple[1] is not None:
rest.query_args['versionId'] = object_tuple[1].encode('utf8')
# rest.headers['x-hws-offline-migrate'] = True
resp = obspycmd.OBSRequestHandler(rest, conn).make_request()
logging.info("HeadObject resp.status[%s]", resp.status)
if resp.status == "200 OK":
logging.warn("Object[%s/%s] already exist in dst bucket[%s], src.e_tag[%s], src.content_length=[%s], "
"dst.e_tag=[%s], dst.content_length=[%s], " % (
str(rest.key), str(object_tuple[1]), rest.bucket,
str(object_tuple[2]), str(object_tuple[3]), resp.e_tag,
resp.content_length))
if resp.e_tag == object_tuple[2] and resp.content_length == object_tuple[3]:
results_queue.put(
(worker_id, object_tuple[0], object_tuple[2], rest.request_type, resp.start_time,
resp.end_time, resp.send_bytes, resp.recv_bytes, rest.record_url,
resp.e_tag, 'AlreadyExist', resp.request_id)
)
else:
results_queue.put(
(worker_id, object_tuple[0].encode('utf8'), object_tuple[2], rest.request_type, resp.start_time,
resp.end_time, resp.send_bytes, resp.recv_bytes, rest.record_url,
resp.e_tag, 'Conflict', resp.request_id)
)
return True
if resp.status != "404 Not Found":
logging.warn(
"Failed to Head Object[%s/%s] in bucket[%s], can't do copy." % (str(rest.key), str(object_tuple[1]),
rest.bucket))
results_queue.put(
(worker_id, object_tuple[0], object_tuple[2], rest.request_type, resp.start_time,
resp.end_time, resp.send_bytes, resp.recv_bytes, rest.record_url,
resp.e_tag, 'UnknownError', resp.request_id)
)
return True
else:
return False
def copy_object(worker_id, conn):
from xml.etree import ElementTree
try:
while True:
while all_objects_queue.empty():
logging.info("all_objects_queue is empty, wait 1s...[%s]." % worker_id)
time.sleep(1)
try:
object_tuple = all_objects_queue.get()
logging.info('get_object tuple:' + str(object_tuple))
except Empty:
continue
# 对象上传完成
if object_tuple == END_MARKER:
logging.warn("object copy finished[%s]." % worker_id)
all_objects_queue.put(object_tuple)
break
# Head Object
# if Object exist
# continue
objectIsExist=JudgeObjectIsExist(object_tuple, running_config['CopyDstBucket'], conn, worker_id)
if objectIsExist:
continue
import urllib
copy_source = '/' + running_config['CopySrcBucket'] + '/' + urllib.quote(object_tuple[0].encode('utf-8'))
if object_tuple[1] is not None:
copy_source = copy_source + '?versionId=' + object_tuple[1].encode('utf8')
# make Copy Object request
rest = obspycmd.OBSRequestDescriptor(request_type='CopyObject',
ak=user.ak, sk=user.sk,
auth_algorithm=running_config['AuthAlgorithm'],
virtual_host=running_config['VirtualHost'],
domain_name=running_config['DomainName'],
region=running_config['Region'])
rest.bucket = running_config['CopyDstBucket']
rest.key = object_tuple[0].encode('utf8')
file_name = object_tuple[0].encode(SYS_ENCODING)
rest.headers['x-amz-copy-source'] = copy_source
logging.debug("=== object_tuple[0]:%s ; file_name:%s ; size:%s ===" % (
str(object_tuple[0].encode('utf8')), str(file_name), str(object_tuple[3])))
resp = obspycmd.OBSRequestHandler(rest, conn).make_request()
e_tag = ''
status = resp.status
if resp.status == "200 OK":
# 校验返回消息中的md5,resp中未解析e_tag,拷贝请求的e_tag在body体内
xml_body = resp.recv_body
root = ElementTree.fromstring(xml_body)
e_tag = root[1].text.strip('"')
logging.debug(
"xml_body=[%s], e_tag=[%s], object_tuple[2]=[%s]" % (str(xml_body), e_tag, str(object_tuple[2])))
if e_tag != object_tuple[2]:
logging.warn(
"WARN:etag mismatching, the data[%s/%s] may be inconsistent." % (rest.bucket, rest.key))
status = "Inconsistent"
results_queue.put(
(worker_id, copy_source, object_tuple[2], rest.request_type, resp.start_time,
resp.end_time, resp.send_bytes, resp.recv_bytes, rest.record_url,
e_tag, status, resp.request_id)
)
except KeyboardInterrupt, data:
logging.warn("copy object exit...[%s]" % data)
return
def put_object(worker_id, conn):
while not all_files_queue.empty():
try:
file_tuple = all_files_queue.get(block=False)
logging.debug('Id of the worker is %s, and put_object tuple: %s' % (
str(worker_id), str(file_tuple)))
# Check if this file is changing. If true, skip it.
if running_config['CheckFileChanging'] and not str(
file_tuple[2]).endswith('/'):
m_time = os.stat(file_tuple[2]).st_mtime
# For improve upload performance , change sleep time from 2s to 100ms
time.sleep(0.1)
if os.stat(file_tuple[2]).st_mtime != m_time:
result_for_manifest = '%s, , %s, , , FAILED:file is changing \n' % (
file_tuple[2], file_tuple[1])
logging.debug("=== the result is %s" % result_for_manifest)
update_objects_manifest(result_for_manifest)
logging.warn(
'File(%s) is changing, skip it!' % file_tuple[2])
continue
except Empty:
logging.debug(
"Empty when getting task tuple from queue,then continue.")
continue
if file_tuple[1] < int(running_config.get('MultipartObjectSize')):
rest = obspycmd.OBSRequestDescriptor(request_type='PutObject',
ak=user.ak, sk=user.sk,
auth_algorithm=running_config[
'AuthAlgorithm'],
virtual_host=running_config[
'VirtualHost'],
domain_name=running_config[
'DomainName'],
region=running_config[
'Region'])
try:
rest.key = file_tuple[0]
except UnicodeDecodeError:
logging.error('Decode error, key: ' + file_tuple[0])
result_for_manifest = '%s, , %s, , , FAILED:decode error before upload\n' % (
file_tuple[2], file_tuple[1])
logging.debug("=== the result is %s" % result_for_manifest)
update_objects_manifest(result_for_manifest)
continue
rest.bucket = running_config['BucketNameFixed']
rest.headers['content-type'] = 'application/octet-stream'
tokens = file_tuple[0].split('.')
if len(tokens) > 1:
suffix = tokens[-1].strip().lower()
if suffix in CONTENT_TYPES:
rest.headers['content-type'] = CONTENT_TYPES[suffix]
if running_config['PutWithACL']:
rest.headers['x-amz-acl'] = running_config['PutWithACL']
if running_config['SrvSideEncryptType'].lower() == 'sse-c':
rest.headers[
'x-amz-server-side-encryption-customer-algorithm'] = 'AES256'
rest.headers[
'x-amz-server-side-encryption-customer-key'] = base64.b64encode(
running_config['CustomerKey'])
rest.headers[
'x-amz-server-side-encryption-customer-key-MD5'] = base64.b64encode(
hashlib.md5(running_config['CustomerKey']).digest())
elif running_config['SrvSideEncryptType'].lower() == 'sse-kms' \
and running_config[
'SrvSideEncryptAlgorithm'].lower() == 'aws:kms':
rest.headers['x-amz-server-side-encryption'] = 'aws:kms'
if running_config['SrvSideEncryptAWSKMSKeyId']:
rest.headers[
'x-amz-server-side-encryption-aws-kms-key-id'] = \
running_config[
'SrvSideEncryptAWSKMSKeyId']
if running_config['SrvSideEncryptContext']:
rest.headers['x-amz-server-side-encryption-context'] = \
running_config['SrvSideEncryptContext']
elif running_config['SrvSideEncryptType'].lower() == 'sse-kms' \
and running_config[
'SrvSideEncryptAlgorithm'].lower() == 'aes256':
rest.headers['x-amz-server-side-encryption'] = 'AES256'
rest.content_length = file_tuple[1]
md5 = ''
if not str(file_tuple[2]).endswith('/'):
file_location = file_tuple[2]
md5_value = util.md5_file_encode_by_size_offset(
file_path=file_location,
size=file_tuple[1],
offset=0)
md5 = md5_value.hexdigest()
md5_encoded = str(base64.b64encode(md5_value.digest()))
logging.debug(
"====== md5_value is %s, md5 value: %s,base64 value: %s.======" % (
md5_value, md5, md5_encoded))
rest.headers['content-md5'] = md5_encoded
rest.headers['x-amz-meta-md5chksum'] = md5
retry_count = 0
resp = obspycmd.DefineResponse()
resp.status = '99999 Not Ready'
while not resp.status.startswith('20'):
resp = obspycmd.OBSRequestHandler(rest, conn).make_request(
file_location=file_tuple[2])
if not resp.status.startswith('20'):
if retry_count == RETRY_TIMES:
logging.error(
'Max retry put_object, key: %s. Status is %s' %
(rest.key, resp.status))
retry_count += 1
break
retry_count += 1
logging.warn(
'Status is %s. Retry put_object, key: %s, retry_count: %d' %
(resp.status, rest.key, retry_count))
time.sleep(5)
else:
break
results_queue.put(
(worker_id, user.username, rest.record_url, rest.request_type,
resp.start_time, resp.end_time,
resp.send_bytes, 0, '', resp.request_id, resp.status,
resp.id2))
if retry_count > RETRY_TIMES:
error_msg = 'FAILED:service error in PutObject'
result_for_manifest = '%s, %s, %s, %s, %s, %s \n' % (
file_tuple[2], rest.bucket + '/' + rest.key,
rest.content_length,
md5, resp.e_tag, error_msg)
logging.debug("=== the result is %s" % result_for_manifest)
update_objects_manifest(result_for_manifest)
continue
# HEAD Object to compare file size with response Content-Length
rest_head = obspycmd.OBSRequestDescriptor(
request_type='HeadObject',
ak=user.ak, sk=user.sk,
auth_algorithm=running_config[
'AuthAlgorithm'],
virtual_host=running_config[
'VirtualHost'],
domain_name=running_config[
'DomainName'],
region=running_config[
'Region'])
rest_head.bucket = rest.bucket
rest_head.key = rest.key
rest_head.headers['Origin'] = ''
if running_config['SrvSideEncryptType'].lower() == 'sse-c':
rest_head.headers[
'x-amz-server-side-encryption-customer-algorithm'] = 'AES256'
rest_head.headers[
'x-amz-server-side-encryption-customer-key'] = base64.b64encode(
running_config['CustomerKey'])
rest_head.headers[
'x-amz-server-side-encryption-customer-key-MD5'] = base64.b64encode(
hashlib.md5(running_config['CustomerKey']).digest())
resp_head = obspycmd.DefineResponse()
resp_head.status = '99999 Not Ready'
resp_head = obspycmd.OBSRequestHandler(rest_head,
conn).make_request()
results_queue.put(
(worker_id, user.username, rest_head.record_url,
rest_head.request_type,
resp_head.start_time,
resp_head.end_time, 0, 0, '', resp_head.request_id,
resp_head.status,
resp_head.id2))
logging.debug(
"=== the Content-Length is %s ===" % resp_head.content_length)
if running_config['CompareETag'] and resp_head.content_length != \
file_tuple[1]:
logging.warn(
"=== delete object, key: %s. Compare content-length and size error,content-length: %s ===" % (
rest.key, resp_head.content_length))
rest_d = obspycmd.OBSRequestDescriptor(
request_type='DeleteObject',
ak=user.ak, sk=user.sk,
auth_algorithm=running_config[
'AuthAlgorithm'],
virtual_host=running_config[
'VirtualHost'],
domain_name=running_config[
'DomainName'],
region=running_config['Region'])
rest_d.bucket = rest.bucket
rest_d.key = rest.key
resp_d = obspycmd.OBSRequestHandler(rest_d,
conn).make_request()
results_queue.put(
(worker_id, user.username, rest_d.record_url,
rest_d.request_type,
resp_d.start_time,
resp_d.end_time, 0, 0, '', resp_d.request_id,
resp_d.status,
resp_d.id2))
result_for_manifest = '%s, %s, %s, %s, %s, FAILED:Content-Length error \n' % (
file_tuple[2], rest.bucket + '/' + rest.key,
file_tuple[1],
md5, resp.e_tag)
logging.debug("=== the result is %s" % result_for_manifest)
update_objects_manifest(result_for_manifest)
continue
result_for_manifest = '%s, %s, %s, %s, %s, SUCCESS \n' % (
file_tuple[2], rest.bucket + '/' + rest.key,
file_tuple[1],
md5, resp.e_tag)
logging.debug("=== the result is %s" % result_for_manifest)
update_objects_manifest(result_for_manifest)
# if ArchiveAfterUpload is true archive the files which has been upload to bucket
if running_config['ArchiveAfterUpload']:
archive_dir = running_config['ArchiveDir']
if resp.status.startswith('200'):
if str(file_tuple[2]).endswith('/'):
archive_dir = archive_dir + file_tuple[2]
archive_dir = archive_dir + os.path.dirname(file_tuple[2])
if not os.path.exists(archive_dir):
util.mkdir_p(archive_dir)
logging.warn(
'The ArchiveDir is no exist , mkdir %s now' % archive_dir)
if not str(file_tuple[2]).endswith('/'):
util.rename(file_tuple[2], archive_dir)
logging.warn(
'The file %s archive success' % file_tuple[2])
else:
rest = obspycmd.OBSRequestDescriptor(request_type='',
ak=user.ak, sk=user.sk,
auth_algorithm=running_config[
'AuthAlgorithm'],
virtual_host=running_config[
'VirtualHost'],
domain_name=running_config[
'DomainName'],
region=running_config[
'Region'])
try:
rest.key = file_tuple[0]
except UnicodeDecodeError:
result_for_manifest = '%s, , %s, , , FAILED:UnicodeDecodeError' % (
file_tuple[2], file_tuple[1])
logging.debug("=== the result is %s" % result_for_manifest)
update_objects_manifest(result_for_manifest)
logging.error('Decode error, key: ' + file_tuple[0])
continue
rest.bucket = running_config['BucketNameFixed']
process_multi_parts_upload(file_tuple=file_tuple,
rest=rest,
conn=conn,
worker_id=worker_id)
def organize_file_paths_for_download(file_name):
downloadTarget = str(running_config['DownloadTarget'])
filename = file_name
if ',' not in downloadTarget:
if str(downloadTarget).endswith('/'):
filename = str(file_name).replace(downloadTarget,
downloadTarget.split('/')[
-2] + '/')
elif str(downloadTarget) == '':
filename = str(file_name)
else:
filename = file_name.replace(file_name, file_name.split('/')[-1])
else:
targets = list(set(downloadTarget.split(',')))
for target in targets:
target = target.strip()
if str(file_name).startswith(target):
filename = file_name.replace(target,
target.split('/')[-2] + '/')
break
else:
filename = file_name.replace(file_name,
file_name.split('/')[-1])
break
return filename
def get_object(worker_id, conn):
while not all_objects_queue.empty():
try:
# (对象名,versionId,eTag,ContentLength)
object_tuple = all_objects_queue.get(block=False)
logging.warn('get_object tuple:' + str(object_tuple))
except Empty:
logging.debug(
"Empty when getting task tuple from queue,then continue.")
continue
file_name = object_tuple[0].encode(SYS_ENCODING)
logging.debug(
"=== file_name:%s ; size:%s ===" % (file_name, object_tuple[1]))
file_name = organize_file_paths_for_download(file_name)
save_path_parent = running_config['SavePath']
file_location = os.path.join(save_path_parent, file_name)
logging.debug("=== location file path is %s ===" % file_location)
# 如果是文件夹,则必定是空文件夹,本地创建此文件夹后跳过进行下一个队列任务
if file_location.endswith('/'):
if not os.path.isdir(file_location):
try:
os.makedirs(file_location)
except OSError:
pass
result_for_manifest = '%s, %s, %s, %s, %s, %s \n' % (
file_location,
running_config['BucketNameFixed'] + '/' + file_name,
object_tuple[3],
'', '', 'SUCCESS')