Debian Codegraph @

azure/datalake/store/core.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 The main file-system class and functionality.
11
12 Provides an pythonic interface to the Azure Data-lake Store, including
13 file-system commands with typical names and options, and a File object
14 which is compatible with the built-in File.
15 """
16
17 # standard imports
18 import io
19 import logging
20 import sys
21 import uuid
22 import json
23
24 # local imports
25 from .exceptions import DatalakeBadOffsetException, DatalakeIncompleteTransferException
26 from .exceptions import FileNotFoundError, PermissionError
27 from .lib import DatalakeRESTInterface
28 from .utils import ensure_writable, read_block
29 from .enums import ExpiryOptionType
30 from .retry import ExponentialRetryPolicy, NoRetryPolicy
31 from .multiprocessor import multi_processor_change_acl
32 import pathlib
33
34
35 logger = logging.getLogger(__name__)
36 valid_expire_types = [x.value for x in ExpiryOptionType]
37
38
39 class AzureDLFileSystem(object):
40 """
41 Access Azure DataLake Store as if it were a file-system
42
43 Parameters
44 ----------
45 store_name: str ("")
46 Store name to connect to. If not supplied, we use environment variable azure_data_lake_store_name
47 token_credential: credentials object
48 When setting up a new connection, this contains the authorization
49 credentials. Use Azure Identity to get this or define an implementation of azure.core.credentials.TokenCredential
50 scopes: str(None)
51 which is a list of scopes to use for the token.
52 url_suffix: str (None)
53 Domain to send REST requests to. The end-point URL is constructed
54 using this and the store_name. If None, use default.
55 api_version: str (2018-09-01)
56 The API version to target with requests. Changing this value will change the behavior of the requests, and can cause unexpected behavior or breaking changes. Changes to this value should be undergone with caution.
57 per_call_timeout_seconds: float(60)
58 This is the timeout for each requests library call.
59 kwargs: optional key/values
60 Other arguments forwarded to the DatalakeRESTInterface constructor.
61 """
62 _singleton = [None]
63
64 def __init__(self, token_credential=None, **kwargs):
65 self.token_credential = token_credential
66 self.kwargs = kwargs
67 self.connect()
68 self.dirs = {}
69 self._emptyDirs = []
70 AzureDLFileSystem._singleton[0] = self
71
72 @classmethod
73 def current(cls):
74 """ Return the most recently created AzureDLFileSystem
75 """
76 if not cls._singleton[0]:
77 return cls()
78 else:
79 return cls._singleton[0]
80
81 def connect(self):
82 """
83 Establish connection object.
84 """
85 self.azure = DatalakeRESTInterface(token_credential=self.token_credential, **self.kwargs)
86 self.token_credential = self.azure.token_credential
87
88 def __setstate__(self, state):
89 self.__dict__.update(state)
90 self.connect()
91
92 def open(self, path, mode='rb', blocksize=2 ** 25, delimiter=None):
93 """ Open a file for reading or writing
94
95 Parameters
96 ----------
97 path: string
98 Path of file on ADL
99 mode: string
100 One of 'rb', 'ab' or 'wb'
101 blocksize: int
102 Size of data-node blocks if reading
103 delimiter: byte(s) or None
104 For writing delimiter-ended blocks
105 """
106 if 'b' not in mode:
107 raise NotImplementedError("Text mode not supported, use mode='%s'"
108 " and manage bytes" % (mode[0] + 'b'))
109 return AzureDLFile(self, AzureDLPath(path), mode, blocksize=blocksize,
110 delimiter=delimiter)
111
112 def _ls_batched(self, path, batch_size=4000):
113 """Batched ListStatus calls. Internal Method"""
114 if batch_size <= 1:
115 raise ValueError("Batch size must be strictly greater than 1")
116 parms = {'listSize': batch_size}
117 ret = []
118 continuation_token = "NonEmptyStringSentinel"
119
120 while continuation_token != "":
121 ls_call_result = self.azure.call('LISTSTATUS', path, **parms)
122
123 data = ls_call_result['FileStatuses']['FileStatus']
124 ret.extend(data)
125
126 continuation_token = ls_call_result['FileStatuses']['continuationToken']
127 parms['listAfter'] = continuation_token # continuationToken to be used as ListAfter
128
129 return ret
130
131 def _ls(self, path, invalidate_cache=True, batch_size=4000):
132 """ List files at given path """
133 path = AzureDLPath(path).trim()
134 key = path.as_posix()
135
136 if invalidate_cache:
137 self.invalidate_cache(key)
138
139 if key not in self.dirs:
140 self.dirs[key] = self._ls_batched(key, batch_size=batch_size)
141 for f in self.dirs[key]:
142 f['name'] = (path / f['pathSuffix']).as_posix()
143 return self.dirs[key]
144
145 def ls(self, path="", detail=False, invalidate_cache=True):
146 """
147 List all elements under directory specified with path
148
149 Parameters
150 ----------
151 path: str or AzureDLPath
152 Path to query
153 detail: bool
154 Detailed info or not.
155 invalidate_cache: bool
156 Whether to invalidate cache or not
157
158 Returns
159 -------
160 List of elements under directory specified with path
161 """
162 path = AzureDLPath(path)
163 files = self._ls(path, invalidate_cache)
164 if not files:
165 # in this case we just invalidated the cache (if it was true), so no need to do it again
166 inf = self.info(path, invalidate_cache=False)
167 if inf['type'] == 'DIRECTORY':
168 # always return an empty array in this case, because there are no entries underneath the folder
169 return []
170
171 raise FileNotFoundError(path)
172 if detail:
173 return files
174 else:
175 return [f['name'] for f in files]
176
177 def info(self, path, invalidate_cache=True, expected_error_code=None):
178 """
179 File information for path
180
181 Parameters
182 ----------
183 path: str or AzureDLPath
184 Path to query
185 invalidate_cache: bool
186 Whether to invalidate cache or not
187 expected_error_code: int
188 Optionally indicates a specific, expected error code, if any.
189
190 Returns
191 -------
192 File information
193 """
194 path = AzureDLPath(path).trim()
195 path_as_posix = path.as_posix()
196 root = path.parent
197 root_as_posix = root.as_posix()
198
199 # in the case of getting info about the root itself or if the cache won't be hit
200 # simply return the result of a GETFILESTATUS from the service
201 if invalidate_cache or path_as_posix in {'/', '.'}:
202 to_return = self.azure.call('GETFILESTATUS', path_as_posix, expected_error_code=expected_error_code)[
203 'FileStatus']
204 to_return['name'] = path_as_posix
205
206 # add the key/value pair back to the cache so long as it isn't the root
207 if path_as_posix not in {'/', '.'}:
208 if root_as_posix not in self.dirs:
209 self.dirs[root_as_posix] = [to_return]
210 else:
211 found = False
212 for f in self.dirs[root_as_posix]:
213 if f['name'] == path_as_posix:
214 found = True
215 break
216 if not found:
217 self.dirs[root_as_posix].append(to_return)
218 return to_return
219
220 for f in self._ls(root, invalidate_cache):
221 if f['name'] == path_as_posix:
222 return f
223
224 raise FileNotFoundError(path)
225
226 def _walk(self, path, invalidate_cache=True, include_dirs=False):
227 """
228 Walk a path recursively and returns list of files and dirs(if parameter set)
229
230 Parameters
231 ----------
232 path: str or AzureDLPath
233 Path to query
234 invalidate_cache: bool
235 Whether to invalidate cache
236 include_dirs: bool
237 Whether to include dirs in return value
238
239 Returns
240 -------
241 List of files and (optionally) dirs
242 """
243 ret = list(self._ls(path, invalidate_cache))
244 self._emptyDirs = []
245 current_subdirs = [f for f in ret if f['type'] != 'FILE']
246 while current_subdirs:
247 dirs_below_current_level = []
248 for apath in current_subdirs:
249 try:
250 sub_elements = self._ls(apath['name'], invalidate_cache)
251 except FileNotFoundError:
252 # Folder may have been deleted while walk is going on. Infrequent so we can take the linear hit
253 ret.remove(apath)
254 continue
255 if not sub_elements:
256 self._emptyDirs.append(apath)
257 else:
258 ret.extend(sub_elements)
259 dirs_below_current_level.extend([f for f in sub_elements if f['type'] != 'FILE'])
260 current_subdirs = dirs_below_current_level
261
262 if include_dirs:
263 return ret
264 else:
265 return [f for f in ret if f['type'] == 'FILE']
266
267 def _empty_dirs_to_add(self):
268 """ Returns directories found empty during walk. Only for internal use"""
269 return self._emptyDirs
270
271 def walk(self, path='', details=False, invalidate_cache=True):
272 """
273 Get all files below given path
274
275 Parameters
276 ----------
277 path: str or AzureDLPath
278 Path to query
279 details: bool
280 Whether to include file details
281 invalidate_cache: bool
282 Whether to invalidate cache
283
284 Returns
285 -------
286 List of files
287 """
288 return [f if details else f['name'] for f in self._walk(path, invalidate_cache)]
289
290 def glob(self, path, details=False, invalidate_cache=True):
291 """
292 Find files (not directories) by glob-matching.
293
294 Parameters
295 ----------
296 path: str or AzureDLPath
297 Path to query
298 details: bool
299 Whether to include file details
300 invalidate_cache: bool
301 Whether to invalidate cache
302
303 Returns
304 -------
305 List of files
306 """
307
308 path = AzureDLPath(path).trim()
309 path_as_posix = path.as_posix()
310 prefix = path.globless_prefix
311 allfiles = self.walk(prefix, details, invalidate_cache)
312 if prefix == path:
313 return allfiles
314 return [f for f in allfiles if AzureDLPath(f['name'] if details else f).match(path_as_posix)]
315
316 def du(self, path, total=False, deep=False, invalidate_cache=True):
317 """
318 Bytes in keys at path
319
320 Parameters
321 ----------
322 path: str or AzureDLPath
323 Path to query
324 total: bool
325 Return the sum on list
326 deep: bool
327 Recursively enumerate or just use files under current dir
328 invalidate_cache: bool
329 Whether to invalidate cache
330
331 Returns
332 -------
333 List of dict of name:size pairs or total size.
334 """
335
336 if deep:
337 files = self._walk(path, invalidate_cache)
338 else:
339 files = self.ls(path, detail=True, invalidate_cache=invalidate_cache)
340 if total:
341 return sum(f.get('length', 0) for f in files)
342 else:
343 return {p['name']: p['length'] for p in files}
344
345 def df(self, path):
346 """ Resource summary of path
347
348 Parameters
349 ----------
350 path: str
351 Path to query
352 """
353 path = AzureDLPath(path).trim()
354 current_path_info = self.info(path, invalidate_cache=False)
355 if current_path_info['type'] == 'FILE':
356 return {'directoryCount': 0, 'fileCount': 1, 'length': current_path_info['length'], 'quota': -1,
357 'spaceConsumed': current_path_info['length'], 'spaceQuota': -1}
358 else:
359 all_files_and_dirs = self._walk(path, include_dirs=True)
360 dir_count = 1 # 1 as walk doesn't return current directory
361 length = file_count = 0
362 for item in all_files_and_dirs:
363 length += item['length']
364 if item['type'] == 'FILE':
365 file_count += 1
366 else:
367 dir_count += 1
368
369 return {'directoryCount': dir_count, 'fileCount': file_count, 'length': length, 'quota': -1,
370 'spaceConsumed': length, 'spaceQuota': -1}
371
372 def chmod(self, path, mod):
373 """ Change access mode of path
374
375 Note this is not recursive.
376
377 Parameters
378 ----------
379 path: str
380 Location to change
381 mod: str
382 Octal representation of access, e.g., "0777" for public read/write.
383 See [docs](http://hadoop.apache.org/docs/r2.4.1/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#Permission)
384 """
385 path = AzureDLPath(path).trim()
386 self.azure.call('SETPERMISSION', path.as_posix(), permission=mod)
387 self.invalidate_cache(path.as_posix())
388
389 def set_expiry(self, path, expiry_option, expire_time=None):
390 """
391 Set or remove the expiration time on the specified file.
392 This operation can only be executed against files.
393
394 Note: Folders are not supported.
395
396 Parameters
397 ----------
398 path: str
399 File path to set or remove expiration time
400 expire_time: int
401 The time that the file will expire, corresponding to the expiry_option that was set
402 expiry_option: str
403 Indicates the type of expiration to use for the file:
404 1. NeverExpire: ExpireTime is ignored.
405 2. RelativeToNow: ExpireTime is an integer in milliseconds representing the expiration date relative to when file expiration is updated.
406 3. RelativeToCreationDate: ExpireTime is an integer in milliseconds representing the expiration date relative to file creation.
407 4. Absolute: ExpireTime is an integer in milliseconds, as a Unix timestamp relative to 1/1/1970 00:00:00.
408 """
409 parms = {}
410 value_to_use = [x for x in valid_expire_types if x.lower() == expiry_option.lower()]
411 if len(value_to_use) != 1:
412 raise ValueError(
413 'expiry_option must be one of: {}. Value given: {}'.format(valid_expire_types, expiry_option))
414
415 if value_to_use[0] != ExpiryOptionType.never_expire.value and not expire_time:
416 raise ValueError(
417 'expire_time must be specified if the expiry_option is not NeverExpire. Value of expiry_option: {}'.format(
418 expiry_option))
419
420 path = AzureDLPath(path).trim()
421 parms['expiryOption'] = value_to_use[0]
422
423 if expire_time:
424 parms['expireTime'] = int(expire_time)
425
426 self.azure.call('SETEXPIRY', path.as_posix(), is_extended=True, **parms)
427 self.invalidate_cache(path.as_posix())
428
429 def _acl_call(self, action, path, acl_spec=None, invalidate_cache=False):
430 """
431 Helper method for ACL calls to reduce code repetition
432
433 Parameters
434 ----------
435 action: str
436 The ACL action being executed. For example SETACL
437 path: str
438 The path the action is being executed on (file or folder)
439 acl_spec: str
440 The optional ACL specification to set on the path in the format
441 '[default:]user|group|other:[entity id or UPN]:r|-w|-x|-,[default:]user|group|other:[entity id or UPN]:r|-w|-x|-,...'
442
443 Note that for remove acl entries the permission (rwx) portion is not required.
444 invalidate_cache: bool
445 optionally indicates that the cache of files should be invalidated after this operation
446 This should always be done for set and remove operations, since the state of the file or folder has changed.
447 """
448 parms = {}
449 path = AzureDLPath(path).trim()
450 posix_path = path.as_posix()
451 if acl_spec:
452 parms['aclSpec'] = acl_spec
453
454 to_return = self.azure.call(action, posix_path, **parms)
455 if invalidate_cache:
456 self.invalidate_cache(posix_path)
457
458 return to_return
459
460 def set_acl(self, path, acl_spec, recursive=False, number_of_sub_process=None):
461 """
462 Set the Access Control List (ACL) for a file or folder.
463
464 Note: this is by default not recursive, and applies only to the file or folder specified.
465
466 Parameters
467 ----------
468 path: str
469 Location to set the ACL on.
470 acl_spec: str
471 The ACL specification to set on the path in the format
472 '[default:]user|group|other:[entity id or UPN]:r|-w|-x|-,[default:]user|group|other:[entity id or UPN]:r|-w|-x|-,...'
473 recursive: bool
474 Specifies whether to set ACLs recursively or not
475 """
476 if recursive:
477 multi_processor_change_acl(adl=self, path=path, method_name="set_acl", acl_spec=acl_spec,
478 number_of_sub_process=number_of_sub_process)
479 else:
480 self._acl_call('SETACL', path, acl_spec, invalidate_cache=True)
481
482 def modify_acl_entries(self, path, acl_spec, recursive=False, number_of_sub_process=None):
483 """
484 Modify existing Access Control List (ACL) entries on a file or folder.
485 If the entry does not exist it is added, otherwise it is updated based on the spec passed in.
486 No entries are removed by this process (unlike set_acl).
487
488 Note: this is by default not recursive, and applies only to the file or folder specified.
489
490 Parameters
491 ----------
492 path: str
493 Location to set the ACL entries on.
494 acl_spec: str
495 The ACL specification to use in modifying the ACL at the path in the format
496 '[default:]user|group|other:[entity id or UPN]:r|-w|-x|-,[default:]user|group|other:[entity id or UPN]:r|-w|-x|-,...'
497 recursive: bool
498 Specifies whether to modify ACLs recursively or not
499 """
500 if recursive:
501 multi_processor_change_acl(adl=self, path=path, method_name="mod_acl", acl_spec=acl_spec,
502 number_of_sub_process=number_of_sub_process)
503 else:
504 self._acl_call('MODIFYACLENTRIES', path, acl_spec, invalidate_cache=True)
505
506 def remove_acl_entries(self, path, acl_spec, recursive=False, number_of_sub_process=None):
507 """
508 Remove existing, named, Access Control List (ACL) entries on a file or folder.
509 If the entry does not exist already it is ignored.
510 Default entries cannot be removed this way, please use remove_default_acl for that.
511 Unnamed entries cannot be removed in this way, please use remove_acl for that.
512
513 Note: this is by default not recursive, and applies only to the file or folder specified.
514
515 Parameters
516 ----------
517 path: str
518 Location to remove the ACL entries.
519 acl_spec: str
520 The ACL specification to remove from the ACL at the path in the format (note that the permission portion is missing)
521 '[default:]user|group|other:[entity id or UPN],[default:]user|group|other:[entity id or UPN],...'
522 recursive: bool
523 Specifies whether to remove ACLs recursively or not
524 """
525 if recursive:
526 multi_processor_change_acl(adl=self, path=path, method_name="rem_acl", acl_spec=acl_spec,
527 number_of_sub_process=number_of_sub_process)
528 else:
529 self._acl_call('REMOVEACLENTRIES', path, acl_spec, invalidate_cache=True)
530
531 def get_acl_status(self, path):
532 """
533 Gets Access Control List (ACL) entries for the specified file or directory.
534
535 Parameters
536 ----------
537 path: str
538 Location to get the ACL.
539 """
540 return self._acl_call('MSGETACLSTATUS', path)['AclStatus']
541
542 def remove_acl(self, path):
543 """
544 Remove the entire, non default, ACL from the file or folder, including unnamed entries.
545 Default entries cannot be removed this way, please use remove_default_acl for that.
546
547 Note: this is not recursive, and applies only to the file or folder specified.
548
549 Parameters
550 ----------
551 path: str
552 Location to remove the ACL.
553 """
554 self._acl_call('REMOVEACL', path, invalidate_cache=True)
555
556 def remove_default_acl(self, path):
557 """
558 Remove the entire default ACL from the folder.
559 Default entries do not exist on files, if a file
560 is specified, this operation does nothing.
561
562 Note: this is not recursive, and applies only to the folder specified.
563
564 Parameters
565 ----------
566 path: str
567 Location to set the ACL on.
568 """
569 self._acl_call('REMOVEDEFAULTACL', path, invalidate_cache=True)
570
571 def chown(self, path, owner=None, group=None):
572 """
573 Change owner and/or owning group
574
575 Note this is not recursive.
576
577 Parameters
578 ----------
579 path: str
580 Location to change
581 owner: str
582 UUID of owning entity
583 group: str
584 UUID of group
585 """
586 parms = {}
587 if owner is None and group is None:
588 raise ValueError('Must supply owner and/or group')
589 if owner:
590 parms['owner'] = owner
591 if group:
592 parms['group'] = group
593 path = AzureDLPath(path).trim()
594 self.azure.call('SETOWNER', path.as_posix(), **parms)
595 self.invalidate_cache(path.as_posix())
596
597 def exists(self, path, invalidate_cache=True):
598 """
599 Does such a file/directory exist?
600
601 Parameters
602 ----------
603 path: str or AzureDLPath
604 Path to query
605 invalidate_cache: bool
606 Whether to invalidate cache
607
608 Returns
609 -------
610 True or false depending on whether the path exists.
611 """
612 try:
613 self.info(path, invalidate_cache, expected_error_code=404)
614 return True
615 except FileNotFoundError:
616 return False
617
618 def cat(self, path):
619 """
620 Return contents of file
621
622 Parameters
623 ----------
624 path: str or AzureDLPath
625 Path to query
626
627 Returns
628 -------
629 Contents of file
630 """
631 with self.open(path, 'rb') as f:
632 return f.read()
633
634 def tail(self, path, size=1024):
635 """
636 Return last bytes of file
637
638 Parameters
639 ----------
640 path: str or AzureDLPath
641 Path to query
642 size: int
643 How many bytes to return
644
645 Returns
646 -------
647 Last(size) bytes of file
648 """
649 length = self.info(path)['length']
650 if size > length:
651 return self.cat(path)
652 with self.open(path, 'rb') as f:
653 f.seek(length - size)
654 return f.read(size)
655
656 def head(self, path, size=1024):
657 """
658 Return first bytes of file
659
660 Parameters
661 ----------
662 path: str or AzureDLPath
663 Path to query
664 size: int
665 How many bytes to return
666
667 Returns
668 -------
669 First(size) bytes of file
670 """
671 with self.open(path, 'rb', blocksize=size) as f:
672 return f.read(size)
673
674 def get(self, path, filename):
675 """
676 Stream data from file at path to local filename
677
678 Parameters
679 ----------
680 path: str or AzureDLPath
681 ADL Path to read
682 filename: str or Path
683 Local file path to write to
684
685 Returns
686 -------
687 None
688 """
689 with self.open(path, 'rb') as f:
690 with open(filename, 'wb') as f2:
691 while True:
692 data = f.read(f.blocksize)
693 if len(data) == 0:
694 break
695 f2.write(data)
696
697 def put(self, filename, path, delimiter=None):
698 """
699 Stream data from local filename to file at path
700
701 Parameters
702 ----------
703 filename: str or Path
704 Local file path to read from
705 path: str or AzureDLPath
706 ADL Path to write to
707 delimiter:
708 Optional delimeter for delimiter-ended blocks
709
710 Returns
711 -------
712 None
713 """
714 with open(filename, 'rb') as f:
715 with self.open(path, 'wb', delimiter=delimiter) as f2:
716 while True:
717 data = f.read(f2.blocksize)
718 if len(data) == 0:
719 break
720 f2.write(data)
721
722 def mkdir(self, path):
723 """
724 Make new directory
725
726 Parameters
727 ----------
728 path: str or AzureDLPath
729 Path to create directory
730
731 Returns
732 -------
733 None
734 """
735 """ """
736 path = AzureDLPath(path).trim()
737 self.azure.call('MKDIRS', path.as_posix())
738 self.invalidate_cache(path)
739
740 def rmdir(self, path):
741 """
742 Remove empty directory
743
744 Parameters
745 ----------
746 path: str or AzureDLPath
747 Directory path to remove
748
749 Returns
750 -------
751 None
752 """
753 if self.info(path)['type'] != "DIRECTORY":
754 raise ValueError('Can only rmdir on directories')
755 # should always invalidate the cache when checking to see if the directory is empty
756 if self.ls(path, invalidate_cache=True):
757 raise ValueError('Directory not empty: %s' % path)
758 self.rm(path, False)
759
760 def mv(self, path1, path2):
761 """
762 Move file between locations on ADL
763
764 Parameters
765 ----------
766 path1:
767 Source Path
768 path2:
769 Destination path
770
771 Returns
772 -------
773 None
774 """
775 path1 = AzureDLPath(path1).trim()
776 path2 = AzureDLPath(path2).trim()
777 self.azure.call('RENAME', path1.as_posix(),
778 destination=path2.as_posix())
779 self.invalidate_cache(path1)
780 self.invalidate_cache(path2)
781
782 def concat(self, outfile, filelist, delete_source=False):
783 """ Concatenate a list of files into one new file
784
785 Parameters
786 ----------
787
788 outfile: path
789 The file which will be concatenated to. If it already exists,
790 the extra pieces will be appended.
791 filelist: list of paths
792 Existing adl files to concatenate, in order
793 delete_source: bool (False)
794 If True, assume that the paths to concatenate exist alone in a
795 directory, and delete that whole directory when done.
796
797 Returns
798 -------
799 None
800 """
801 outfile = AzureDLPath(outfile).trim()
802 delete = 'true' if delete_source else 'false'
803 sourceList = [AzureDLPath(f).as_posix() for f in filelist]
804 sources = {}
805 sources["sources"] = sourceList
806
807 self.azure.call('MSCONCAT', outfile.as_posix(),
808 data=bytearray(json.dumps(sources, separators=(',', ':')), encoding="utf-8"),
809 deleteSourceDirectory=delete,
810 headers={'Content-Type': "application/json"},
811 retry_policy=NoRetryPolicy())
812 self.invalidate_cache(outfile)
813
814 merge = concat
815
816 def cp(self, path1, path2):
817 """ Not implemented. Copy file between locations on ADL """
818 # TODO: any implementation for this without download?
819 raise NotImplementedError
820
821 def rm(self, path, recursive=False):
822 """
823 Remove a file or directory
824
825 Parameters
826 ----------
827 path: str or AzureDLPath
828 The location to remove.
829 recursive: bool (True)
830 Whether to remove also all entries below, i.e., which are returned
831 by `walk()`.
832
833 Returns
834 -------
835 None
836 """
837 path = AzureDLPath(path).trim()
838 # Always invalidate the cache when attempting to check existence of something to delete
839 if not self.exists(path, invalidate_cache=True):
840 raise FileNotFoundError(path)
841 self.azure.call('DELETE', path.as_posix(), recursive=recursive)
842 self.invalidate_cache(path)
843 if recursive:
844 matches = [p for p in self.dirs if p.startswith(path.as_posix())]
845 [self.invalidate_cache(m) for m in matches]
846
847 def invalidate_cache(self, path=None):
848 """
849 Remove entry from object file-cache
850
851 Parameters
852 ----------
853 path: str or AzureDLPath
854 Remove the path from object file-cache
855
856 Returns
857 -------
858 None
859 """
860 if path is None:
861 self.dirs.clear()
862 else:
863 path = AzureDLPath(path).trim()
864 self.dirs.pop(path.as_posix(), None)
865 parent = AzureDLPath(path.parent).trim()
866 self.dirs.pop(parent.as_posix(), None)
867
868 def touch(self, path):
869 """
870 Create empty file
871
872 Parameters
873 ----------
874 path: str or AzureDLPath
875 Path of file to create
876
877 Returns
878 -------
879 None
880 """
881 with self.open(path, 'wb'):
882 pass
883
884 def read_block(self, fn, offset, length, delimiter=None):
885 """ Read a block of bytes from an ADL file
886
887 Starting at ``offset`` of the file, read ``length`` bytes. If
888 ``delimiter`` is set then we ensure that the read starts and stops at
889 delimiter boundaries that follow the locations ``offset`` and ``offset
890 + length``. If ``offset`` is zero then we start at zero. The
891 bytestring returned WILL include the end delimiter string.
892
893 If offset+length is beyond the eof, reads to eof.
894
895 Parameters
896 ----------
897 fn: string
898 Path to filename on ADL
899 offset: int
900 Byte offset to start read
901 length: int
902 Number of bytes to read
903 delimiter: bytes (optional)
904 Ensure reading starts and stops at delimiter bytestring
905
906 Examples
907 --------
908 >>> adl.read_block('data/file.csv', 0, 13) # doctest: +SKIP
909 b'Alice, 100\\nBo'
910 >>> adl.read_block('data/file.csv', 0, 13, delimiter=b'\\n') # doctest: +SKIP
911 b'Alice, 100\\nBob, 200\\n'
912
913 Use ``length=None`` to read to the end of the file.
914 >>> adl.read_block('data/file.csv', 0, None, delimiter=b'\\n') # doctest: +SKIP
915 b'Alice, 100\\nBob, 200\\nCharlie, 300'
916
917 See Also
918 --------
919 distributed.utils.read_block
920 """
921 with self.open(fn, 'rb') as f:
922 size = f.info()['length']
923 if offset >= size:
924 return b''
925 if length is None:
926 length = size
927 if offset + length > size:
928 length = size - offset
929 bytes = read_block(f, offset, length, delimiter)
930 return bytes
931
932 # ALIASES
933 listdir = ls
934 access = exists
935 rename = mv
936 stat = info
937 unlink = remove = rm
938
939
940 class AzureDLFile(object):
941 """
942 Open ADL key as a file. Data is only loaded and cached on demand.
943
944 Parameters
945 ----------
946 azure: azure connection
947 path: AzureDLPath
948 location of file
949 mode: str {'wb', 'rb', 'ab'}
950 blocksize: int
951 Size of the write or read-ahead buffer. For writing(and appending, will be
952 truncated to 4MB (2**22).
953 delimiter: bytes or None
954 If specified and in write mode, each flush will send data terminating
955 on this bytestring, potentially leaving some data in the buffer.
956
957 Examples
958 --------
959 >>> adl = AzureDLFileSystem() # doctest: +SKIP
960 >>> with adl.open('my-dir/my-file.txt', mode='rb') as f: # doctest: +SKIP
961 ... f.read(10) # doctest: +SKIP
962
963 See Also
964 --------
965 AzureDLFileSystem.open: used to create AzureDLFile objects
966 """
967
968 def __init__(self, azure, path, mode='rb', blocksize=2 ** 25,
969 delimiter=None):
970 self.mode = mode
971 if mode not in {'rb', 'wb', 'ab'}:
972 raise NotImplementedError("File mode must be {'rb', 'wb', 'ab'}, not %s" % mode)
973 self.path = path
974 self.azure = azure
975 self.cache = b""
976 self.loc = 0
977 self.delimiter = delimiter
978 self.start = 0
979 self.end = 0
980 self.closed = False
981 self.trim = True
982 self.buffer = io.BytesIO()
983 self.blocksize = blocksize
984 uniqueid = str(uuid.uuid4())
985 self.filesessionid = uniqueid
986 self.leaseid = uniqueid
987
988 # always invalidate the cache when checking for existence of a file
989 # that may be created or written to (for the first time).
990 try:
991 file_data = self.azure.info(path, invalidate_cache=True, expected_error_code=404)
992 exists = True
993 except FileNotFoundError:
994 exists = False
995
996 # cannot create a new file object out of a directory
997 if exists and file_data['type'] == 'DIRECTORY':
998 raise IOError(
999 'path: {} is a directory, not a file, and cannot be opened for reading or writing'.format(path))
1000
1001 if mode == 'ab' or mode == 'wb':
1002 self.blocksize = min(2 ** 22, blocksize)
1003
1004 if mode == 'ab' and exists:
1005 self.loc = file_data['length']
1006 elif (mode == 'ab' and not exists) or (mode == 'wb'):
1007 # Create the file
1008 _put_data_with_retry(
1009 rest=self.azure.azure,
1010 op='CREATE',
1011 path=self.path.as_posix(),
1012 data=None,
1013 overwrite='true',
1014 write='true',
1015 syncFlag='DATA',
1016 leaseid=self.leaseid,
1017 filesessionid=self.filesessionid)
1018 logger.debug('Created file %s ' % self.path)
1019 else: # mode == 'rb':
1020 if not exists:
1021 raise FileNotFoundError(path.as_posix())
1022 self.size = file_data['length']
1023
1024 def info(self):
1025 """ File information about this path """
1026 return self.azure.info(self.path)
1027
1028 def tell(self):
1029 """ Current file location """
1030 return self.loc
1031
1032 def seek(self, loc, whence=0):
1033 """ Set current file location
1034
1035 Parameters
1036 ----------
1037 loc: int
1038 byte location
1039 whence: {0, 1, 2}
1040 from start of file, current location or end of file, resp.
1041 """
1042 if not self.mode == 'rb':
1043 raise ValueError('Seek only available in read mode')
1044 if whence == 0:
1045 nloc = loc
1046 elif whence == 1:
1047 nloc = self.loc + loc
1048 elif whence == 2:
1049 nloc = self.size + loc
1050 else:
1051 raise ValueError(
1052 "invalid whence (%s, should be 0, 1 or 2)" % whence)
1053 if nloc < 0:
1054 raise ValueError('Seek before start of file')
1055 if nloc > self.size:
1056 raise ValueError('ADLFS does not support seeking beyond file')
1057 self.loc = nloc
1058 return self.loc
1059
1060 def readline(self, length=-1):
1061 """
1062 Read and return a line from the stream.
1063
1064 If length is specified, at most size bytes will be read.
1065 """
1066 if length < 0:
1067 length = self.size
1068
1069 line = b""
1070 while True:
1071
1072 # if cache has last bytes of file and its read, return line and exit loop
1073 if self.end >= self.size and self.loc >= self.end:
1074 return line
1075
1076 self._read_blocksize()
1077
1078 found = self.cache[self.loc - self.start:].find(b'\n') + 1
1079 if found:
1080 partialLine = self.cache[
1081 self.loc - self.start: min(self.loc - self.start + found, self.loc - self.start + length)]
1082 else:
1083 partialLine = self.cache[self.loc - self.start:]
1084
1085 self.loc += len(partialLine)
1086 line += partialLine
1087
1088 if found:
1089 return line
1090
1091 def __next__(self):
1092 out = self.readline()
1093 if not out:
1094 raise StopIteration
1095 return out
1096
1097 next = __next__
1098
1099 def __iter__(self):
1100 return self
1101
1102 def readlines(self):
1103 """ Return all lines in a file as a list """
1104 return list(self)
1105
1106 def _fetch(self, start, end):
1107 self.start = start
1108 self.end = min(end, self.size)
1109 response = _fetch_range_with_retry(
1110 self.azure.azure, self.path.as_posix(), self.start, self.end, filesessionid=self.filesessionid)
1111 self.cache = getattr(response, 'content', response)
1112
1113 def _read_blocksize(self, offset=-1):
1114 """
1115 Reads next blocksize of data and updates the cache if read offset is not within cache otherwise nop
1116
1117 Parameters
1118 ----------
1119 offset: int (-1)
1120 offset from where to read; if <0, last read location or beginning of file.
1121
1122 Returns
1123 -------
1124 None
1125 """
1126 if offset < 0:
1127 offset = self.loc
1128 if offset >= self.size:
1129 self.start = self.size
1130 self.end = self.size
1131 self.cache = b""
1132 return
1133 if self.start <= offset < self.end:
1134 logger.debug("Read offset {offset} is within cache {start}-{end}. "
1135 "Not going to server.".format(offset=offset, start=self.start, end=self.end))
1136 return
1137 if offset > self.size:
1138 raise ValueError('Read offset is outside the File')
1139 self._fetch(offset, offset + self.blocksize)
1140
1141 def read(self, length=-1):
1142 """
1143 Return data from cache, or fetch pieces as necessary
1144
1145 Parameters
1146 ----------
1147 length: int (-1)
1148 Number of bytes to read; if <0, all remaining bytes.
1149 """
1150 if self.mode != 'rb':
1151 raise ValueError('File not in read mode')
1152 if length < 0:
1153 length = self.size
1154 if self.closed:
1155 raise ValueError('I/O operation on closed file.')
1156 flag = 0
1157 out = b""
1158 while length > 0:
1159 self._read_blocksize()
1160 data_read = self.cache[self.loc - self.start:
1161 min(self.loc - self.start + length, self.end - self.start)]
1162 if not data_read: # Check to catch possible server errors. Ideally shouldn't happen.
1163 flag += 1
1164 if flag >= 5:
1165 exception_string = "Current Location:{loc}, " \
1166 "File Size:{size}, Cache Start:{start}, " \
1167 "Cache End:{end}".format(loc=self.loc, size=self.size,
1168 start=self.start, end=self.end)
1169 raise DatalakeIncompleteTransferException('Could not read data: {path}. '
1170 'Repeated zero byte reads. Possible file corruption. File Details'
1171 '{details}'.format(path=self.path, details=exception_string))
1172 out += data_read
1173 self.loc += len(data_read)
1174 length -= len(data_read)
1175 if self.loc >= self.size:
1176 length = 0
1177
1178 return out
1179
1180 read1 = read
1181
1182 def readinto(self, b):
1183 """
1184 Reads data into buffer b
1185
1186
1187 Parameters
1188 ----------
1189 b: bytearray
1190 Buffer to which bytes are read into
1191
1192 Returns
1193 -------
1194 Returns number of bytes read.
1195 """
1196 temp = self.read(len(b))
1197 b[:len(temp)] = temp
1198 return len(temp)
1199
1200 def write(self, data):
1201 """
1202 Write data to buffer.
1203
1204 Buffer only sent to ADL on flush() or if buffer is bigger than
1205 blocksize.
1206
1207 Parameters
1208 ----------
1209 data: bytes
1210 Set of bytes to be written.
1211 """
1212 if self.mode not in {'wb', 'ab'}:
1213 raise ValueError('File not in write mode')
1214 if self.closed:
1215 raise ValueError('I/O operation on closed file.')
1216
1217 # TODO Flush may be simplified
1218 # Buffered writes so a very large buffer is not copied leading to very large memory consumption
1219 bytes_written = 0
1220 for i in range(0, len(data), self.blocksize):
1221 out = self.buffer.write(ensure_writable(data[i:i + self.blocksize]))
1222 self.loc += out
1223 bytes_written += out
1224 self.flush(syncFlag='DATA')
1225 return bytes_written
1226
1227 def flush(self, syncFlag='METADATA', force=False):
1228 """
1229 Write buffered data to ADL.
1230
1231 Without delimiter: Uploads the current buffer.
1232
1233 With delimiter: writes an amount of data less than or equal to the
1234 block-size, which ends on the delimiter, until buffer is smaller than
1235 the blocksize. If there is no delimiter in a block uploads whole block.
1236
1237 If force=True, flushes all data in the buffer, even if it doesn't end
1238 with a delimiter; appropriate when closing the file.
1239 """
1240 if not self.writable() or self.closed:
1241 return
1242
1243 if not (syncFlag == 'METADATA' or syncFlag == 'DATA' or syncFlag == 'CLOSE'):
1244 raise ValueError('syncFlag must be one of these: METADATA, DATA or CLOSE')
1245
1246 common_args_append = {
1247 'rest': self.azure.azure,
1248 'op': 'APPEND',
1249 'path': self.path.as_posix(),
1250 'append': 'true',
1251 'leaseid': self.leaseid,
1252 'filesessionid': self.filesessionid
1253 }
1254 self.buffer.seek(0) # Go to start of buffer
1255 data = self.buffer.read()
1256
1257 while len(data) > self.blocksize:
1258 data_to_write_limit = self.blocksize
1259 if self.delimiter:
1260 delimiter_index = data.rfind(self.delimiter, 0, self.blocksize)
1261 if delimiter_index != -1: # delimiter found
1262 data_to_write_limit = delimiter_index + len(self.delimiter)
1263
1264 offset = self.tell() - len(data)
1265 _put_data_with_retry(syncFlag='DATA', data=data[:data_to_write_limit], offset=offset, **common_args_append)
1266 logger.debug('Wrote %d bytes to %s' % (data_to_write_limit, self))
1267 data = data[data_to_write_limit:]
1268
1269 if force:
1270 offset = self.tell() - len(data)
1271 _put_data_with_retry(syncFlag=syncFlag, data=data, offset=offset, **common_args_append)
1272 logger.debug('Wrote %d bytes to %s' % (len(data), self))
1273 data = b''
1274
1275 self.buffer = io.BytesIO(data)
1276 self.buffer.seek(0, 2) # seek to end for other writes to buffer
1277
1278 def close(self):
1279 """ Close file
1280
1281 If in write mode, causes flush of any unwritten data.
1282 """
1283 logger.debug("closing stream")
1284 if self.closed:
1285 return
1286 if self.writable():
1287 self.flush(syncFlag='CLOSE', force=True)
1288 self.azure.invalidate_cache(self.path.as_posix())
1289 self.closed = True
1290
1291 def readable(self):
1292 """Return whether the AzureDLFile was opened for reading"""
1293 return self.mode == 'rb'
1294
1295 def seekable(self):
1296 """Return whether the AzureDLFile is seekable (only in read mode)"""
1297 return self.readable()
1298
1299 def writable(self):
1300 """Return whether the AzureDLFile was opened for writing"""
1301 return self.mode in {'wb', 'ab'}
1302
1303 def __str__(self):
1304 return "<ADL file: %s>" % (self.path.as_posix())
1305
1306 __repr__ = __str__
1307
1308 def __enter__(self):
1309 return self
1310
1311 def __exit__(self, *args):
1312 self.close()
1313
1314
1315 def _fetch_range(rest, path, start, end, stream=False, retry_policy=ExponentialRetryPolicy(), **kwargs):
1316 logger.debug('Fetch: %s, %s-%s', path, start, end)
1317 # if the caller gives a bad start/end combination, OPEN will throw and
1318 # this call will bubble it up
1319 return rest.call(
1320 'OPEN', path, offset=start, length=end - start, read='true', stream=stream, retry_policy=retry_policy, **kwargs)
1321
1322
1323 def _fetch_range_with_retry(rest, path, start, end, stream=False, retries=10,
1324 delay=0.01, backoff=3, **kwargs):
1325 err = None
1326 retry_policy = ExponentialRetryPolicy(max_retries=retries, exponential_retry_interval=delay,
1327 exponential_factor=backoff)
1328 try:
1329 return _fetch_range(rest, path, start, end, stream=False, retry_policy=retry_policy, **kwargs)
1330 except Exception as e:
1331 err = e
1332 exception = RuntimeError('Max number of ADL retries exceeded: exception ' + repr(err))
1333 rest.log_response_and_raise(None, exception)
1334
1335
1336 def _put_data(rest, op, path, data, retry_policy=ExponentialRetryPolicy(), **kwargs):
1337 logger.debug('Put: %s %s, %s', op, path, kwargs)
1338 return rest.call(op, path=path, data=data, retry_policy=retry_policy, **kwargs)
1339
1340
1341 def _put_data_with_retry(rest, op, path, data, retries=10, delay=0.01, backoff=3,
1342 **kwargs):
1343 err = None
1344 retry_policy = ExponentialRetryPolicy(max_retries=retries, exponential_retry_interval=delay,
1345 exponential_factor=backoff)
1346 try:
1347 return _put_data(rest, op, path, data, retry_policy=retry_policy, **kwargs)
1348 except (PermissionError, FileNotFoundError) as e:
1349 rest.log_response_and_raise(None, e)
1350 except DatalakeBadOffsetException as e:
1351 try:
1352 # There is a possibility that a call in previous retry succeeded in the backend
1353 # but didn't generate a response. In that case, any other retry will fail as the
1354 # data is already written. We can try a zero byte append at len(data) + offset
1355 # and see if it succeeds. If it does, we assume that data is written and carry on.
1356 current_offset = kwargs.pop('offset', None)
1357 if current_offset is None:
1358 raise e
1359 return _put_data(rest, op, path, [], retry_policy=retry_policy, offset=current_offset + len(data), **kwargs)
1360 except:
1361 rest.log_response_and_raise(None, e)
1362 except Exception as e:
1363 err = e
1364 logger.debug('Exception %s on ADL upload',
1365 repr(err))
1366 exception = RuntimeError('Max number of ADL retries exceeded: exception ' + repr(err))
1367 rest.log_response_and_raise(None, exception)
1368
1369
1370 class AzureDLPath(type(pathlib.PurePath())):
1371 """
1372 Subclass of native object-oriented filesystem path.
1373
1374 This is used as a convenience class for reducing boilerplate and
1375 eliminating differences between system-dependent paths.
1376
1377 We subclass the system's concrete pathlib class due to this issue:
1378
1379 http://stackoverflow.com/questions/29850801/subclass-pathlib-path-fails
1380
1381 Parameters
1382 ----------
1383 path: AzureDLPath or string
1384 location of file or directory
1385
1386 Examples
1387 --------
1388 >>> p1 = AzureDLPath('/Users/foo') # doctest: +SKIP
1389 >>> p2 = AzureDLPath(p1.name) # doctest: +SKIP
1390 """
1391
1392 def __contains__(self, s):
1393 """ Return whether string is contained in path. """
1394 return s in self.as_posix()
1395
1396 def __getstate__(self):
1397 return self.as_posix()
1398
1399 def __setstate__(self, state):
1400 self.__init__(state)
1401
1402 @property
1403 def globless_prefix(self):
1404 """ Return shortest path prefix without glob quantifiers. """
1405 parts = []
1406 for part in self.parts:
1407 if any(q in part for q in ['*', '?']):
1408 break
1409 parts.append(part)
1410 return pathlib.PurePath(*parts)
1411
1412 def startswith(self, prefix, *args, **kwargs):
1413 """ Return whether string starts with the prefix.
1414
1415 This is equivalent to `str.startswith`.
1416 """
1417 return self.as_posix().startswith(prefix.as_posix(), *args, **kwargs)
1418
1419 def trim(self):
1420 """ Return path without anchor (concatenation of drive and root). """
1421 return self.relative_to(self.anchor)