-
Notifications
You must be signed in to change notification settings - Fork 104
/
spec.py
2236 lines (1965 loc) · 79.1 KB
/
spec.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import asyncio
import errno
import io
import logging
import os
import re
import typing
import warnings
import weakref
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from glob import has_magic
from typing import List, Optional, Tuple
from uuid import uuid4
from azure.core.exceptions import (
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
)
from azure.core.utils import parse_connection_string
from azure.storage.blob import (
BlobBlock,
BlobProperties,
BlobSasPermissions,
BlobType,
generate_blob_sas,
)
from azure.storage.blob.aio import BlobPrefix
from azure.storage.blob.aio import BlobServiceClient as AIOBlobServiceClient
from fsspec.asyn import AsyncFileSystem, _get_batch_size, get_loop, sync, sync_wrapper
from fsspec.spec import AbstractBufferedFile
from fsspec.utils import infer_storage_options
from .utils import (
close_container_client,
close_credential,
close_service_client,
filter_blobs,
get_blob_metadata,
match_blob_version,
)
logger = logging.getLogger(__name__)
FORWARDED_BLOB_PROPERTIES = [
"metadata",
"creation_time",
"deleted",
"deleted_time",
"last_modified",
"content_time",
"content_settings",
"remaining_retention_days",
"archive_status",
"last_accessed_on",
"etag",
"tags",
"tag_count",
]
VERSIONED_BLOB_PROPERTIES = [
"version_id",
"is_current_version",
]
_ROOT_PATH = "/"
_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024
_SOCKET_TIMEOUT_DEFAULT = object()
# https://github.com/Azure/azure-sdk-for-python/issues/11419#issuecomment-628143480
def make_callback(key, callback):
if callback is None:
return None
sent_total = False
def wrapper(response):
nonlocal sent_total
current = response.context.get(key)
total = response.context["data_stream_total"]
if current is None:
return
if not sent_total and total is not None:
callback.set_size(total)
callback.absolute_update(current)
return wrapper
def get_running_loop():
# this was removed from fsspec in https://github.com/fsspec/filesystem_spec/pull/1134
if hasattr(asyncio, "get_running_loop"):
return asyncio.get_running_loop()
else:
loop = asyncio._get_running_loop()
if loop is None:
raise RuntimeError("no running event loop")
else:
return loop
def _coalesce_version_id(*args) -> Optional[str]:
"""Helper to coalesce a list of version_ids down to one"""
version_ids = set(args)
if None in version_ids:
version_ids.remove(None)
if len(version_ids) > 1:
raise ValueError(
"Cannot coalesce version_ids where more than one are defined,"
" {}".format(version_ids)
)
elif len(version_ids) == 0:
return None
else:
return version_ids.pop()
class AzureBlobFileSystem(AsyncFileSystem):
"""
Access Azure Datalake Gen2 and Azure Storage if it were a file system using Multiprotocol Access
Parameters
----------
account_name: str
The storage account name. This is used to authenticate requests
signed with an account key and to construct the storage endpoint. It
is required unless a connection string is given, or if a custom
domain is used with anonymous authentication.
account_key: str
The storage account key. This is used for shared key authentication.
If any of account key, sas token or client_id is specified, anonymous access
will be used.
sas_token: str
A shared access signature token to use to authenticate requests
instead of the account key. If account key and sas token are both
specified, account key will be used to sign. If any of account key, sas token
or client_id are specified, anonymous access will be used.
request_session: Session
The session object to use for http requests.
connection_string: str
If specified, this will override all other parameters besides
request session. See
http://azure.microsoft.com/en-us/documentation/articles/storage-configure-connection-string/
for the connection string format.
credential: azure.core.credentials_async.AsyncTokenCredential or SAS token
The credentials with which to authenticate. Optional if the account URL already has a SAS token.
Can include an instance of TokenCredential class from azure.identity.aio.
blocksize: int
The block size to use for download/upload operations. Defaults to hardcoded value of
``BlockBlobService.MAX_BLOCK_SIZE``
client_id: str
Client ID to use when authenticating using an AD Service Principal client/secret.
client_secret: str
Client secret to use when authenticating using an AD Service Principal client/secret.
tenant_id: str
Tenant ID to use when authenticating using an AD Service Principal client/secret.
anon: boolean, optional
The value to use for whether to attempt anonymous access if no other credential is
passed. By default (``None``), the ``AZURE_STORAGE_ANON`` environment variable is
checked. False values (``false``, ``0``, ``f``) will resolve to `False` and
anonymous access will not be attempted. Otherwise the value for ``anon`` resolves
to ``True``.
default_fill_cache: bool = True
Whether to use cache filling with open by default
default_cache_type: string ('bytes')
If given, the default cache_type value used for "open()". Set to none if no caching
is desired. Docs in fsspec
version_aware : bool (False)
Whether to support blob versioning. If enable this will require the
user to have the necessary permissions for dealing with versioned blobs.
assume_container_exists: Optional[bool] (None)
Set this to true to not check for existence of containers at all, assuming they exist.
None (default) means to warn in case of a failure when checking for existence of a container
False throws if retrieving container properties fails, which might happen if your
authentication is only valid at the storage container level, and not the
storage account level.
max_concurrency:
The number of concurrent connections to use when uploading or downloading a blob.
If None it will be inferred from fsspec.asyn._get_batch_size().
timeout: int
Sets the server-side timeout when uploading or downloading a blob.
connection_timeout: int
The number of seconds the client will wait to establish a connection to the server
when uploading or downloading a blob.
read_timeout: int
The number of seconds the client will wait, between consecutive read operations,
for a response from the server while uploading or downloading a blob.
account_host: str
The storage account host. This string is the entire url to the for the storage
after the https://, i.e. "https://{account_host}". This parameter is only
required for Azure clouds where account urls do not end with "blob.core.windows.net".
Note that the account_name parameter is still required.
Pass on to fsspec:
skip_instance_cache: to control reuse of instances
use_listings_cache, listings_expiry_time, max_paths: to control reuse of directory listings
Examples
--------
Authentication with an account_key
>>> abfs = AzureBlobFileSystem(account_name="XXXX", account_key="XXXX")
>>> abfs.ls('')
Authentication with an Azure ServicePrincipal
>>> abfs = AzureBlobFileSystem(account_name="XXXX", tenant_id=TENANT_ID,
... client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
>>> abfs.ls('')
Authentication with DefaultAzureCredential
>>> abfs = AzureBlobFileSystem(account_name="XXXX", anon=False)
>>> abfs.ls('')
Read files as
>>> ddf = dd.read_csv('abfs://container_name/folder/*.csv', storage_options={
... 'account_name': ACCOUNT_NAME, 'tenant_id': TENANT_ID, 'client_id': CLIENT_ID,
... 'client_secret': CLIENT_SECRET})
... })
Sharded Parquet & csv files can be read as:
>>> ddf = dd.read_csv('abfs://container_name/folder/*.csv', storage_options={
... 'account_name': ACCOUNT_NAME, 'account_key': ACCOUNT_KEY})
>>> ddf = dd.read_parquet('abfs://container_name/folder.parquet', storage_options={
... 'account_name': ACCOUNT_NAME, 'account_key': ACCOUNT_KEY,})
"""
protocol = "abfs"
def __init__(
self,
account_name: str = None,
account_key: str = None,
connection_string: str = None,
credential: str = None,
sas_token: str = None,
request_session=None,
socket_timeout=_SOCKET_TIMEOUT_DEFAULT,
blocksize: int = _DEFAULT_BLOCK_SIZE,
client_id: str = None,
client_secret: str = None,
tenant_id: str = None,
anon: bool = None,
location_mode: str = "primary",
loop=None,
asynchronous: bool = False,
default_fill_cache: bool = True,
default_cache_type: str = "bytes",
version_aware: bool = False,
assume_container_exists: Optional[bool] = None,
max_concurrency: Optional[int] = None,
timeout: Optional[int] = None,
connection_timeout: Optional[int] = None,
read_timeout: Optional[int] = None,
account_host: str = None,
**kwargs,
):
self.kwargs = kwargs.copy()
super_kwargs = {
k: kwargs.pop(k)
for k in ["use_listings_cache", "listings_expiry_time", "max_paths"]
if k in kwargs
} # pass on to fsspec superclass
super().__init__(
asynchronous=asynchronous, loop=loop or get_loop(), **super_kwargs
)
self.account_name = account_name or os.getenv("AZURE_STORAGE_ACCOUNT_NAME")
self.account_key = account_key or os.getenv("AZURE_STORAGE_ACCOUNT_KEY")
self.connection_string = connection_string or os.getenv(
"AZURE_STORAGE_CONNECTION_STRING"
)
self.sas_token = sas_token or os.getenv("AZURE_STORAGE_SAS_TOKEN")
self.client_id = client_id or os.getenv("AZURE_STORAGE_CLIENT_ID")
self.client_secret = client_secret or os.getenv("AZURE_STORAGE_CLIENT_SECRET")
self.tenant_id = tenant_id or os.getenv("AZURE_STORAGE_TENANT_ID")
if anon is not None:
self.anon = anon
else:
self.anon = os.getenv("AZURE_STORAGE_ANON", "true").lower() not in [
"false",
"0",
"f",
]
self.location_mode = location_mode
self.credential = credential
if account_host:
self.account_host = account_host
self.request_session = request_session
self.assume_container_exists = assume_container_exists
if socket_timeout is not _SOCKET_TIMEOUT_DEFAULT:
warnings.warn(
"socket_timeout is deprecated and has no effect.", FutureWarning
)
self.blocksize = blocksize
self.default_fill_cache = default_fill_cache
self.default_cache_type = default_cache_type
self.version_aware = version_aware
self._timeout_kwargs = {}
if timeout is not None:
self._timeout_kwargs["timeout"] = timeout
if connection_timeout is not None:
self._timeout_kwargs["connection_timeout"] = connection_timeout
if read_timeout is not None:
self._timeout_kwargs["read_timeout"] = read_timeout
if (
self.credential is None
and self.account_key is None
and self.sas_token is None
and self.client_id is not None
):
(
self.credential,
self.sync_credential,
) = self._get_credential_from_service_principal()
else:
self.sync_credential = None
# Solving issue in https://github.com/fsspec/adlfs/issues/270
if (
self.credential is None
and self.anon is False
and self.sas_token is None
and self.account_key is None
):
(
self.credential,
self.sync_credential,
) = self._get_default_azure_credential(**kwargs)
self.do_connect()
weakref.finalize(self, sync, self.loop, close_service_client, self)
if self.credential is not None:
weakref.finalize(self, sync, self.loop, close_credential, self)
if max_concurrency is None:
batch_size = _get_batch_size()
if batch_size > 0:
max_concurrency = batch_size
self.max_concurrency = max_concurrency
@classmethod
def _strip_protocol(cls, path: str):
"""
Remove the protocol from the input path
Parameters
----------
path: str
Path to remove the protocol from
Returns
-------
str
Returns a path without the protocol
"""
if isinstance(path, list):
return [cls._strip_protocol(p) for p in path]
STORE_SUFFIX = ".dfs.core.windows.net"
logger.debug(f"_strip_protocol for {path}")
if not path.startswith(("abfs://", "az://", "abfss://")):
path = path.lstrip("/")
path = "abfs://" + path
ops = infer_storage_options(path)
if "username" in ops:
if ops.get("username", None):
ops["path"] = ops["username"] + ops["path"]
# we need to make sure that the path retains
# the format {host}/{path}
# here host is the container_name
elif ops.get("host", None):
if (
ops["host"].count(STORE_SUFFIX) == 0
): # no store-suffix, so this is container-name
ops["path"] = ops["host"] + ops["path"]
url_query = ops.get("url_query")
if url_query is not None:
ops["path"] = f"{ops['path']}?{url_query}"
logger.debug(f"_strip_protocol({path}) = {ops}")
stripped_path = ops["path"].lstrip("/")
return stripped_path
@staticmethod
def _get_kwargs_from_urls(urlpath):
"""Get the account_name from the urlpath and pass to storage_options"""
ops = infer_storage_options(urlpath)
out = {}
host = ops.get("host", None)
if host:
match = re.match(
r"(?P<account_name>.+)\.(dfs|blob)\.core\.windows\.net", host
)
if match:
account_name = match.groupdict()["account_name"]
out["account_name"] = account_name
url_query = ops.get("url_query")
if url_query is not None:
from urllib.parse import parse_qs
parsed = parse_qs(url_query)
if "versionid" in parsed:
out["version_aware"] = True
return out
def _get_credential_from_service_principal(self):
"""
Create a Credential for authentication. This can include a TokenCredential
client_id, client_secret and tenant_id
Returns
-------
Tuple of (Async Credential, Sync Credential).
"""
from azure.identity import ClientSecretCredential
from azure.identity.aio import (
ClientSecretCredential as AIOClientSecretCredential,
)
async_credential = AIOClientSecretCredential(
tenant_id=self.tenant_id,
client_id=self.client_id,
client_secret=self.client_secret,
)
sync_credential = ClientSecretCredential(
tenant_id=self.tenant_id,
client_id=self.client_id,
client_secret=self.client_secret,
)
return (async_credential, sync_credential)
def _get_default_azure_credential(self, **kwargs):
"""
Create a Credential for authentication using DefaultAzureCredential
Returns
-------
Tuple of (Async Credential, Sync Credential).
"""
from azure.identity import DefaultAzureCredential
from azure.identity.aio import (
DefaultAzureCredential as AIODefaultAzureCredential,
)
async_credential = AIODefaultAzureCredential(**kwargs)
sync_credential = DefaultAzureCredential(**kwargs)
return (async_credential, sync_credential)
def do_connect(self):
"""Connect to the BlobServiceClient, using user-specified connection details.
Tries credentials first, then connection string and finally account key
Raises
------
ValueError if none of the connection details are available
"""
try:
if self.connection_string is not None:
self.service_client = AIOBlobServiceClient.from_connection_string(
conn_str=self.connection_string
)
elif self.account_name is not None:
if hasattr(self, "account_host"):
self.account_url: str = f"https://{self.account_host}"
else:
self.account_url: str = (
f"https://{self.account_name}.blob.core.windows.net"
)
creds = [self.credential, self.account_key]
if any(creds):
self.service_client = [
AIOBlobServiceClient(
account_url=self.account_url,
credential=cred,
_location_mode=self.location_mode,
)
for cred in creds
if cred is not None
][0]
elif self.sas_token is not None:
if not self.sas_token.startswith("?"):
self.sas_token = f"?{self.sas_token}"
self.service_client = AIOBlobServiceClient(
account_url=self.account_url + self.sas_token,
credential=None,
_location_mode=self.location_mode,
)
else:
# Fall back to anonymous login, and assume public container
self.service_client = AIOBlobServiceClient(
account_url=self.account_url
)
else:
raise ValueError(
"Must provide either a connection_string or account_name with credentials!!"
)
except RuntimeError:
loop = get_loop()
asyncio.set_event_loop(loop)
self.do_connect()
except Exception as e:
raise ValueError(f"unable to connect to account for {e}") from e
def split_path(
self, path, delimiter="/", return_container: bool = False, **kwargs
) -> Tuple[str, str, Optional[str]]:
"""
Normalize ABFS path string into bucket and key.
Parameters
----------
path : string
Input path, like `abfs://my_container/path/to/file`
delimiter: string
Delimiter used to split the path
return_container: bool
Examples
--------
>>> split_path("abfs://my_container/path/to/file")
['my_container', 'path/to/file']
>>> split_path("abfs://my_container/path/to/versioned_file?versionid=some_version_id")
['my_container', 'path/to/versioned_file', 'some_version_id']
"""
if path in ["", delimiter]:
return "", "", None
path = self._strip_protocol(path)
path = path.lstrip(delimiter)
if "/" not in path:
# this means path is the container_name
return path, "", None
container, keypart = path.split(delimiter, 1)
key, _, version_id = keypart.partition("?versionid=")
return (
container,
key,
version_id if self.version_aware and version_id else None,
)
def modified(self, path: str) -> datetime:
return self.info(path)["last_modified"]
def created(self, path: str) -> datetime:
return self.info(path)["creation_time"]
async def _info(self, path, refresh=False, **kwargs):
"""Give details of entry at path
Returns a single dictionary, with exactly the same information as ``ls``
would with ``detail=True``.
The default implementation should calls ls and could be overridden by a
shortcut. kwargs are passed on to ```ls()``.
Some file systems might not be able to measure the file's size, in
which case, the returned dict will include ``'size': None``.
Returns
-------
dict with keys: name (full path in the FS), size (in bytes), type (file,
directory, or something else) and other FS-specific keys.
"""
container, path, path_version_id = self.split_path(path)
fullpath = "/".join([container, path]) if path else container
version_id = _coalesce_version_id(path_version_id, kwargs.get("version_id"))
kwargs["version_id"] = version_id
if fullpath == "":
return {"name": "", "size": None, "type": "directory"}
elif path == "":
if not refresh and _ROOT_PATH in self.dircache:
out = [o for o in self.dircache[_ROOT_PATH] if o["name"] == container]
if out:
return out[0]
try:
async with self.service_client.get_container_client(
container=container
) as cc:
properties = await cc.get_container_properties()
except ResourceNotFoundError as exc:
raise FileNotFoundError(
errno.ENOENT, "No such container", container
) from exc
info = (await self._details([properties]))[0]
# Make result consistent with _ls_containers()
if not info.get("metadata"):
info["metadata"] = None
return info
if not refresh:
out = self._ls_from_cache(fullpath)
if out is not None:
if self.version_aware and version_id is not None:
out = [
o
for o in out
if o["name"] == fullpath and match_blob_version(o, version_id)
]
if out:
return out[0]
else:
out = [o for o in out if o["name"] == fullpath]
if out:
return out[0]
return {"name": fullpath, "size": None, "type": "directory"}
try:
async with self.service_client.get_blob_client(container, path) as bc:
props = await bc.get_blob_properties(version_id=version_id)
return (await self._details([props]))[0]
except ResourceNotFoundError:
pass
if not version_id:
if await self._dir_exists(container, path):
return {"name": fullpath, "size": None, "type": "directory"}
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), fullpath)
async def _ls_containers(self, return_glob: bool = False):
if _ROOT_PATH not in self.dircache or return_glob:
# This is the case where only the containers are being returned
logger.info(
"Returning a list of containers in the azure blob storage account"
)
contents = self.service_client.list_containers(include_metadata=True)
containers = [c async for c in contents]
files = await self._details(containers)
self.dircache[_ROOT_PATH] = files
return self.dircache[_ROOT_PATH]
async def _ls_blobs(
self,
target_path: str,
container: str,
path: str,
delimiter: str = "/",
return_glob: bool = False,
version_id: Optional[str] = None,
versions: bool = False,
**kwargs,
):
if (version_id or versions) and not self.version_aware:
raise ValueError(
"version_id/versions cannot be specified if the filesystem "
"is not version aware"
)
if (
target_path in self.dircache
and not return_glob
and not versions
and all(
match_blob_version(b, version_id) for b in self.dircache[target_path]
)
):
return self.dircache[target_path]
assert container not in ["", delimiter]
async with self.service_client.get_container_client(container=container) as cc:
path = path.strip("/")
include = ["metadata"]
if version_id is not None or versions:
assert self.version_aware
include.append("versions")
blobs = cc.walk_blobs(include=include, name_starts_with=path)
# Check the depth that needs to be screened
depth = target_path.count("/")
outblobs = []
try:
async for next_blob in blobs:
if depth in [0, 1] and path == "":
outblobs.append(next_blob)
elif isinstance(next_blob, BlobProperties):
if next_blob["name"].count("/") == depth:
outblobs.append(next_blob)
elif not next_blob["name"].endswith("/") and (
next_blob["name"].count("/") == (depth - 1)
):
outblobs.append(next_blob)
else:
async for blob_ in next_blob:
if isinstance(blob_, BlobProperties) or isinstance(
blob_, BlobPrefix
):
if blob_["name"].endswith("/"):
if blob_["name"].rstrip("/").count("/") == depth:
outblobs.append(blob_)
elif blob_["name"].count("/") == depth and (
hasattr(blob_, "size") and blob_["size"] == 0
):
outblobs.append(blob_)
else:
pass
elif blob_["name"].count("/") == (depth):
outblobs.append(blob_)
else:
pass
except ResourceNotFoundError:
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), target_path
)
finalblobs = await self._details(
outblobs,
target_path=target_path,
return_glob=return_glob,
version_id=version_id,
versions=versions,
)
if return_glob:
return finalblobs
if not finalblobs:
if not await self._exists(target_path):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), target_path
)
return []
if not self.version_aware or finalblobs[0].get("is_current_version"):
self.dircache[target_path] = finalblobs
return finalblobs
async def _ls(
self,
path: str,
detail: bool = False,
invalidate_cache: bool = False,
delimiter: str = "/",
return_glob: bool = False,
version_id: Optional[str] = None,
versions: bool = False,
**kwargs,
):
"""
Create a list of blob names from a blob container
Parameters
----------
path: str
Path to an Azure Blob with its container name
detail: bool
If False, return a list of blob names, else a list of dictionaries with blob details
invalidate_cache: bool
If True, do not use the cache
delimiter: str
Delimiter used to split paths
version_id: str
Specific blob version to list
versions: bool
If True, list all versions
return_glob: bool
"""
logger.debug("abfs.ls() is searching for %s", path)
target_path = self._strip_protocol(path).strip("/")
container, path, path_version_id = self.split_path(path)
version_id = _coalesce_version_id(version_id, path_version_id)
if invalidate_cache:
self.dircache.clear()
if (container in ["", ".", "*", delimiter]) and (path in ["", delimiter]):
output = await self._ls_containers(return_glob=return_glob)
else:
output = await self._ls_blobs(
target_path,
container,
path,
delimiter=delimiter,
return_glob=return_glob,
version_id=version_id,
versions=versions,
)
if versions:
for entry in output:
entry_version_id = entry.get("version_id")
if entry_version_id:
entry["name"] += f"?versionid={entry_version_id}"
if detail:
return output
return list(sorted(set([o["name"] for o in output])))
async def _details(
self,
contents,
delimiter="/",
return_glob: bool = False,
target_path="",
version_id: Optional[str] = None,
versions: bool = False,
**kwargs,
):
"""
Return a list of dictionaries of specifying details about the contents
Parameters
----------
contents
delimiter: str
Delimiter used to separate containers and files
return_glob: bool
version_id: str
Specific target version to be returned
versions: bool
If True, return all versions
Returns
-------
List of dicts
Returns details about the contents, such as name, size and type
"""
output = []
for content in contents:
data = {
key: content[key]
for key in FORWARDED_BLOB_PROPERTIES
if content.has_key(key) # NOQA
}
if self.version_aware:
data.update(
(key, content[key])
for key in VERSIONED_BLOB_PROPERTIES
if content.has_key(key) # NOQA
)
if content.has_key("container"): # NOQA
fname = f"{content.container}{delimiter}{content.name}"
fname = fname.rstrip(delimiter)
if content.has_key("size"): # NOQA
data["name"] = fname
data["size"] = content.size
data["type"] = "file"
else:
data["name"] = fname
data["size"] = None
data["type"] = "directory"
else:
fname = f"{content.name}"
data["name"] = fname
data["size"] = None
data["type"] = "directory"
if data.get("metadata"):
if data["metadata"].get("is_directory") == "true":
data["type"] = "directory"
data["size"] = None
elif data["metadata"].get("is_directory") == "false":
data["type"] = "file"
elif (
# In some cases Hdi_isfolder is capitalized, see #440
data["metadata"].get("hdi_isfolder") == "true"
or data["metadata"].get("Hdi_isfolder") == "true"
):
data["type"] = "directory"
data["size"] = None
if return_glob:
data["name"] = data["name"].rstrip("/")
output.append(data)
if target_path:
if (
len(output) == 1
and output[0]["type"] == "file"
and not self.version_aware
):
# This handles the case where path is a file passed to ls
return output
output = await filter_blobs(
output,
target_path,
delimiter,
version_id=version_id,
versions=versions,
)
return output
async def _find(self, path, withdirs=False, prefix="", **kwargs):
"""List all files below path.
Like posix ``find`` command without conditions.
Parameters
----------
path : str
The path (directory) to list from
withdirs: bool
Whether to include directory paths in the output. This is True
when used by glob, but users usually only want files.
prefix: str
Only return files that match `^{path}/{prefix}`
kwargs are passed to ``ls``.
"""
full_path = self._strip_protocol(path)
full_path = full_path.strip("/")
if await self._isfile(full_path):
return [full_path]
if prefix != "":
prefix = prefix.strip("/")
target_path = f"{full_path}/{prefix}"
else:
target_path = f"{full_path}/"
container, path, _ = self.split_path(target_path)
async with self.service_client.get_container_client(
container=container
) as container_client:
blobs = container_client.list_blobs(
include=["metadata"], name_starts_with=path
)
files = {}
dir_set = set()
dirs = {}
detail = kwargs.pop("detail", False)
try:
infos = await self._details([b async for b in blobs])
except ResourceNotFoundError:
# find doesn't raise but returns [] or {} instead
infos = []
for info in infos:
name = _name = info["name"]
while True:
parent_dir = self._parent(_name).rstrip("/")
if parent_dir not in dir_set and parent_dir != full_path.strip("/"):
dir_set.add(parent_dir)
dirs[parent_dir] = {
"name": parent_dir,
"type": "directory",
"size": 0,
}
_name = parent_dir.rstrip("/")
else:
break
if info["type"] == "directory":
dirs[name] = info
if info["type"] == "file":
files[name] = info
if not infos:
try:
file = await self._info(full_path)
except FileNotFoundError:
pass
else:
files[file["name"]] = file
if withdirs:
files.update(dirs)
files = {k: v for k, v in files.items() if k.startswith(target_path)}
names = sorted([n for n in files.keys()])
if not detail:
return names
return {name: files[name] for name in names}
def _walk(self, path, dirs, files):
for p, d, f in zip([path], [dirs], [files]):
yield p, d, f
async def _async_walk(self, path: str, maxdepth=None, **kwargs):
"""Return all files belows path
List all files, recursing into subdirectories; output is iterator-style,