-
Notifications
You must be signed in to change notification settings - Fork 336
/
copy_helper.py
2801 lines (2434 loc) · 113 KB
/
copy_helper.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
# -*- coding: utf-8 -*-
# Copyright 2011 Google Inc. All Rights Reserved.
# Copyright 2011, Nexenta Systems Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helper functions for copy functionality."""
from __future__ import absolute_import
import base64
from collections import namedtuple
import csv
import datetime
import errno
import gzip
import hashlib
from hashlib import md5
import json
import logging
import mimetypes
import os
import pickle
import random
import re
import shutil
import stat
import subprocess
import tempfile
import textwrap
import time
import traceback
from boto import config
import crcmod
import gslib
from gslib.cloud_api import ArgumentException
from gslib.cloud_api import CloudApi
from gslib.cloud_api import NotFoundException
from gslib.cloud_api import PreconditionException
from gslib.cloud_api import Preconditions
from gslib.cloud_api import ResumableDownloadException
from gslib.cloud_api import ResumableUploadAbortException
from gslib.cloud_api import ResumableUploadException
from gslib.cloud_api import ResumableUploadStartOverException
from gslib.cloud_api_helper import GetDownloadSerializationDict
from gslib.commands.compose import MAX_COMPOSE_ARITY
from gslib.commands.config import DEFAULT_PARALLEL_COMPOSITE_UPLOAD_COMPONENT_SIZE
from gslib.commands.config import DEFAULT_PARALLEL_COMPOSITE_UPLOAD_THRESHOLD
from gslib.cs_api_map import ApiSelector
from gslib.daisy_chain_wrapper import DaisyChainWrapper
from gslib.exception import CommandException
from gslib.file_part import FilePart
from gslib.hashing_helper import Base64EncodeHash
from gslib.hashing_helper import CalculateB64EncodedMd5FromContents
from gslib.hashing_helper import CalculateHashesFromContents
from gslib.hashing_helper import GetDownloadHashAlgs
from gslib.hashing_helper import GetUploadHashAlgs
from gslib.hashing_helper import HashingFileUploadWrapper
from gslib.progress_callback import ConstructAnnounceText
from gslib.progress_callback import FileProgressCallbackHandler
from gslib.progress_callback import ProgressCallbackWithBackoff
from gslib.resumable_streaming_upload import ResumableStreamingJsonUploadWrapper
from gslib.storage_url import ContainsWildcard
from gslib.storage_url import StorageUrlFromString
from gslib.third_party.storage_apitools import storage_v1_messages as apitools_messages
from gslib.translation_helper import AddS3MarkerAclToObjectMetadata
from gslib.translation_helper import CopyObjectMetadata
from gslib.translation_helper import DEFAULT_CONTENT_TYPE
from gslib.translation_helper import GenerationFromUrlAndString
from gslib.translation_helper import ObjectMetadataFromHeaders
from gslib.translation_helper import PreconditionsFromHeaders
from gslib.translation_helper import S3MarkerAclFromObjectMetadata
from gslib.util import CreateLock
from gslib.util import CreateTrackerDirIfNeeded
from gslib.util import DEFAULT_FILE_BUFFER_SIZE
from gslib.util import GetCloudApiInstance
from gslib.util import GetFileSize
from gslib.util import GetJsonResumableChunkSize
from gslib.util import GetMaxRetryDelay
from gslib.util import GetNumRetries
from gslib.util import GetStreamFromFileUrl
from gslib.util import HumanReadableToBytes
from gslib.util import IS_WINDOWS
from gslib.util import IsCloudSubdirPlaceholder
from gslib.util import MIN_SIZE_COMPUTE_LOGGING
from gslib.util import ResumableThreshold
from gslib.util import TEN_MIB
from gslib.util import UTF8
from gslib.wildcard_iterator import CreateWildcardIterator
# pylint: disable=g-import-not-at-top
if IS_WINDOWS:
import msvcrt
from ctypes import c_int
from ctypes import c_uint64
from ctypes import c_char_p
from ctypes import c_wchar_p
from ctypes import windll
from ctypes import POINTER
from ctypes import WINFUNCTYPE
from ctypes import WinError
# Declare copy_helper_opts as a global because namedtuple isn't aware of
# assigning to a class member (which breaks pickling done by multiprocessing).
# For details see
# http://stackoverflow.com/questions/16377215/how-to-pickle-a-namedtuple-instance-correctly
# Similarly can't pickle logger.
# pylint: disable=global-at-module-level
global global_copy_helper_opts, global_logger
PARALLEL_UPLOAD_TEMP_NAMESPACE = (
u'/gsutil/tmp/parallel_composite_uploads/for_details_see/gsutil_help_cp/')
PARALLEL_UPLOAD_STATIC_SALT = u"""
PARALLEL_UPLOAD_SALT_TO_PREVENT_COLLISIONS.
The theory is that no user will have prepended this to the front of
one of their object names and then done an MD5 hash of the name, and
then prepended PARALLEL_UPLOAD_TEMP_NAMESPACE to the front of their object
name. Note that there will be no problems with object name length since we
hash the original name.
"""
TRACKER_FILE_UNWRITABLE_EXCEPTION_TEXT = (
'Couldn\'t write tracker file (%s): %s. This can happen if gsutil is '
'configured to save tracker files to an unwritable directory)')
# When uploading a file, get the following fields in the response for
# filling in command output and manifests.
UPLOAD_RETURN_FIELDS = ['crc32c', 'generation', 'md5Hash', 'size']
# This tuple is used only to encapsulate the arguments needed for
# command.Apply() in the parallel composite upload case.
# Note that content_type is used instead of a full apitools Object() because
# apitools objects are not picklable.
# filename: String name of file.
# file_start: start byte of file (may be in the middle of a file for partitioned
# files).
# file_length: length of upload (may not be the entire length of a file for
# partitioned files).
# src_url: FileUrl describing the source file.
# dst_url: CloudUrl describing the destination component file.
# canned_acl: canned_acl to apply to the uploaded file/component.
# content_type: content-type for final object, used for setting content-type
# of components and final object.
# tracker_file: tracker file for this component.
# tracker_file_lock: tracker file lock for tracker file(s).
PerformParallelUploadFileToObjectArgs = namedtuple(
'PerformParallelUploadFileToObjectArgs',
'filename file_start file_length src_url dst_url canned_acl '
'content_type tracker_file tracker_file_lock')
ObjectFromTracker = namedtuple('ObjectFromTracker',
'object_name generation')
# The maximum length of a file name can vary wildly between different
# operating systems, so we always ensure that tracker files are less
# than 100 characters in order to avoid any such issues.
MAX_TRACKER_FILE_NAME_LENGTH = 100
# TODO: Refactor this file to be less cumbersome. In particular, some of the
# different paths (e.g., uploading a file to an object vs. downloading an
# object to a file) could be split into separate files.
# Chunk size to use while zipping/unzipping gzip files.
GZIP_CHUNK_SIZE = 8192
PARALLEL_COMPOSITE_SUGGESTION_THRESHOLD = 150 * 1024 * 1024
suggested_parallel_composites = False
class TrackerFileType(object):
UPLOAD = 'upload'
DOWNLOAD = 'download'
PARALLEL_UPLOAD = 'parallel_upload'
def _RmExceptionHandler(cls, e):
"""Simple exception handler to allow post-completion status."""
cls.logger.error(str(e))
def _ParallelUploadCopyExceptionHandler(cls, e):
"""Simple exception handler to allow post-completion status."""
cls.logger.error(str(e))
cls.op_failure_count += 1
cls.logger.debug('\n\nEncountered exception while copying:\n%s\n',
traceback.format_exc())
def _PerformParallelUploadFileToObject(cls, args, thread_state=None):
"""Function argument to Apply for performing parallel composite uploads.
Args:
cls: Calling Command class.
args: PerformParallelUploadFileToObjectArgs tuple describing the target.
thread_state: gsutil Cloud API instance to use for the operation.
Returns:
StorageUrl representing a successfully uploaded component.
"""
fp = FilePart(args.filename, args.file_start, args.file_length)
gsutil_api = GetCloudApiInstance(cls, thread_state=thread_state)
with fp:
# We take many precautions with the component names that make collisions
# effectively impossible. Specifying preconditions will just allow us to
# reach a state in which uploads will always fail on retries.
preconditions = None
# Fill in content type if one was provided.
dst_object_metadata = apitools_messages.Object(
name=args.dst_url.object_name,
bucket=args.dst_url.bucket_name,
contentType=args.content_type)
try:
if global_copy_helper_opts.canned_acl:
# No canned ACL support in JSON, force XML API to be used for
# upload/copy operations.
orig_prefer_api = gsutil_api.prefer_api
gsutil_api.prefer_api = ApiSelector.XML
ret = _UploadFileToObject(args.src_url, fp, args.file_length,
args.dst_url, dst_object_metadata,
preconditions, gsutil_api, cls.logger, cls,
_ParallelUploadCopyExceptionHandler,
gzip_exts=None, allow_splitting=False)
finally:
if global_copy_helper_opts.canned_acl:
gsutil_api.prefer_api = orig_prefer_api
component = ret[2]
_AppendComponentTrackerToParallelUploadTrackerFile(
args.tracker_file, component, args.tracker_file_lock)
return ret
CopyHelperOpts = namedtuple('CopyHelperOpts', [
'perform_mv',
'no_clobber',
'daisy_chain',
'read_args_from_stdin',
'print_ver',
'use_manifest',
'preserve_acl',
'canned_acl',
'test_callback_file'])
# pylint: disable=global-variable-undefined
def CreateCopyHelperOpts(perform_mv=False, no_clobber=False, daisy_chain=False,
read_args_from_stdin=False, print_ver=False,
use_manifest=False, preserve_acl=False,
canned_acl=None, test_callback_file=None):
"""Creates CopyHelperOpts for passing options to CopyHelper."""
# We create a tuple with union of options needed by CopyHelper and any
# copy-related functionality in CpCommand, RsyncCommand, or Command class.
global global_copy_helper_opts
global_copy_helper_opts = CopyHelperOpts(
perform_mv=perform_mv,
no_clobber=no_clobber,
daisy_chain=daisy_chain,
read_args_from_stdin=read_args_from_stdin,
print_ver=print_ver,
use_manifest=use_manifest,
preserve_acl=preserve_acl,
canned_acl=canned_acl,
test_callback_file=test_callback_file)
return global_copy_helper_opts
# pylint: disable=global-variable-undefined
# pylint: disable=global-variable-not-assigned
def GetCopyHelperOpts():
"""Returns namedtuple holding CopyHelper options."""
global global_copy_helper_opts
return global_copy_helper_opts
def GetTrackerFilePath(dst_url, tracker_file_type, api_selector, src_url=None):
"""Gets the tracker file name described by the arguments.
Public for testing purposes.
Args:
dst_url: Destination URL for tracker file.
tracker_file_type: TrackerFileType for this operation.
api_selector: API to use for this operation.
src_url: Source URL for the source file name for parallel uploads.
Returns:
File path to tracker file.
"""
resumable_tracker_dir = CreateTrackerDirIfNeeded()
if tracker_file_type == TrackerFileType.UPLOAD:
# Encode the dest bucket and object name into the tracker file name.
res_tracker_file_name = (
re.sub('[/\\\\]', '_', 'resumable_upload__%s__%s__%s.url' %
(dst_url.bucket_name, dst_url.object_name, api_selector)))
elif tracker_file_type == TrackerFileType.DOWNLOAD:
# Encode the fully-qualified dest file name into the tracker file name.
res_tracker_file_name = (
re.sub('[/\\\\]', '_', 'resumable_download__%s__%s.etag' %
(os.path.realpath(dst_url.object_name), api_selector)))
elif tracker_file_type == TrackerFileType.PARALLEL_UPLOAD:
# Encode the dest bucket and object names as well as the source file name
# into the tracker file name.
res_tracker_file_name = (
re.sub('[/\\\\]', '_', 'parallel_upload__%s__%s__%s__%s.url' %
(dst_url.bucket_name, dst_url.object_name,
src_url, api_selector)))
res_tracker_file_name = _HashFilename(res_tracker_file_name)
tracker_file_name = '%s_%s' % (str(tracker_file_type).lower(),
res_tracker_file_name)
tracker_file_path = '%s%s%s' % (resumable_tracker_dir, os.sep,
tracker_file_name)
assert len(tracker_file_name) < MAX_TRACKER_FILE_NAME_LENGTH
return tracker_file_path
def _SelectDownloadStrategy(dst_url):
"""Get download strategy based on the destination object.
Args:
dst_url: Destination StorageUrl.
Returns:
gsutil Cloud API DownloadStrategy.
"""
dst_is_special = False
if dst_url.IsFileUrl():
# Check explicitly first because os.stat doesn't work on 'nul' in Windows.
if dst_url.object_name == os.devnull:
dst_is_special = True
try:
mode = os.stat(dst_url.object_name).st_mode
if stat.S_ISCHR(mode):
dst_is_special = True
except OSError:
pass
if dst_is_special:
return CloudApi.DownloadStrategy.ONE_SHOT
else:
return CloudApi.DownloadStrategy.RESUMABLE
def _GetUploadTrackerData(tracker_file_name, logger):
"""Reads tracker data from an upload tracker file if it exists.
Args:
tracker_file_name: Tracker file name for this upload.
logger: for outputting log messages.
Returns:
Serialization data if the tracker file already exists (resume existing
upload), None otherwise.
"""
tracker_file = None
# If we already have a matching tracker file, get the serialization data
# so that we can resume the upload.
try:
tracker_file = open(tracker_file_name, 'r')
tracker_data = tracker_file.read()
return tracker_data
except IOError as e:
# Ignore non-existent file (happens first time a upload is attempted on an
# object, or when re-starting an upload after a
# ResumableUploadStartOverException), but warn user for other errors.
if e.errno != errno.ENOENT:
logger.warn('Couldn\'t read upload tracker file (%s): %s. Restarting '
'upload from scratch.', tracker_file_name, e.strerror)
finally:
if tracker_file:
tracker_file.close()
def _ReadOrCreateDownloadTrackerFile(src_obj_metadata, dst_url,
api_selector):
"""Checks for a download tracker file and creates one if it does not exist.
Args:
src_obj_metadata: Metadata for the source object. Must include
etag.
dst_url: Destination file StorageUrl.
api_selector: API mode to use (for tracker file naming).
Returns:
True if the tracker file already exists (resume existing download),
False if we created a new tracker file (new download).
"""
assert src_obj_metadata.etag
tracker_file_name = GetTrackerFilePath(
dst_url, TrackerFileType.DOWNLOAD, api_selector)
tracker_file = None
# Check to see if we already have a matching tracker file.
try:
tracker_file = open(tracker_file_name, 'r')
etag_value = tracker_file.readline().rstrip('\n')
if etag_value == src_obj_metadata.etag:
return True
except IOError as e:
# Ignore non-existent file (happens first time a download
# is attempted on an object), but warn user for other errors.
if e.errno != errno.ENOENT:
print('Couldn\'t read URL tracker file (%s): %s. Restarting '
'download from scratch.' %
(tracker_file_name, e.strerror))
finally:
if tracker_file:
tracker_file.close()
# Otherwise, create a new tracker file and start from scratch.
try:
with os.fdopen(os.open(tracker_file_name,
os.O_WRONLY | os.O_CREAT, 0600), 'w') as tf:
tf.write('%s\n' % src_obj_metadata.etag)
return False
except (IOError, OSError) as e:
if src_obj_metadata.size < ResumableThreshold():
# Small downloads used to be written in one shot without writing a
# tracker file. For backwards compatibility, they must continue to
# function even if the tracker file/dir is not writable. Fall through
# so the download will be retriable/resumable; resumes across process
# breaks will not be supported.
pass
else:
raise CommandException(TRACKER_FILE_UNWRITABLE_EXCEPTION_TEXT %
(tracker_file_name, e.strerror))
finally:
if tracker_file:
tracker_file.close()
def _DeleteTrackerFile(tracker_file_name):
if tracker_file_name and os.path.exists(tracker_file_name):
os.unlink(tracker_file_name)
def InsistDstUrlNamesContainer(exp_dst_url, have_existing_dst_container,
command_name):
"""Ensures the destination URL names a container.
Acceptable containers include directory, bucket, bucket
subdir, and non-existent bucket subdir.
Args:
exp_dst_url: Wildcard-expanded destination StorageUrl.
have_existing_dst_container: bool indicator of whether exp_dst_url
names a container (directory, bucket, or existing bucket subdir).
command_name: Name of command making call. May not be the same as the
calling class's self.command_name in the case of commands implemented
atop other commands (like mv command).
Raises:
CommandException: if the URL being checked does not name a container.
"""
if ((exp_dst_url.IsFileUrl() and not exp_dst_url.IsDirectory()) or
(exp_dst_url.IsCloudUrl() and exp_dst_url.IsBucket()
and not have_existing_dst_container)):
raise CommandException('Destination URL must name a directory, bucket, '
'or bucket\nsubdirectory for the multiple '
'source form of the %s command.' % command_name)
def _ShouldTreatDstUrlAsBucketSubDir(have_multiple_srcs, dst_url,
have_existing_dest_subdir,
src_url_names_container,
recursion_requested):
"""Checks whether dst_url should be treated as a bucket "sub-directory".
The decision about whether something constitutes a bucket "sub-directory"
depends on whether there are multiple sources in this request and whether
there is an existing bucket subdirectory. For example, when running the
command:
gsutil cp file gs://bucket/abc
if there's no existing gs://bucket/abc bucket subdirectory we should copy
file to the object gs://bucket/abc. In contrast, if
there's an existing gs://bucket/abc bucket subdirectory we should copy
file to gs://bucket/abc/file. And regardless of whether gs://bucket/abc
exists, when running the command:
gsutil cp file1 file2 gs://bucket/abc
we should copy file1 to gs://bucket/abc/file1 (and similarly for file2).
Finally, for recursive copies, if the source is a container then we should
copy to a container as the target. For example, when running the command:
gsutil cp -r dir1 gs://bucket/dir2
we should copy the subtree of dir1 to gs://bucket/dir2.
Note that we don't disallow naming a bucket "sub-directory" where there's
already an object at that URL. For example it's legitimate (albeit
confusing) to have an object called gs://bucket/dir and
then run the command
gsutil cp file1 file2 gs://bucket/dir
Doing so will end up with objects gs://bucket/dir, gs://bucket/dir/file1,
and gs://bucket/dir/file2.
Args:
have_multiple_srcs: Bool indicator of whether this is a multi-source
operation.
dst_url: StorageUrl to check.
have_existing_dest_subdir: bool indicator whether dest is an existing
subdirectory.
src_url_names_container: bool indicator of whether the source URL
is a container.
recursion_requested: True if a recursive operation has been requested.
Returns:
bool indicator.
"""
if have_existing_dest_subdir:
return True
if dst_url.IsCloudUrl():
return (have_multiple_srcs or
(src_url_names_container and recursion_requested))
def _ShouldTreatDstUrlAsSingleton(have_multiple_srcs,
have_existing_dest_subdir, dst_url,
recursion_requested):
"""Checks that dst_url names a single file/object after wildcard expansion.
It is possible that an object path might name a bucket sub-directory.
Args:
have_multiple_srcs: Bool indicator of whether this is a multi-source
operation.
have_existing_dest_subdir: bool indicator whether dest is an existing
subdirectory.
dst_url: StorageUrl to check.
recursion_requested: True if a recursive operation has been requested.
Returns:
bool indicator.
"""
if recursion_requested:
return False
if dst_url.IsFileUrl():
return not dst_url.IsDirectory()
else: # dst_url.IsCloudUrl()
return (not have_multiple_srcs and
not have_existing_dest_subdir and
dst_url.IsObject())
def ConstructDstUrl(src_url, exp_src_url, src_url_names_container,
have_multiple_srcs, exp_dst_url, have_existing_dest_subdir,
recursion_requested):
"""Constructs the destination URL for a given exp_src_url/exp_dst_url pair.
Uses context-dependent naming rules that mimic Linux cp and mv behavior.
Args:
src_url: Source StorageUrl to be copied.
exp_src_url: Single StorageUrl from wildcard expansion of src_url.
src_url_names_container: True if src_url names a container (including the
case of a wildcard-named bucket subdir (like gs://bucket/abc,
where gs://bucket/abc/* matched some objects).
have_multiple_srcs: True if this is a multi-source request. This can be
true if src_url wildcard-expanded to multiple URLs or if there were
multiple source URLs in the request.
exp_dst_url: the expanded StorageUrl requested for the cp destination.
Final written path is constructed from this plus a context-dependent
variant of src_url.
have_existing_dest_subdir: bool indicator whether dest is an existing
subdirectory.
recursion_requested: True if a recursive operation has been requested.
Returns:
StorageUrl to use for copy.
Raises:
CommandException if destination object name not specified for
source and source is a stream.
"""
if _ShouldTreatDstUrlAsSingleton(
have_multiple_srcs, have_existing_dest_subdir, exp_dst_url,
recursion_requested):
# We're copying one file or object to one file or object.
return exp_dst_url
if exp_src_url.IsFileUrl() and exp_src_url.IsStream():
if have_existing_dest_subdir:
raise CommandException('Destination object name needed when '
'source is a stream')
return exp_dst_url
if not recursion_requested and not have_multiple_srcs:
# We're copying one file or object to a subdirectory. Append final comp
# of exp_src_url to exp_dst_url.
src_final_comp = exp_src_url.object_name.rpartition(src_url.delim)[-1]
return StorageUrlFromString('%s%s%s' % (
exp_dst_url.url_string.rstrip(exp_dst_url.delim),
exp_dst_url.delim, src_final_comp))
# Else we're copying multiple sources to a directory, bucket, or a bucket
# "sub-directory".
# Ensure exp_dst_url ends in delim char if we're doing a multi-src copy or
# a copy to a directory. (The check for copying to a directory needs
# special-case handling so that the command:
# gsutil cp gs://bucket/obj dir
# will turn into file://dir/ instead of file://dir -- the latter would cause
# the file "dirobj" to be created.)
# Note: need to check have_multiple_srcs or src_url.names_container()
# because src_url could be a bucket containing a single object, named
# as gs://bucket.
if ((have_multiple_srcs or src_url_names_container or
(exp_dst_url.IsFileUrl() and exp_dst_url.IsDirectory()))
and not exp_dst_url.url_string.endswith(exp_dst_url.delim)):
exp_dst_url = StorageUrlFromString('%s%s' % (exp_dst_url.url_string,
exp_dst_url.delim))
# Making naming behavior match how things work with local Linux cp and mv
# operations depends on many factors, including whether the destination is a
# container, the plurality of the source(s), and whether the mv command is
# being used:
# 1. For the "mv" command that specifies a non-existent destination subdir,
# renaming should occur at the level of the src subdir, vs appending that
# subdir beneath the dst subdir like is done for copying. For example:
# gsutil rm -r gs://bucket
# gsutil cp -r dir1 gs://bucket
# gsutil cp -r dir2 gs://bucket/subdir1
# gsutil mv gs://bucket/subdir1 gs://bucket/subdir2
# would (if using cp naming behavior) end up with paths like:
# gs://bucket/subdir2/subdir1/dir2/.svn/all-wcprops
# whereas mv naming behavior should result in:
# gs://bucket/subdir2/dir2/.svn/all-wcprops
# 2. Copying from directories, buckets, or bucket subdirs should result in
# objects/files mirroring the source directory hierarchy. For example:
# gsutil cp dir1/dir2 gs://bucket
# should create the object gs://bucket/dir2/file2, assuming dir1/dir2
# contains file2).
# To be consistent with Linux cp behavior, there's one more wrinkle when
# working with subdirs: The resulting object names depend on whether the
# destination subdirectory exists. For example, if gs://bucket/subdir
# exists, the command:
# gsutil cp -r dir1/dir2 gs://bucket/subdir
# should create objects named like gs://bucket/subdir/dir2/a/b/c. In
# contrast, if gs://bucket/subdir does not exist, this same command
# should create objects named like gs://bucket/subdir/a/b/c.
# 3. Copying individual files or objects to dirs, buckets or bucket subdirs
# should result in objects/files named by the final source file name
# component. Example:
# gsutil cp dir1/*.txt gs://bucket
# should create the objects gs://bucket/f1.txt and gs://bucket/f2.txt,
# assuming dir1 contains f1.txt and f2.txt.
recursive_move_to_new_subdir = False
if (global_copy_helper_opts.perform_mv and recursion_requested
and src_url_names_container and not have_existing_dest_subdir):
# Case 1. Handle naming rules for bucket subdir mv. Here we want to
# line up the src_url against its expansion, to find the base to build
# the new name. For example, running the command:
# gsutil mv gs://bucket/abcd gs://bucket/xyz
# when processing exp_src_url=gs://bucket/abcd/123
# exp_src_url_tail should become /123
# Note: mv.py code disallows wildcard specification of source URL.
recursive_move_to_new_subdir = True
exp_src_url_tail = (
exp_src_url.url_string[len(src_url.url_string):])
dst_key_name = '%s/%s' % (exp_dst_url.object_name.rstrip('/'),
exp_src_url_tail.strip('/'))
elif src_url_names_container and (exp_dst_url.IsCloudUrl() or
exp_dst_url.IsDirectory()):
# Case 2. Container copy to a destination other than a file.
# Build dst_key_name from subpath of exp_src_url past
# where src_url ends. For example, for src_url=gs://bucket/ and
# exp_src_url=gs://bucket/src_subdir/obj, dst_key_name should be
# src_subdir/obj.
src_url_path_sans_final_dir = GetPathBeforeFinalDir(src_url)
dst_key_name = exp_src_url.versionless_url_string[
len(src_url_path_sans_final_dir):].lstrip(src_url.delim)
# Handle case where dst_url is a non-existent subdir.
if not have_existing_dest_subdir:
dst_key_name = dst_key_name.partition(src_url.delim)[-1]
# Handle special case where src_url was a directory named with '.' or
# './', so that running a command like:
# gsutil cp -r . gs://dest
# will produce obj names of the form gs://dest/abc instead of
# gs://dest/./abc.
if dst_key_name.startswith('.%s' % os.sep):
dst_key_name = dst_key_name[2:]
else:
# Case 3.
dst_key_name = exp_src_url.object_name.rpartition(src_url.delim)[-1]
if (not recursive_move_to_new_subdir and (
exp_dst_url.IsFileUrl() or _ShouldTreatDstUrlAsBucketSubDir(
have_multiple_srcs, exp_dst_url, have_existing_dest_subdir,
src_url_names_container, recursion_requested))):
if exp_dst_url.object_name and exp_dst_url.object_name.endswith(
exp_dst_url.delim):
dst_key_name = '%s%s%s' % (
exp_dst_url.object_name.rstrip(exp_dst_url.delim),
exp_dst_url.delim, dst_key_name)
else:
delim = exp_dst_url.delim if exp_dst_url.object_name else ''
dst_key_name = '%s%s%s' % (exp_dst_url.object_name or '',
delim, dst_key_name)
new_exp_dst_url = exp_dst_url.Clone()
new_exp_dst_url.object_name = dst_key_name.replace(src_url.delim,
exp_dst_url.delim)
return new_exp_dst_url
def _CreateDigestsFromDigesters(digesters):
digests = {}
if digesters:
for alg in digesters:
digests[alg] = base64.encodestring(
digesters[alg].digest()).rstrip('\n')
return digests
def _CreateDigestsFromLocalFile(logger, algs, file_name, src_obj_metadata):
"""Creates a base64 CRC32C and/or MD5 digest from file_name.
Args:
logger: for outputting log messages.
algs: list of algorithms to compute.
file_name: file to digest.
src_obj_metadata: metadta of source object.
Returns:
Dict of algorithm name : base 64 encoded digest
"""
hash_dict = {}
if 'md5' in algs:
if src_obj_metadata.size and src_obj_metadata.size > TEN_MIB:
logger.info(
'Computing MD5 for %s...', file_name)
hash_dict['md5'] = md5()
if 'crc32c' in algs:
hash_dict['crc32c'] = crcmod.predefined.Crc('crc-32c')
with open(file_name, 'rb') as fp:
CalculateHashesFromContents(
fp, hash_dict, ProgressCallbackWithBackoff(
src_obj_metadata.size,
FileProgressCallbackHandler(
ConstructAnnounceText('Hashing', file_name), logger).call))
digests = {}
for alg_name, digest in hash_dict.iteritems():
digests[alg_name] = Base64EncodeHash(digest.hexdigest())
return digests
def _CheckCloudHashes(logger, src_url, dst_url, src_obj_metadata,
dst_obj_metadata):
"""Validates integrity of two cloud objects copied via daisy-chain.
Args:
logger: for outputting log messages.
src_url: CloudUrl for source cloud object.
dst_url: CloudUrl for destination cloud object.
src_obj_metadata: Cloud Object metadata for object being downloaded from.
dst_obj_metadata: Cloud Object metadata for object being uploaded to.
Raises:
CommandException: if cloud digests don't match local digests.
"""
checked_one = False
download_hashes = {}
upload_hashes = {}
if src_obj_metadata.md5Hash:
download_hashes['md5'] = src_obj_metadata.md5Hash
if src_obj_metadata.crc32c:
download_hashes['crc32c'] = src_obj_metadata.crc32c
if dst_obj_metadata.md5Hash:
upload_hashes['md5'] = dst_obj_metadata.md5Hash
if dst_obj_metadata.crc32c:
upload_hashes['crc32c'] = dst_obj_metadata.crc32c
for alg, upload_b64_digest in upload_hashes.iteritems():
if alg not in download_hashes:
continue
download_b64_digest = download_hashes[alg]
logger.debug(
'Comparing source vs destination %s-checksum for %s. (%s/%s)', alg,
dst_url, download_b64_digest, upload_b64_digest)
if download_b64_digest != upload_b64_digest:
raise CommandException(
'%s signature for source object (%s) doesn\'t match '
'destination object digest (%s). Object (%s) will be deleted.' % (
alg, download_b64_digest, upload_b64_digest, dst_url))
checked_one = True
if not checked_one:
# One known way this can currently happen is when downloading objects larger
# than 5 GiB from S3 (for which the etag is not an MD5).
logger.warn(
'WARNING: Found no hashes to validate object downloaded from %s and '
'uploaded to %s. Integrity cannot be assured without hashes.',
src_url, dst_url)
def _CheckHashes(logger, obj_url, obj_metadata, file_name, digests,
is_upload=False):
"""Validates integrity by comparing cloud digest to local digest.
Args:
logger: for outputting log messages.
obj_url: CloudUrl for cloud object.
obj_metadata: Cloud Object being downloaded from or uploaded to.
file_name: Local file name on disk being downloaded to or uploaded from.
digests: Computed Digests for the object.
is_upload: If true, comparing for an uploaded object (controls logging).
Raises:
CommandException: if cloud digests don't match local digests.
"""
local_hashes = digests
cloud_hashes = {}
if obj_metadata.md5Hash:
cloud_hashes['md5'] = obj_metadata.md5Hash.rstrip('\n')
if obj_metadata.crc32c:
cloud_hashes['crc32c'] = obj_metadata.crc32c.rstrip('\n')
checked_one = False
for alg in local_hashes:
if alg not in cloud_hashes:
continue
local_b64_digest = local_hashes[alg]
cloud_b64_digest = cloud_hashes[alg]
logger.debug(
'Comparing local vs cloud %s-checksum for %s. (%s/%s)', alg, file_name,
local_b64_digest, cloud_b64_digest)
if local_b64_digest != cloud_b64_digest:
raise CommandException(
'%s signature computed for local file (%s) doesn\'t match '
'cloud-supplied digest (%s). %s (%s) will be deleted.' % (
alg, local_b64_digest, cloud_b64_digest,
'Cloud object' if is_upload else 'Local file',
obj_url if is_upload else file_name))
checked_one = True
if not checked_one:
if is_upload:
logger.warn(
'WARNING: Found no hashes to validate object uploaded to %s. '
'Integrity cannot be assured without hashes.', obj_url)
else:
# One known way this can currently happen is when downloading objects larger
# than 5 GB from S3 (for which the etag is not an MD5).
logger.warn(
'WARNING: Found no hashes to validate object downloaded to %s. '
'Integrity cannot be assured without hashes.', file_name)
def IsNoClobberServerException(e):
"""Checks to see if the server attempted to clobber a file.
In this case we specified via a precondition that we didn't want the file
clobbered.
Args:
e: The Exception that was generated by a failed copy operation
Returns:
bool indicator - True indicates that the server did attempt to clobber
an existing file.
"""
return ((isinstance(e, PreconditionException)) or
(isinstance(e, ResumableUploadException) and '412' in e.message))
def CheckForDirFileConflict(exp_src_url, dst_url):
"""Checks whether copying exp_src_url into dst_url is not possible.
This happens if a directory exists in local file system where a file
needs to go or vice versa. In that case we print an error message and
exits. Example: if the file "./x" exists and you try to do:
gsutil cp gs://mybucket/x/y .
the request can't succeed because it requires a directory where
the file x exists.
Note that we don't enforce any corresponding restrictions for buckets,
because the flat namespace semantics for buckets doesn't prohibit such
cases the way hierarchical file systems do. For example, if a bucket
contains an object called gs://bucket/dir and then you run the command:
gsutil cp file1 file2 gs://bucket/dir
you'll end up with objects gs://bucket/dir, gs://bucket/dir/file1, and
gs://bucket/dir/file2.
Args:
exp_src_url: Expanded source StorageUrl.
dst_url: Destination StorageUrl.
Raises:
CommandException: if errors encountered.
"""
if dst_url.IsCloudUrl():
# The problem can only happen for file destination URLs.
return
dst_path = dst_url.object_name
final_dir = os.path.dirname(dst_path)
if os.path.isfile(final_dir):
raise CommandException('Cannot retrieve %s because a file exists '
'where a directory needs to be created (%s).' %
(exp_src_url.url_string, final_dir))
if os.path.isdir(dst_path):
raise CommandException('Cannot retrieve %s because a directory exists '
'(%s) where the file needs to be created.' %
(exp_src_url.url_string, dst_path))
def _PartitionFile(fp, file_size, src_url, content_type, canned_acl,
dst_bucket_url, random_prefix, tracker_file,
tracker_file_lock):
"""Partitions a file into FilePart objects to be uploaded and later composed.
These objects, when composed, will match the original file. This entails
splitting the file into parts, naming and forming a destination URL for each
part, and also providing the PerformParallelUploadFileToObjectArgs
corresponding to each part.
Args:
fp: The file object to be partitioned.
file_size: The size of fp, in bytes.
src_url: Source FileUrl from the original command.
content_type: content type for the component and final objects.
canned_acl: The user-provided canned_acl, if applicable.
dst_bucket_url: CloudUrl for the destination bucket
random_prefix: The randomly-generated prefix used to prevent collisions
among the temporary component names.
tracker_file: The path to the parallel composite upload tracker file.
tracker_file_lock: The lock protecting access to the tracker file.
Returns:
dst_args: The destination URIs for the temporary component objects.
"""
parallel_composite_upload_component_size = HumanReadableToBytes(
config.get('GSUtil', 'parallel_composite_upload_component_size',
DEFAULT_PARALLEL_COMPOSITE_UPLOAD_COMPONENT_SIZE))
(num_components, component_size) = _GetPartitionInfo(
file_size, MAX_COMPOSE_ARITY, parallel_composite_upload_component_size)
dst_args = {} # Arguments to create commands and pass to subprocesses.
file_names = [] # Used for the 2-step process of forming dst_args.
for i in range(num_components):
# "Salt" the object name with something a user is very unlikely to have
# used in an object name, then hash the extended name to make sure
# we don't run into problems with name length. Using a deterministic
# naming scheme for the temporary components allows users to take
# advantage of resumable uploads for each component.
encoded_name = (PARALLEL_UPLOAD_STATIC_SALT + fp.name).encode(UTF8)
content_md5 = md5()
content_md5.update(encoded_name)
digest = content_md5.hexdigest()
temp_file_name = (random_prefix + PARALLEL_UPLOAD_TEMP_NAMESPACE +
digest + '_' + str(i))
tmp_dst_url = dst_bucket_url.Clone()
tmp_dst_url.object_name = temp_file_name
if i < (num_components - 1):
# Every component except possibly the last is the same size.
file_part_length = component_size
else:
# The last component just gets all of the remaining bytes.
file_part_length = (file_size - ((num_components -1) * component_size))
offset = i * component_size
func_args = PerformParallelUploadFileToObjectArgs(
fp.name, offset, file_part_length, src_url, tmp_dst_url, canned_acl,
content_type, tracker_file, tracker_file_lock)
file_names.append(temp_file_name)
dst_args[temp_file_name] = func_args
return dst_args
def _DoParallelCompositeUpload(fp, src_url, dst_url, dst_obj_metadata,
canned_acl, file_size, preconditions, gsutil_api,
command_obj, copy_exception_handler):
"""Uploads a local file to a cloud object using parallel composite upload.
The file is partitioned into parts, and then the parts are uploaded in
parallel, composed to form the original destination object, and deleted.
Args:
fp: The file object to be uploaded.
src_url: FileUrl representing the local file.
dst_url: CloudUrl representing the destination file.
dst_obj_metadata: apitools Object describing the destination object.
canned_acl: The canned acl to apply to the object, if any.