-
Notifications
You must be signed in to change notification settings - Fork 654
/
helper.py
3120 lines (2614 loc) · 118 KB
/
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
from __future__ import with_statement
import errno
import getpass
import itertools
import json
import mimetypes
import os
import platform
import shutil
import sys
import threading
import uuid
from abc import ABCMeta, abstractmethod
from collections import namedtuple
from concurrent.futures import ThreadPoolExecutor
from copy import copy
from datetime import datetime
from multiprocessing.pool import ThreadPool
from tempfile import mkstemp
from time import time
from types import GeneratorType
import requests
import six
from _socket import gethostname
from attr import attrs, attrib, asdict
from furl import furl
from pathlib2 import Path
from requests import codes as requests_codes
from requests.exceptions import ConnectionError
from six import binary_type, StringIO
from six.moves.queue import Queue, Empty
from six.moves.urllib.parse import urlparse
from clearml.utilities.requests_toolbelt import MultipartEncoderMonitor, MultipartEncoder
from .callbacks import UploadProgressReport, DownloadProgressReport
from .util import quote_url
from ..backend_api.session import Session
from ..backend_api.utils import get_http_session_with_retry
from ..backend_config.bucket_config import S3BucketConfigurations, GSBucketConfigurations, AzureContainerConfigurations
from ..config import config, deferred_config
from ..debugging import get_logger
from ..errors import UsageError
from ..utilities.process.mp import ForkSafeRLock, SafeEvent
class StorageError(Exception):
pass
class DownloadError(Exception):
pass
@six.add_metaclass(ABCMeta)
class _Driver(object):
_certs_cache_context = "certs"
_file_server_hosts = None
@classmethod
def get_logger(cls):
return get_logger('storage')
@abstractmethod
def get_container(self, container_name, config=None, **kwargs):
pass
@abstractmethod
def test_upload(self, test_path, config, **kwargs):
pass
@abstractmethod
def upload_object_via_stream(self, iterator, container, object_name, extra, **kwargs):
pass
@abstractmethod
def list_container_objects(self, container, ex_prefix=None, **kwargs):
pass
@abstractmethod
def get_direct_access(self, remote_path, **kwargs):
pass
@abstractmethod
def download_object(self, obj, local_path, overwrite_existing, delete_on_failure, callback, **kwargs):
pass
@abstractmethod
def download_object_as_stream(self, obj, chunk_size, **kwargs):
pass
@abstractmethod
def delete_object(self, obj, **kwargs):
pass
@abstractmethod
def upload_object(self, file_path, container, object_name, extra, **kwargs):
pass
@abstractmethod
def get_object(self, container_name, object_name, **kwargs):
pass
@abstractmethod
def exists_file(self, container_name, object_name):
pass
@classmethod
def get_file_server_hosts(cls):
if cls._file_server_hosts is None:
hosts = [Session.get_files_server_host()] + (Session.legacy_file_servers or [])
for host in hosts[:]:
substituted = StorageHelper._apply_url_substitutions(host)
if substituted not in hosts:
hosts.append(substituted)
cls._file_server_hosts = hosts
return cls._file_server_hosts
@classmethod
def download_cert(cls, cert_url):
# import here to avoid circular imports
from .manager import StorageManager
cls.get_logger().info("Attempting to download remote certificate '{}'".format(cert_url))
potential_exception = None
downloaded_verify = None
try:
downloaded_verify = StorageManager.get_local_copy(cert_url, cache_context=cls._certs_cache_context)
except Exception as e:
potential_exception = e
if not downloaded_verify:
cls.get_logger().error(
"Failed downloading remote certificate '{}'{}".format(
cert_url, "Error is: {}".format(potential_exception) if potential_exception else ""
)
)
else:
cls.get_logger().info("Successfully downloaded remote certificate '{}'".format(cert_url))
return downloaded_verify
class _HttpDriver(_Driver):
""" LibCloud http/https adapter (simple, enough for now) """
timeout_connection = deferred_config('http.timeout.connection', 30)
timeout_total = deferred_config('http.timeout.total', 30)
max_retries = deferred_config('http.download.max_retries', 15)
min_kbps_speed = 50
schemes = ('http', 'https')
class _Container(object):
_default_backend_session = None
def __init__(self, name, retries=5, **kwargs):
self.name = name
self.session = get_http_session_with_retry(
total=retries,
connect=retries,
read=retries,
redirect=retries,
backoff_factor=0.5,
backoff_max=120,
status_forcelist=[
requests_codes.request_timeout,
requests_codes.timeout,
requests_codes.bad_gateway,
requests_codes.service_unavailable,
requests_codes.bandwidth_limit_exceeded,
requests_codes.too_many_requests,
],
config=config
)
self._file_server_hosts = set(_HttpDriver.get_file_server_hosts())
def _should_attach_auth_header(self):
return any(
(self.name.rstrip('/') == host.rstrip('/') or self.name.startswith(host.rstrip('/') + '/'))
for host in self._file_server_hosts
)
def get_headers(self, _):
if not self._default_backend_session:
from ..backend_interface.base import InterfaceBase
self._default_backend_session = InterfaceBase._get_default_session()
if self._should_attach_auth_header():
return self._default_backend_session.add_auth_headers({})
class _HttpSessionHandle(object):
def __init__(self, url, is_stream, container_name, object_name):
self.url, self.is_stream, self.container_name, self.object_name = \
url, is_stream, container_name, object_name
def __init__(self, retries=None):
self._retries = retries or int(self.max_retries)
self._containers = {}
def get_container(self, container_name, config=None, **kwargs):
if container_name not in self._containers:
self._containers[container_name] = self._Container(name=container_name, retries=self._retries, **kwargs)
return self._containers[container_name]
def upload_object_via_stream(self, iterator, container, object_name, extra=None, callback=None, **kwargs):
def monitor_callback(monitor):
new_chunk = monitor.bytes_read - monitor.previous_read
monitor.previous_read = monitor.bytes_read
try:
callback(new_chunk)
except Exception as ex:
self.get_logger().debug('Exception raised when running callback function: {}'.format(ex))
# when sending data in post, there is no connection timeout, just an entire upload timeout
timeout = int(self.timeout_total)
url = container.name
path = object_name
if not urlparse(url).netloc:
host, _, path = object_name.partition('/')
url += host + '/'
stream_size = None
if hasattr(iterator, 'tell') and hasattr(iterator, 'seek'):
pos = iterator.tell()
iterator.seek(0, 2)
stream_size = iterator.tell() - pos
iterator.seek(pos, 0)
timeout = max(timeout, (stream_size / 1024) / float(self.min_kbps_speed))
m = MultipartEncoder(fields={path: (path, iterator, get_file_mimetype(object_name))})
if callback and stream_size:
m = MultipartEncoderMonitor(m, callback=monitor_callback)
m.previous_read = 0
headers = {
'Content-Type': m.content_type,
}
headers.update(container.get_headers(url) or {})
res = container.session.post(
url, data=m, timeout=timeout, headers=headers
)
if res.status_code != requests.codes.ok:
raise ValueError('Failed uploading object %s (%d): %s' % (object_name, res.status_code, res.text))
# call back is useless because we are not calling it while uploading...
return res
def list_container_objects(self, *args, **kwargs):
raise NotImplementedError('List is not implemented for http protocol')
def delete_object(self, obj, *args, **kwargs):
assert isinstance(obj, self._HttpSessionHandle)
container = self._containers[obj.container_name]
res = container.session.delete(obj.url, headers=container.get_headers(obj.url))
if res.status_code != requests.codes.ok:
self.get_logger().warning('Failed deleting object %s (%d): %s' % (
obj.object_name, res.status_code, res.text))
return False
return True
def get_object(self, container_name, object_name, *args, **kwargs):
is_stream = kwargs.get('stream', True)
url = '/'.join((
container_name[:-1] if container_name.endswith('/') else container_name,
object_name.lstrip('/')
))
return self._HttpSessionHandle(url, is_stream, container_name, object_name)
def _get_download_object(self, obj):
# bypass for session result
if not isinstance(obj, self._HttpSessionHandle):
return obj
container = self._containers[obj.container_name]
# set stream flag before we send the request
container.session.stream = obj.is_stream
res = container.session.get(
obj.url, timeout=(int(self.timeout_connection), int(self.timeout_total)),
headers=container.get_headers(obj.url))
if res.status_code != requests.codes.ok:
raise ValueError('Failed getting object %s (%d): %s' % (obj.object_name, res.status_code, res.reason))
return res
def download_object_as_stream(self, obj, chunk_size=64 * 1024, **_):
# return iterable object
obj = self._get_download_object(obj)
return obj.iter_content(chunk_size=chunk_size)
def download_object(self, obj, local_path, overwrite_existing=True, delete_on_failure=True, callback=None, **_):
obj = self._get_download_object(obj)
p = Path(local_path)
if not overwrite_existing and p.is_file():
self.get_logger().warning('failed saving after download: overwrite=False and file exists (%s)' % str(p))
return
length = 0
with p.open(mode='wb') as f:
for chunk in obj.iter_content(chunk_size=5 * 1024 * 1024):
# filter out keep-alive new chunks
if not chunk:
continue
chunk_size = len(chunk)
f.write(chunk)
length += chunk_size
if callback:
callback(chunk_size)
return length
def get_direct_access(self, remote_path, **_):
return None
def test_upload(self, test_path, config, **kwargs):
return True
def upload_object(self, file_path, container, object_name, extra, callback=None, **kwargs):
with open(file_path, 'rb') as stream:
return self.upload_object_via_stream(iterator=stream, container=container,
object_name=object_name, extra=extra, callback=callback, **kwargs)
def exists_file(self, container_name, object_name):
# noinspection PyBroadException
try:
container = self.get_container(container_name)
url = container_name + object_name
return container.session.head(url, allow_redirects=True, headers=container.get_headers(url)).ok
except Exception:
return False
class _Stream(object):
encoding = None
mode = 'rw'
name = ''
newlines = '\n'
softspace = False
def __init__(self, input_iterator=None):
self.closed = False
self._buffer = Queue()
self._input_iterator = input_iterator
self._leftover = None
def __iter__(self):
return self
def __next__(self):
return self.next()
def close(self):
self.closed = True
def flush(self):
pass
def fileno(self):
return 87
def isatty(self):
return False
def next(self):
while not self.closed or not self._buffer.empty():
# input stream
if self._input_iterator:
try:
chunck = next(self._input_iterator)
# make sure we always return bytes
if isinstance(chunck, six.string_types):
chunck = chunck.encode("utf-8")
return chunck
except StopIteration:
self.closed = True
raise StopIteration()
except Exception as ex:
_Driver.get_logger().error('Failed downloading: %s' % ex)
else:
# in/out stream
try:
return self._buffer.get(block=True, timeout=1.)
except Empty:
pass
raise StopIteration()
def read(self, size=None):
try:
data = self.next() if self._leftover is None else self._leftover
except StopIteration:
return six.b('')
self._leftover = None
try:
while size is None or not data or len(data) < size:
chunk = self.next()
if chunk is not None:
if data is not None:
data += chunk
else:
data = chunk
except StopIteration:
pass
if size is not None and data and len(data) > size:
self._leftover = data[size:]
return data[:size]
return data
def readline(self, size=None):
return self.read(size)
def readlines(self, sizehint=None):
pass
def truncate(self, size=None):
pass
def write(self, bytes):
self._buffer.put(bytes, block=True)
def writelines(self, sequence):
for s in sequence:
self.write(s)
class _Boto3Driver(_Driver):
""" Boto3 storage adapter (simple, enough for now) """
_min_pool_connections = 512
_max_multipart_concurrency = deferred_config('aws.boto3.max_multipart_concurrency', 16)
_multipart_threshold = deferred_config('aws.boto3.multipart_threshold', (1024 ** 2) * 8) # 8 MB
_multipart_chunksize = deferred_config('aws.boto3.multipart_chunksize', (1024 ** 2) * 8)
_pool_connections = deferred_config('aws.boto3.pool_connections', 512)
_connect_timeout = deferred_config('aws.boto3.connect_timeout', 60)
_read_timeout = deferred_config('aws.boto3.read_timeout', 60)
_signature_version = deferred_config('aws.boto3.signature_version', None)
_stream_download_pool_connections = deferred_config('aws.boto3.stream_connections', 128)
_stream_download_pool = None
_stream_download_pool_pid = None
_containers = {}
scheme = 's3'
scheme_prefix = str(furl(scheme=scheme, netloc=''))
_bucket_location_failure_reported = set()
class _Container(object):
_creation_lock = ForkSafeRLock()
def __init__(self, name, cfg):
try:
import boto3
import botocore.client
from botocore.exceptions import ClientError # noqa: F401
except ImportError:
raise UsageError(
'AWS S3 storage driver (boto3) not found. '
'Please install driver using: pip install \"boto3>=1.9\"'
)
# skip 's3://'
self.name = name[5:]
endpoint = (('https://' if cfg.secure else 'http://') + cfg.host) if cfg.host else None
verify = cfg.verify
if verify is True:
# True is a non-documented value for boto3, use None instead (which means verify)
print("Using boto3 verify=None instead of true")
verify = None
elif isinstance(verify, str) and not os.path.exists(verify) and verify.split("://")[0] in driver_schemes:
verify = _Boto3Driver.download_cert(verify)
# boto3 client creation isn't thread-safe (client itself is)
with self._creation_lock:
boto_kwargs = {
"endpoint_url": endpoint,
"use_ssl": cfg.secure,
"verify": verify,
"region_name": cfg.region or None, # None in case cfg.region is an empty string
"config": botocore.client.Config(
max_pool_connections=max(
int(_Boto3Driver._min_pool_connections),
int(_Boto3Driver._pool_connections)),
connect_timeout=int(_Boto3Driver._connect_timeout),
read_timeout=int(_Boto3Driver._read_timeout),
signature_version=_Boto3Driver._signature_version,
)
}
if not cfg.use_credentials_chain:
boto_kwargs["aws_access_key_id"] = cfg.key or None
boto_kwargs["aws_secret_access_key"] = cfg.secret or None
if cfg.token:
boto_kwargs["aws_session_token"] = cfg.token
boto_session = boto3.Session(
profile_name=cfg.profile or None,
)
self.resource = boto_session.resource("s3", **boto_kwargs)
self.config = cfg
bucket_name = self.name[len(cfg.host) + 1:] if cfg.host else self.name
self.bucket = self.resource.Bucket(bucket_name)
@attrs
class ListResult(object):
name = attrib(default=None)
size = attrib(default=None)
def __init__(self):
pass
def _get_stream_download_pool(self):
if self._stream_download_pool is None or self._stream_download_pool_pid != os.getpid():
self._stream_download_pool_pid = os.getpid()
self._stream_download_pool = ThreadPoolExecutor(max_workers=int(self._stream_download_pool_connections))
return self._stream_download_pool
def get_container(self, container_name, config=None, **kwargs):
if container_name not in self._containers:
self._containers[container_name] = self._Container(name=container_name, cfg=config)
self._containers[container_name].config.retries = kwargs.get('retries', 5)
return self._containers[container_name]
def upload_object_via_stream(self, iterator, container, object_name, callback=None, extra=None, **kwargs):
import boto3.s3.transfer
stream = _Stream(iterator)
extra_args = {}
try:
extra_args = {
'ContentType': get_file_mimetype(object_name)
}
extra_args.update(container.config.extra_args or {})
container.bucket.upload_fileobj(
stream,
object_name,
Config=boto3.s3.transfer.TransferConfig(
use_threads=container.config.multipart,
max_concurrency=int(self._max_multipart_concurrency) if container.config.multipart else 1,
num_download_attempts=container.config.retries,
multipart_threshold=int(self._multipart_threshold),
multipart_chunksize=int(self._multipart_chunksize),
),
Callback=callback,
ExtraArgs=extra_args,
)
except RuntimeError:
# one might get an error similar to: "RuntimeError: cannot schedule new futures after interpreter shutdown"
# In this case, retry the upload without threads
try:
container.bucket.upload_fileobj(
stream,
object_name,
Config=boto3.s3.transfer.TransferConfig(
use_threads=False,
num_download_attempts=container.config.retries,
multipart_threshold=int(self._multipart_threshold),
multipart_chunksize=int(self._multipart_chunksize),
),
Callback=callback,
ExtraArgs=extra_args
)
except Exception as ex:
self.get_logger().error("Failed uploading: %s" % ex)
return False
except Exception as ex:
self.get_logger().error('Failed uploading: %s' % ex)
return False
return True
def upload_object(self, file_path, container, object_name, callback=None, extra=None, **kwargs):
import boto3.s3.transfer
extra_args = {}
try:
extra_args = {
'ContentType': get_file_mimetype(object_name or file_path)
}
extra_args.update(container.config.extra_args or {})
container.bucket.upload_file(
file_path,
object_name,
Config=boto3.s3.transfer.TransferConfig(
use_threads=container.config.multipart,
max_concurrency=int(self._max_multipart_concurrency) if container.config.multipart else 1,
num_download_attempts=container.config.retries,
multipart_threshold=int(self._multipart_threshold),
multipart_chunksize=int(self._multipart_chunksize),
),
Callback=callback,
ExtraArgs=extra_args,
)
except RuntimeError:
# one might get an error similar to: "RuntimeError: cannot schedule new futures after interpreter shutdown"
# In this case, retry the upload without threads
try:
container.bucket.upload_file(
file_path,
object_name,
Config=boto3.s3.transfer.TransferConfig(
use_threads=False,
num_download_attempts=container.config.retries,
multipart_threshold=int(self._multipart_threshold),
multipart_chunksize=int(self._multipart_chunksize)
),
Callback=callback,
ExtraArgs=extra_args
)
except Exception as ex:
self.get_logger().error("Failed uploading: %s" % ex)
return False
except Exception as ex:
self.get_logger().error("Failed uploading: %s" % ex)
return False
return True
def list_container_objects(self, container, ex_prefix=None, **kwargs):
if ex_prefix:
res = container.bucket.objects.filter(Prefix=ex_prefix)
else:
res = container.bucket.objects.all()
for res in res:
yield self.ListResult(name=res.key, size=res.size)
def delete_object(self, object, **kwargs):
from botocore.exceptions import ClientError
object.delete()
try:
# Try loading the file to verify deletion
object.load()
return False
except ClientError as e:
return int(e.response['Error']['Code']) == 404
def get_object(self, container_name, object_name, *args, **kwargs):
full_container_name = 's3://' + container_name
container = self._containers[full_container_name]
obj = container.resource.Object(container.bucket.name, object_name)
obj.container_name = full_container_name
return obj
def download_object_as_stream(self, obj, chunk_size=64 * 1024, verbose=None, log=None, **_):
def async_download(a_obj, a_stream, cb, cfg):
try:
a_obj.download_fileobj(a_stream, Callback=cb, Config=cfg)
if cb:
cb.close(report_completed=True)
except Exception as ex:
if cb:
cb.close()
(log or self.get_logger()).error('Failed downloading: %s' % ex)
a_stream.close()
import boto3.s3.transfer
# return iterable object
stream = _Stream()
container = self._containers[obj.container_name]
config = boto3.s3.transfer.TransferConfig(
use_threads=container.config.multipart,
max_concurrency=int(self._max_multipart_concurrency) if container.config.multipart else 1,
num_download_attempts=container.config.retries,
multipart_threshold=int(self._multipart_threshold),
multipart_chunksize=int(self._multipart_chunksize),
)
total_size_mb = obj.content_length / (1024. * 1024.)
remote_path = os.path.join(obj.container_name, obj.key)
cb = DownloadProgressReport(total_size_mb, verbose, remote_path, log)
self._get_stream_download_pool().submit(async_download, obj, stream, cb, config)
return stream
def download_object(self, obj, local_path, overwrite_existing=True, delete_on_failure=True, callback=None, **_):
import boto3.s3.transfer
p = Path(local_path)
if not overwrite_existing and p.is_file():
self.get_logger().warning('failed saving after download: overwrite=False and file exists (%s)' % str(p))
return
container = self._containers[obj.container_name]
Config = boto3.s3.transfer.TransferConfig(
use_threads=container.config.multipart,
max_concurrency=int(self._max_multipart_concurrency) if container.config.multipart else 1,
num_download_attempts=container.config.retries,
multipart_threshold=int(self._multipart_threshold),
multipart_chunksize=int(self._multipart_chunksize)
)
obj.download_file(str(p), Callback=callback, Config=Config)
@classmethod
def _test_bucket_config(cls, conf, log, test_path='', raise_on_error=True, log_on_error=True):
try:
import boto3
from botocore.exceptions import ClientError
except ImportError:
return False
if not conf.bucket:
return False
try:
if not conf.is_valid():
raise Exception('Missing credentials')
fullname = furl(conf.bucket).add(path=test_path).add(path='%s-upload_test' % cls.__module__)
bucket_name = str(fullname.path.segments[0])
filename = str(furl(path=fullname.path.segments[1:]))
if conf.subdir:
filename = "{}/{}".format(conf.subdir, filename)
data = {
'user': getpass.getuser(),
'machine': gethostname(),
'time': datetime.utcnow().isoformat()
}
boto_session = boto3.Session(
aws_access_key_id=conf.key or None,
aws_secret_access_key=conf.secret or None,
aws_session_token=conf.token or None,
profile_name=conf.profile or None
)
endpoint = (('https://' if conf.secure else 'http://') + conf.host) if conf.host else None
boto_resource = boto_session.resource('s3', region_name=conf.region or None, endpoint_url=endpoint)
bucket = boto_resource.Bucket(bucket_name)
bucket.put_object(Key=filename, Body=six.b(json.dumps(data)))
region = cls._get_bucket_region(conf=conf, log=log, report_info=True)
if region and ((conf.region and region != conf.region) or (not conf.region and region != 'us-east-1')):
msg = "incorrect region specified for bucket %s (detected region %s)" % (conf.bucket, region)
else:
return True
except ClientError as ex:
msg = ex.response['Error']['Message']
if log_on_error and log:
log.error(msg)
if raise_on_error:
raise
except Exception as ex:
msg = str(ex)
if log_on_error and log:
log.error(msg)
if raise_on_error:
raise
msg = ("Failed testing access to bucket %s: " % conf.bucket) + msg
if log_on_error and log:
log.error(msg)
if raise_on_error:
raise StorageError(msg)
return False
@classmethod
def _get_bucket_region(cls, conf, log=None, report_info=False):
import boto3
from botocore.exceptions import ClientError
if not conf.bucket:
return None
def report(msg):
if log and conf.get_bucket_host() not in cls._bucket_location_failure_reported:
if report_info:
log.debug(msg)
else:
log.warning(msg)
cls._bucket_location_failure_reported.add(conf.get_bucket_host())
try:
boto_session = boto3.Session(
conf.key, conf.secret, aws_session_token=conf.token, profile_name=conf.profile_name or None
)
boto_resource = boto_session.resource('s3')
return boto_resource.meta.client.get_bucket_location(Bucket=conf.bucket)["LocationConstraint"]
except ClientError as ex:
report("Failed getting bucket location (region) for bucket "
"%s: %s (%s, access_key=%s). Default region will be used. "
"This is normal if you do not have GET_BUCKET_LOCATION permission"
% (conf.bucket, ex.response['Error']['Message'], ex.response['Error']['Code'], conf.key))
except Exception as ex:
report("Failed getting bucket location (region) for bucket %s: %s. Default region will be used."
% (conf.bucket, str(ex)))
return None
def get_direct_access(self, remote_path, **_):
return None
def test_upload(self, test_path, config, **_):
return True
def exists_file(self, container_name, object_name):
obj = self.get_object(container_name, object_name)
# noinspection PyBroadException
try:
obj.load()
except Exception:
return False
return bool(obj)
class _GoogleCloudStorageDriver(_Driver):
"""Storage driver for google cloud storage"""
_stream_download_pool_connections = deferred_config('google.storage.stream_connections', 128)
_stream_download_pool = None
_stream_download_pool_pid = None
_containers = {}
scheme = 'gs'
scheme_prefix = str(furl(scheme=scheme, netloc=''))
class _Container(object):
def __init__(self, name, cfg):
try:
from google.cloud import storage # noqa
from google.oauth2 import service_account # noqa
except ImportError:
raise UsageError(
'Google cloud driver not found. '
'Please install driver using: pip install \"google-cloud-storage>=1.13.2\"'
)
self.name = name[len(_GoogleCloudStorageDriver.scheme_prefix):]
if cfg.credentials_json:
# noinspection PyBroadException
try:
credentials = service_account.Credentials.from_service_account_file(cfg.credentials_json)
except Exception:
credentials = None
if not credentials:
# noinspection PyBroadException
try:
# Try parsing this as json to support actual json content and not a file path
credentials = service_account.Credentials.from_service_account_info(
json.loads(cfg.credentials_json)
)
except Exception:
pass
else:
credentials = None
self.client = storage.Client(project=cfg.project, credentials=credentials)
for adapter in self.client._http.adapters.values():
if cfg.pool_connections:
adapter._pool_connections = cfg.pool_connections
if cfg.pool_maxsize:
adapter._pool_maxsize = cfg.pool_maxsize
self.config = cfg
self.bucket = self.client.bucket(self.name)
def _get_stream_download_pool(self):
if self._stream_download_pool is None or self._stream_download_pool_pid != os.getpid():
self._stream_download_pool_pid = os.getpid()
self._stream_download_pool = ThreadPoolExecutor(max_workers=int(self._stream_download_pool_connections))
return self._stream_download_pool
def get_container(self, container_name, config=None, **kwargs):
if container_name not in self._containers:
self._containers[container_name] = self._Container(name=container_name, cfg=config)
self._containers[container_name].config.retries = kwargs.get('retries', 5)
return self._containers[container_name]
def upload_object_via_stream(self, iterator, container, object_name, extra=None, **kwargs):
try:
blob = container.bucket.blob(object_name)
blob.upload_from_file(iterator)
except Exception as ex:
self.get_logger().error('Failed uploading: %s' % ex)
return False
return True
def upload_object(self, file_path, container, object_name, extra=None, **kwargs):
try:
blob = container.bucket.blob(object_name)
blob.upload_from_filename(file_path)
except Exception as ex:
self.get_logger().error('Failed uploading: %s' % ex)
return False
return True
def list_container_objects(self, container, ex_prefix=None, **kwargs):
# noinspection PyBroadException
try:
return list(container.bucket.list_blobs(prefix=ex_prefix))
except TypeError:
# google-cloud-storage < 1.17
return [blob for blob in container.bucket.list_blobs() if blob.name.startswith(ex_prefix)]
def delete_object(self, object, **kwargs):
try:
object.delete()
except Exception as ex:
try:
from google.cloud.exceptions import NotFound # noqa
if isinstance(ex, NotFound):
return False
except ImportError:
pass
name = getattr(object, "name", "")
self.get_logger().warning("Failed deleting object {}: {}".format(name, ex))
return False
return not object.exists()
def get_object(self, container_name, object_name, *args, **kwargs):
full_container_name = str(furl(scheme=self.scheme, netloc=container_name))
container = self._containers[full_container_name]
obj = container.bucket.blob(object_name)
obj.container_name = full_container_name
return obj
def download_object_as_stream(self, obj, chunk_size=256 * 1024, **_):
raise NotImplementedError('Unsupported for google storage')
def async_download(a_obj, a_stream):
try:
a_obj.download_to_file(a_stream)
except Exception as ex:
self.get_logger().error('Failed downloading: %s' % ex)
a_stream.close()
# return iterable object
stream = _Stream()
obj.chunk_size = chunk_size
self._get_stream_download_pool().submit(async_download, obj, stream)
return stream
def download_object(self, obj, local_path, overwrite_existing=True, delete_on_failure=True, callback=None, **_):
p = Path(local_path)
if not overwrite_existing and p.is_file():
self.get_logger().warning('failed saving after download: overwrite=False and file exists (%s)' % str(p))
return
obj.download_to_filename(str(p))
def test_upload(self, test_path, config, **_):
bucket_url = str(furl(scheme=self.scheme, netloc=config.bucket))
bucket = self.get_container(container_name=bucket_url, config=config).bucket
test_obj = bucket
if test_path:
if not test_path.endswith('/'):
test_path += '/'
blob = bucket.blob(test_path)
if blob.exists():
test_obj = blob
permissions_to_test = ('storage.objects.get', 'storage.objects.update')
return set(test_obj.test_iam_permissions(permissions_to_test)) == set(permissions_to_test)
def get_direct_access(self, remote_path, **_):
return None
def exists_file(self, container_name, object_name):
return self.get_object(container_name, object_name).exists()
class _AzureBlobServiceStorageDriver(_Driver):
scheme = "azure"
_containers = {}
_max_connections = deferred_config("azure.storage.max_connections", 0)
class _Container(object):
def __init__(self, name, config, account_url):
self.MAX_SINGLE_PUT_SIZE = 4 * 1024 * 1024
self.SOCKET_TIMEOUT = (300, 2000)
self.name = name
self.config = config
self.account_url = account_url
try:
from azure.storage.blob import BlobServiceClient # noqa
self.__legacy = False
except ImportError:
try:
from azure.storage.blob import BlockBlobService # noqa
from azure.common import AzureHttpError # noqa
self.__legacy = True
except ImportError:
raise UsageError(
"Azure blob storage driver not found. "
"Please install driver using: 'pip install clearml[azure]' or "
"pip install '\"azure.storage.blob>=12.0.0\"'"
)