Debian Codegraph @

azure/datalake/store/multithread.py

raw
1 # -*- coding: utf-8 -*-
2 # coding=utf-8
3 # --------------------------------------------------------------------------
4 # Copyright (c) Microsoft Corporation. All rights reserved.
5 # Licensed under the MIT License. See License.txt in the project root for
6 # license information.
7 # --------------------------------------------------------------------------
8
9 """
10 High performance multi-threaded module to up/download
11
12 Calls method in `core` with thread pool executor to ensure the network
13 is used to its maximum throughput.
14
15 Only implements upload and download of (massive) files and directory trees.
16 """
17 from contextlib import closing
18 import glob
19 import logging
20 import os
21 import pickle
22 import time
23 import errno
24 import uuid
25
26 from io import open
27 from .core import AzureDLPath, _fetch_range
28 from .exceptions import FileExistsError, FileNotFoundError
29 from .transfer import ADLTransferClient
30 from .utils import datadir, read_block, tokenize
31 from .retry import ExponentialRetryPolicy
32
33 logger = logging.getLogger(__name__)
34
35
36 def save(instance, filename, keep=True):
37 if os.path.exists(filename):
38 all_downloads = load(filename)
39 else:
40 all_downloads = {}
41 if not instance.client._fstates.contains_all('finished') and keep:
42 all_downloads[instance._name] = instance
43 else:
44 all_downloads.pop(instance._name, None)
45 try:
46 # persist failure should not halt things
47 with open(filename, 'wb') as f:
48 pickle.dump(all_downloads, f)
49 except IOError:
50 logger.debug("Persist failed: %s" % filename)
51
52
53 def load(filename):
54 try:
55 return pickle.load(open(filename, 'rb'))
56 except:
57 return {}
58
59
60 class ADLDownloader(object):
61 """ Download remote file(s) using chunks and threads
62
63 Launches multiple threads for efficient downloading, with `chunksize`
64 assigned to each. The remote path can be a single file, a directory
65 of files or a glob pattern.
66
67 Parameters
68 ----------
69 adlfs: ADL filesystem instance
70 rpath: str
71 remote path/globstring to use to find remote files. Recursive glob
72 patterns using `**` are not supported.
73 lpath: str
74 local path. If downloading a single file, will write to this specific
75 file, unless it is an existing directory, in which case a file is
76 created within it. If downloading multiple files, this is the root
77 directory to write within. Will create directories as required.
78 nthreads: int [None]
79 Number of threads to use. If None, uses the number of cores.
80 chunksize: int [2**28]
81 Number of bytes for a chunk. Large files are split into chunks. Files
82 smaller than this number will always be transferred in a single thread.
83 buffersize: int [2**22]
84 Ignored in curret implementation.
85 Number of bytes for internal buffer. This block cannot be bigger than
86 a chunk and cannot be smaller than a block.
87 blocksize: int [2**22]
88 Number of bytes for a block. Within each chunk, we write a smaller
89 block for each API call. This block cannot be bigger than a chunk.
90 client: ADLTransferClient [None]
91 Set an instance of ADLTransferClient when finer-grained control over
92 transfer parameters is needed. Ignores `nthreads` and `chunksize` set
93 by constructor.
94 run: bool [True]
95 Whether to begin executing immediately.
96 overwrite: bool [False]
97 Whether to forcibly overwrite existing files/directories. If False and
98 local path is a directory, will quit regardless if any files would be
99 overwritten or not. If True, only matching filenames are actually
100 overwritten.
101 progress_callback: callable [None]
102 Callback for progress with signature function(current, total) where
103 current is the number of bytes transfered so far, and total is the
104 size of the blob, or None if the total size is unknown.
105 timeout: int (0)
106 Default value 0 means infinite timeout. Otherwise time in seconds before the
107 process will stop and raise an exception if transfer is still in progress
108
109 See Also
110 --------
111 azure.datalake.store.transfer.ADLTransferClient
112 """
113 def __init__(self, adlfs, rpath, lpath, nthreads=None, chunksize=2**28,
114 buffersize=2**22, blocksize=2**22, client=None, run=True,
115 overwrite=False, verbose=False, progress_callback=None, timeout=0):
116
117 # validate that the src exists and the current user has access to it
118 # this only validates access to the top level folder. If there are files
119 # or folders underneath it that the user does not have access to the download
120 # will fail on those files. We clean the path in case there are wildcards.
121 # In this case, we will always invalidate the cache for this check to
122 # do our best to ensure that the path exists as close to run time of the transfer as possible.
123 # Due to the nature of a distributed filesystem, the path could be deleted later during execution,
124 # at which point the transfer's behavior may be non-deterministic, but it will indicate an error.
125 if not adlfs.exists(AzureDLPath(rpath).globless_prefix, invalidate_cache=True):
126 raise FileNotFoundError('Data Lake item at path: {} either does not exist or the current user does not have permission to access it.'.format(rpath))
127 if client:
128 self.client = client
129 else:
130 self.client = ADLTransferClient(
131 adlfs,
132 transfer=get_chunk,
133 nthreads=nthreads,
134 chunksize=chunksize,
135 buffersize=buffersize,
136 blocksize=blocksize,
137 chunked=False,
138 verbose=verbose,
139 parent=self,
140 progress_callback=progress_callback,
141 timeout=timeout)
142 self._name = tokenize(adlfs, rpath, lpath, chunksize, blocksize)
143 self.rpath = rpath
144 self.lpath = lpath
145 self._overwrite = overwrite
146 existing_files = self._setup()
147 if existing_files:
148 raise FileExistsError('Overwrite was not specified and the following files exist, blocking the transfer operation. Please specify overwrite to overwrite these files during transfer: {}'.format(','.join(existing_files)))
149
150 if run:
151 self.run()
152
153 def save(self, keep=True):
154 """ Persist this download
155
156 Saves a copy of this transfer process in its current state to disk.
157 This is done automatically for a running transfer, so that as a chunk
158 is completed, this is reflected. Thus, if a transfer is interrupted,
159 e.g., by user action, the transfer can be restarted at another time.
160 All chunks that were not already completed will be restarted at that
161 time.
162
163 See methods ``load`` to retrieved saved transfers and ``run`` to
164 resume a stopped transfer.
165
166 Parameters
167 ----------
168 keep: bool (True)
169 If True, transfer will be saved if some chunks remain to be
170 completed; the transfer will be sure to be removed otherwise.
171 """
172 save(self, os.path.join(datadir, 'downloads'), keep)
173
174 @staticmethod
175 def load():
176 """ Load list of persisted transfers from disk, for possible resumption.
177
178 Returns
179 -------
180 A dictionary of download instances. The hashes are auto-
181 generated unique. The state of the chunks completed, errored, etc.,
182 can be seen in the status attribute. Instances can be resumed with
183 ``run()``.
184 """
185 return load(os.path.join(datadir, 'downloads'))
186
187 @staticmethod
188 def clear_saved():
189 """ Remove references to all persisted downloads.
190 """
191 if os.path.exists(os.path.join(datadir, 'downloads')):
192 os.remove(os.path.join(datadir, 'downloads'))
193
194 @property
195 def hash(self):
196 return self._name
197
198
199
200 def _setup(self):
201 """ Create set of parameters to loop over
202 """
203
204 def is_glob_path(path):
205 path = AzureDLPath(path).trim()
206 prefix = path.globless_prefix
207 return not path == prefix
208 is_rpath_glob = is_glob_path(self.rpath)
209
210 if is_rpath_glob:
211 rfiles = self.client._adlfs.glob(self.rpath, details=True, invalidate_cache=True)
212 else:
213 rfiles = self.client._adlfs.walk(self.rpath, details=True, invalidate_cache=True)
214
215 if not rfiles:
216 raise ValueError('No files to download')
217
218 # If only one file is returned we are not sure whether user specified a dir or a file to download,
219 # since walk gives the same result for both i.e walk("DirWithsingleFile") == walk("DirWithSingleFile\SingleFile)
220 # If user specified a file in rpath,
221 # then we want to download the file into lpath directly and not create another subdir for that.
222 # If user specified a dir that happens to contain only one file, we want to create the dir as well under lpath.
223 if len(rfiles) == 1 and not is_rpath_glob and self.client._adlfs.info(self.rpath)['type'] == 'FILE':
224 if os.path.exists(self.lpath) and os.path.isdir(self.lpath):
225 file_pairs = [(os.path.join(self.lpath, os.path.basename(rfiles[0]['name'] + '.inprogress')),
226 rfiles[0])]
227 else:
228 file_pairs = [(self.lpath, rfiles[0])]
229 else:
230 local_rel_rpath = str(AzureDLPath(self.rpath).trim().globless_prefix)
231 file_pairs = [(os.path.join(self.lpath, os.path.relpath(f['name'] +'.inprogress', local_rel_rpath)), f)
232 for f in rfiles]
233
234
235 # this property is used for internal validation
236 # and should not be referenced directly by public callers
237 self._file_pairs = file_pairs
238
239 existing_files = []
240 for lfile, rfile in file_pairs:
241 # only interested in the final destination file name for existence,
242 # not the initial inprogress target
243 destination_file = lfile.replace('.inprogress', '')
244 if not self._overwrite and os.path.exists(destination_file):
245 existing_files.append(destination_file)
246 else:
247 self.client.submit(rfile['name'], lfile, rfile['length'])
248
249 return existing_files
250
251 def run(self, nthreads=None, monitor=True):
252 """ Populate transfer queue and execute downloads
253
254 Parameters
255 ----------
256 nthreads: int [None]
257 Override default nthreads, if given
258 monitor: bool [True]
259 To watch and wait (block) until completion.
260 """
261 def touch(self, src, dst):
262 root = os.path.dirname(dst)
263 if not os.path.exists(root) and root:
264 # don't attempt to create current directory
265 logger.debug('Creating directory %s', root)
266 try:
267 os.makedirs(root)
268 except OSError as e:
269 if e.errno != errno.EEXIST:
270 raise
271 logger.debug('Creating empty file %s', dst)
272 with open(dst, 'wb'):
273 pass
274
275 for empty_directory in self.client._adlfs._empty_dirs_to_add():
276 local_rel_rpath = str(AzureDLPath(self.rpath).trim().globless_prefix)
277 path = os.path.join(self.lpath, os.path.relpath(empty_directory['name'], local_rel_rpath))
278 try:
279 os.makedirs(path)
280 except OSError as e:
281 if e.errno != errno.EEXIST:
282 raise
283 self.client.run(nthreads, monitor, before_start=touch)
284
285 def active(self):
286 """ Return whether the downloader is active """
287 return self.client.active
288
289 def successful(self):
290 """
291 Return whether the downloader completed successfully.
292
293 It will raise AssertionError if the downloader is active.
294 """
295 return self.client.successful
296
297 def __str__(self):
298 return "<ADL Download: %s -> %s (%s)>" % (self.rpath, self.lpath,
299 self.client.status)
300
301 __repr__ = __str__
302
303 def get_chunk(adlfs, src, dst, offset, size, buffersize, blocksize,
304 shutdown_event=None, retries=10, delay=0.01, backoff=3):
305 """ Download a piece of a remote file and write locally
306
307 Internal function used by `download`.
308 """
309 err = None
310 total_bytes_downloaded = 0
311 retry_policy = ExponentialRetryPolicy(max_retries=retries, exponential_retry_interval=delay,
312 exponential_factor=backoff)
313 filesessionid = str(uuid.uuid4())
314 try:
315 nbytes = 0
316 start = offset
317
318 with open(dst, 'rb+') as fout:
319 fout.seek(start)
320 while start < offset+size:
321 with closing(_fetch_range(adlfs.azure, src, start=start,
322 end=min(start+blocksize, offset+size), stream=True,
323 retry_policy=retry_policy, filesessionid=filesessionid)) as response:
324 chunk = response.content
325 if shutdown_event and shutdown_event.is_set():
326 return total_bytes_downloaded, None
327 if chunk:
328 nwritten = fout.write(chunk)
329 if nwritten:
330 nbytes += nwritten
331 start += nwritten
332 else:
333 raise IOError("Failed to write to disk for {0} at location {1} with blocksize {2}".format(dst, start, blocksize))
334 logger.debug('Downloaded %s bytes to %s, byte offset %s', nbytes, dst, offset)
335
336 # There are certain cases where we will be throttled and recieve less than the expected amount of data.
337 # In these cases, instead of failing right away, instead indicate a retry is occuring and update offset and
338 # size to attempt another read to get the rest of the data. We will only do this if the amount of bytes read
339 # is less than size, because if somehow we recieved too much data we are not clear on how to proceed.
340 if nbytes < size:
341 errMsg = 'Did not recieve total bytes requested from server. This can be due to server side throttling and will be retried. Data Expected: {}. Data Received: {}.'.format(size, nbytes)
342 size -= nbytes
343 offset += nbytes
344 total_bytes_downloaded += nbytes
345 raise IOError(errMsg)
346 elif nbytes > size:
347 raise IOError('Received more bytes than expected from the server. Expected: {}. Received: {}.'.format(size, nbytes))
348 else:
349 total_bytes_downloaded += nbytes
350
351 return total_bytes_downloaded, None
352 except Exception as e:
353 err = e
354 logger.debug('Exception %s on ADL download on attempt', repr(err))
355 exception = RuntimeError('Max number of ADL retries exceeded: exception ' + repr(err))
356 logger.error('Download failed %s; %s', dst, repr(exception))
357 return total_bytes_downloaded, exception
358
359
360 class ADLUploader(object):
361 """ Upload local file(s) using chunks and threads
362
363 Launches multiple threads for efficient uploading, with `chunksize`
364 assigned to each. The path can be a single file, a directory
365 of files or a glob pattern.
366
367 Parameters
368 ----------
369 adlfs: ADL filesystem instance
370 rpath: str
371 remote path to upload to; if multiple files, this is the dircetory
372 root to write within
373 lpath: str
374 local path. Can be single file, directory (in which case, upload
375 recursively) or glob pattern. Recursive glob patterns using `**` are
376 not supported.
377 nthreads: int [None]
378 Number of threads to use. If None, uses the number of cores.
379 chunksize: int [None]
380 Number of bytes for a chunk. Large files are split into chunks. Files
381 smaller than this number will always be transferred in a single thread.
382 buffersize: int [2**22]
383 Number of bytes for internal buffer. This block cannot be bigger than
384 a chunk and cannot be smaller than a block.
385 blocksize: int [2**22]
386 Number of bytes for a block. Within each chunk, we write a smaller
387 block for each API call. This block cannot be bigger than a chunk.
388 client: ADLTransferClient [None]
389 Set an instance of ADLTransferClient when finer-grained control over
390 transfer parameters is needed. Ignores `nthreads` and `chunksize`
391 set by constructor.
392 run: bool [True]
393 Whether to begin executing immediately.
394 overwrite: bool [False]
395 Whether to forcibly overwrite existing files/directories. If False and
396 remote path is a directory, will quit regardless if any files would be
397 overwritten or not. If True, only matching filenames are actually
398 overwritten.
399 progress_callback: callable [None]
400 Callback for progress with signature function(current, total) where
401 current is the number of bytes transfered so far, and total is the
402 size of the blob, or None if the total size is unknown.
403 timeout: int (0)
404 Default value 0 means infinite timeout. Otherwise time in seconds before the
405 process will stop and raise an exception if transfer is still in progress
406
407 See Also
408 --------
409 azure.datalake.store.transfer.ADLTransferClient
410 """
411 def __init__(self, adlfs, rpath, lpath, nthreads=None, chunksize=None,
412 buffersize=2**22, blocksize=2**22, client=None, run=True,
413 overwrite=False, verbose=False, progress_callback=None, timeout=0):
414
415 if client:
416 self.client = client
417 else:
418 self.client = ADLTransferClient(
419 adlfs,
420 transfer=put_chunk,
421 nthreads=nthreads,
422 chunksize=None,
423 buffersize=buffersize,
424 blocksize=blocksize,
425 chunked=False,
426 delimiter=None, # TODO: see utils.cs for what is required to support delimiters.
427 parent=self,
428 verbose=verbose,
429 unique_temporary=True,
430 progress_callback=progress_callback,
431 timeout=timeout)
432 self._name = tokenize(adlfs, rpath, lpath, chunksize, blocksize)
433 self.rpath = AzureDLPath(rpath)
434 self.lpath = lpath
435 self._overwrite = overwrite
436 existing_files = self._setup()
437
438 if existing_files:
439 raise FileExistsError('Overwrite was not specified and the following files exist, blocking the transfer operation. Please specify overwrite to overwrite these files during transfer: {}'.format(','.join(existing_files)))
440
441 if run:
442 self.run()
443
444 def save(self, keep=True):
445 """ Persist this upload
446
447 Saves a copy of this transfer process in its current state to disk.
448 This is done automatically for a running transfer, so that as a chunk
449 is completed, this is reflected. Thus, if a transfer is interrupted,
450 e.g., by user action, the transfer can be restarted at another time.
451 All chunks that were not already completed will be restarted at that
452 time.
453
454 See methods ``load`` to retrieved saved transfers and ``run`` to
455 resume a stopped transfer.
456
457 Parameters
458 ----------
459 keep: bool (True)
460 If True, transfer will be saved if some chunks remain to be
461 completed; the transfer will be sure to be removed otherwise.
462 """
463 save(self, os.path.join(datadir, 'uploads'), keep)
464
465 @staticmethod
466 def load():
467 """ Load list of persisted transfers from disk, for possible resumption.
468
469 Returns
470 -------
471 A dictionary of upload instances. The hashes are auto
472 generated unique. The state of the chunks completed, errored, etc.,
473 can be seen in the status attribute. Instances can be resumed with
474 ``run()``.
475 """
476 return load(os.path.join(datadir, 'uploads'))
477
478 @staticmethod
479 def clear_saved():
480 """ Remove references to all persisted uploads.
481 """
482 if os.path.exists(os.path.join(datadir, 'uploads')):
483 os.remove(os.path.join(datadir, 'uploads'))
484
485 @property
486 def hash(self):
487 return self._name
488
489 def _setup(self):
490 """ Create set of parameters to loop over
491 """
492 is_path_walk_empty = False
493 if "*" not in self.lpath:
494 lfiles = []
495 for directory, subdir, fnames in os.walk(self.lpath):
496 lfiles.extend([os.path.join(directory, f) for f in fnames])
497 if not subdir and not fnames: # Empty Directory
498 self.client._adlfs._emptyDirs.append(directory)
499
500 if (not lfiles and os.path.exists(self.lpath) and
501 not os.path.isdir(self.lpath)):
502 lfiles = [self.lpath]
503 is_path_walk_empty = True
504 else:
505 lfiles = glob.glob(self.lpath)
506
507 if len(lfiles) > 0 and not is_path_walk_empty:
508 local_rel_lpath = str(AzureDLPath(self.lpath).globless_prefix)
509 file_pairs = [(f, self.rpath / AzureDLPath(f).relative_to(local_rel_lpath)) for f in lfiles]
510 elif lfiles:
511 if self.client._adlfs.exists(self.rpath, invalidate_cache=True) and \
512 self.client._adlfs.info(self.rpath, invalidate_cache=False)['type'] == "DIRECTORY":
513 file_pairs = [(lfiles[0], self.rpath / AzureDLPath(lfiles[0]).name)]
514 else:
515 file_pairs = [(lfiles[0], self.rpath)]
516 else:
517 raise ValueError('No files to upload')
518
519 # this property is used for internal validation
520 # and should not be referenced directly by public callers
521 self._file_pairs = file_pairs
522
523 existing_files = []
524 for lfile, rfile in file_pairs:
525 if not self._overwrite and self.client._adlfs.exists(rfile, invalidate_cache=False):
526 existing_files.append(rfile.as_posix())
527 else:
528 fsize = os.stat(lfile).st_size
529 self.client.submit(lfile, rfile, fsize)
530
531 return existing_files
532
533 def run(self, nthreads=None, monitor=True):
534 """ Populate transfer queue and execute downloads
535
536 Parameters
537 ----------
538 nthreads: int [None]
539 Override default nthreads, if given
540 monitor: bool [True]
541 To watch and wait (block) until completion.
542 """
543 for empty_directory in self.client._adlfs._empty_dirs_to_add():
544 local_rel_path = os.path.relpath(empty_directory, self.lpath)
545 rel_rpath = str(AzureDLPath(self.rpath).trim().globless_prefix / local_rel_path)
546 self.client._adlfs.mkdir(rel_rpath)
547
548 self.client.run(nthreads, monitor)
549
550 def active(self):
551 """ Return whether the uploader is active """
552 return self.client.active
553
554 def successful(self):
555 """
556 Return whether the uploader completed successfully.
557
558 It will raise AssertionError if the uploader is active.
559 """
560 return self.client.successful
561
562 def __str__(self):
563 return "<ADL Upload: %s -> %s (%s)>" % (self.lpath, self.rpath,
564 self.client.status)
565
566 __repr__ = __str__
567
568
569 def put_chunk(adlfs, src, dst, offset, size, buffersize, blocksize, delimiter=None,
570 shutdown_event=None):
571 """ Upload a piece of a local file
572
573 Internal function used by `upload`.
574 """
575 nbytes = 0
576 try:
577 with adlfs.open(dst, 'wb', blocksize=buffersize, delimiter=delimiter) as fout:
578 end = offset + size
579 miniblock = min(size, blocksize)
580 # For empty files there is no need to take the IO hit.
581 if size != 0:
582 with open(src, 'rb') as fin:
583 for o in range(offset, end, miniblock):
584 if shutdown_event and shutdown_event.is_set():
585 return nbytes, None
586 data = read_block(fin, o, miniblock, delimiter)
587 nbytes += fout.write(data)
588
589 except Exception as e:
590 exception = repr(e)
591 logger.error('Upload failed %s; %s', src, exception)
592 return nbytes, exception
593 logger.debug('Uploaded from %s, byte offset %s', src, offset)
594 return nbytes, None