registry.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. from __future__ import annotations
  2. import importlib
  3. import types
  4. import warnings
  5. __all__ = ["registry", "get_filesystem_class", "default"]
  6. # internal, mutable
  7. _registry: dict[str, type] = {}
  8. # external, immutable
  9. registry = types.MappingProxyType(_registry)
  10. default = "file"
  11. def register_implementation(name, cls, clobber=False, errtxt=None):
  12. """Add implementation class to the registry
  13. Parameters
  14. ----------
  15. name: str
  16. Protocol name to associate with the class
  17. cls: class or str
  18. if a class: fsspec-compliant implementation class (normally inherits from
  19. ``fsspec.AbstractFileSystem``, gets added straight to the registry. If a
  20. str, the full path to an implementation class like package.module.class,
  21. which gets added to known_implementations,
  22. so the import is deferred until the filesystem is actually used.
  23. clobber: bool (optional)
  24. Whether to overwrite a protocol with the same name; if False, will raise
  25. instead.
  26. errtxt: str (optional)
  27. If given, then a failure to import the given class will result in this
  28. text being given.
  29. """
  30. if isinstance(cls, str):
  31. if name in known_implementations and clobber is False:
  32. if cls != known_implementations[name]["class"]:
  33. raise ValueError(
  34. f"Name ({name}) already in the known_implementations and clobber "
  35. f"is False"
  36. )
  37. else:
  38. known_implementations[name] = {
  39. "class": cls,
  40. "err": errtxt or f"{cls} import failed for protocol {name}",
  41. }
  42. else:
  43. if name in registry and clobber is False:
  44. if _registry[name] is not cls:
  45. raise ValueError(
  46. f"Name ({name}) already in the registry and clobber is False"
  47. )
  48. else:
  49. _registry[name] = cls
  50. # protocols mapped to the class which implements them. This dict can be
  51. # updated with register_implementation
  52. known_implementations = {
  53. "abfs": {
  54. "class": "adlfs.AzureBlobFileSystem",
  55. "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage",
  56. },
  57. "adl": {
  58. "class": "adlfs.AzureDatalakeFileSystem",
  59. "err": "Install adlfs to access Azure Datalake Gen1",
  60. },
  61. "arrow_hdfs": {
  62. "class": "fsspec.implementations.arrow.HadoopFileSystem",
  63. "err": "pyarrow and local java libraries required for HDFS",
  64. },
  65. "async_wrapper": {
  66. "class": "fsspec.asyn_wrapper.AsyncWrapperFileSystem",
  67. },
  68. "asynclocal": {
  69. "class": "morefs.asyn_local.AsyncLocalFileSystem",
  70. "err": "Install 'morefs[asynclocalfs]' to use AsyncLocalFileSystem",
  71. },
  72. "az": {
  73. "class": "adlfs.AzureBlobFileSystem",
  74. "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage",
  75. },
  76. "blockcache": {"class": "fsspec.implementations.cached.CachingFileSystem"},
  77. "box": {
  78. "class": "boxfs.BoxFileSystem",
  79. "err": "Please install boxfs to access BoxFileSystem",
  80. },
  81. "cached": {"class": "fsspec.implementations.cached.CachingFileSystem"},
  82. "dask": {
  83. "class": "fsspec.implementations.dask.DaskWorkerFileSystem",
  84. "err": "Install dask distributed to access worker file system",
  85. },
  86. "data": {"class": "fsspec.implementations.data.DataFileSystem"},
  87. "dbfs": {
  88. "class": "fsspec.implementations.dbfs.DatabricksFileSystem",
  89. "err": "Install the requests package to use the DatabricksFileSystem",
  90. },
  91. "dir": {"class": "fsspec.implementations.dirfs.DirFileSystem"},
  92. "dropbox": {
  93. "class": "dropboxdrivefs.DropboxDriveFileSystem",
  94. "err": (
  95. 'DropboxFileSystem requires "dropboxdrivefs","requests" and "'
  96. '"dropbox" to be installed'
  97. ),
  98. },
  99. "dvc": {
  100. "class": "dvc.api.DVCFileSystem",
  101. "err": "Install dvc to access DVCFileSystem",
  102. },
  103. "file": {"class": "fsspec.implementations.local.LocalFileSystem"},
  104. "filecache": {"class": "fsspec.implementations.cached.WholeFileCacheFileSystem"},
  105. "ftp": {"class": "fsspec.implementations.ftp.FTPFileSystem"},
  106. "gcs": {
  107. "class": "gcsfs.GCSFileSystem",
  108. "err": "Please install gcsfs to access Google Storage",
  109. },
  110. "gdrive": {
  111. "class": "gdrivefs.GoogleDriveFileSystem",
  112. "err": "Please install gdrivefs for access to Google Drive",
  113. },
  114. "generic": {"class": "fsspec.generic.GenericFileSystem"},
  115. "git": {
  116. "class": "fsspec.implementations.git.GitFileSystem",
  117. "err": "Install pygit2 to browse local git repos",
  118. },
  119. "github": {
  120. "class": "fsspec.implementations.github.GithubFileSystem",
  121. "err": "Install the requests package to use the github FS",
  122. },
  123. "gs": {
  124. "class": "gcsfs.GCSFileSystem",
  125. "err": "Please install gcsfs to access Google Storage",
  126. },
  127. "hdfs": {
  128. "class": "fsspec.implementations.arrow.HadoopFileSystem",
  129. "err": "pyarrow and local java libraries required for HDFS",
  130. },
  131. "hf": {
  132. "class": "huggingface_hub.HfFileSystem",
  133. "err": "Install huggingface_hub to access HfFileSystem",
  134. },
  135. "http": {
  136. "class": "fsspec.implementations.http.HTTPFileSystem",
  137. "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed',
  138. },
  139. "https": {
  140. "class": "fsspec.implementations.http.HTTPFileSystem",
  141. "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed',
  142. },
  143. "jlab": {
  144. "class": "fsspec.implementations.jupyter.JupyterFileSystem",
  145. "err": "Jupyter FS requires requests to be installed",
  146. },
  147. "jupyter": {
  148. "class": "fsspec.implementations.jupyter.JupyterFileSystem",
  149. "err": "Jupyter FS requires requests to be installed",
  150. },
  151. "lakefs": {
  152. "class": "lakefs_spec.LakeFSFileSystem",
  153. "err": "Please install lakefs-spec to access LakeFSFileSystem",
  154. },
  155. "libarchive": {
  156. "class": "fsspec.implementations.libarchive.LibArchiveFileSystem",
  157. "err": "LibArchive requires to be installed",
  158. },
  159. "local": {"class": "fsspec.implementations.local.LocalFileSystem"},
  160. "memory": {"class": "fsspec.implementations.memory.MemoryFileSystem"},
  161. "oci": {
  162. "class": "ocifs.OCIFileSystem",
  163. "err": "Install ocifs to access OCI Object Storage",
  164. },
  165. "ocilake": {
  166. "class": "ocifs.OCIFileSystem",
  167. "err": "Install ocifs to access OCI Data Lake",
  168. },
  169. "oss": {
  170. "class": "ossfs.OSSFileSystem",
  171. "err": "Install ossfs to access Alibaba Object Storage System",
  172. },
  173. "reference": {"class": "fsspec.implementations.reference.ReferenceFileSystem"},
  174. "root": {
  175. "class": "fsspec_xrootd.XRootDFileSystem",
  176. "err": (
  177. "Install fsspec-xrootd to access xrootd storage system. "
  178. "Note: 'root' is the protocol name for xrootd storage systems, "
  179. "not referring to root directories"
  180. ),
  181. },
  182. "s3": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"},
  183. "s3a": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"},
  184. "sftp": {
  185. "class": "fsspec.implementations.sftp.SFTPFileSystem",
  186. "err": 'SFTPFileSystem requires "paramiko" to be installed',
  187. },
  188. "simplecache": {"class": "fsspec.implementations.cached.SimpleCacheFileSystem"},
  189. "smb": {
  190. "class": "fsspec.implementations.smb.SMBFileSystem",
  191. "err": 'SMB requires "smbprotocol" or "smbprotocol[kerberos]" installed',
  192. },
  193. "ssh": {
  194. "class": "fsspec.implementations.sftp.SFTPFileSystem",
  195. "err": 'SFTPFileSystem requires "paramiko" to be installed',
  196. },
  197. "tar": {"class": "fsspec.implementations.tar.TarFileSystem"},
  198. "tosfs": {
  199. "class": "tosfs.TosFileSystem",
  200. "err": "Install tosfs to access ByteDance volcano engine Tinder Object Storage",
  201. },
  202. "wandb": {"class": "wandbfs.WandbFS", "err": "Install wandbfs to access wandb"},
  203. "webdav": {
  204. "class": "webdav4.fsspec.WebdavFileSystem",
  205. "err": "Install webdav4 to access WebDAV",
  206. },
  207. "webhdfs": {
  208. "class": "fsspec.implementations.webhdfs.WebHDFS",
  209. "err": 'webHDFS access requires "requests" to be installed',
  210. },
  211. "zip": {"class": "fsspec.implementations.zip.ZipFileSystem"},
  212. }
  213. assert list(known_implementations) == sorted(known_implementations), (
  214. "Not in alphabetical order"
  215. )
  216. def get_filesystem_class(protocol):
  217. """Fetch named protocol implementation from the registry
  218. The dict ``known_implementations`` maps protocol names to the locations
  219. of classes implementing the corresponding file-system. When used for the
  220. first time, appropriate imports will happen and the class will be placed in
  221. the registry. All subsequent calls will fetch directly from the registry.
  222. Some protocol implementations require additional dependencies, and so the
  223. import may fail. In this case, the string in the "err" field of the
  224. ``known_implementations`` will be given as the error message.
  225. """
  226. if not protocol:
  227. protocol = default
  228. if protocol not in registry:
  229. if protocol not in known_implementations:
  230. raise ValueError(f"Protocol not known: {protocol}")
  231. bit = known_implementations[protocol]
  232. try:
  233. register_implementation(protocol, _import_class(bit["class"]))
  234. except ImportError as e:
  235. raise ImportError(bit.get("err")) from e
  236. cls = registry[protocol]
  237. if getattr(cls, "protocol", None) in ("abstract", None):
  238. cls.protocol = protocol
  239. return cls
  240. s3_msg = """Your installed version of s3fs is very old and known to cause
  241. severe performance issues, see also https://github.com/dask/dask/issues/10276
  242. To fix, you should specify a lower version bound on s3fs, or
  243. update the current installation.
  244. """
  245. def _import_class(fqp: str):
  246. """Take a fully-qualified path and return the imported class or identifier.
  247. ``fqp`` is of the form "package.module.klass" or
  248. "package.module:subobject.klass".
  249. Warnings
  250. --------
  251. This can import arbitrary modules. Make sure you haven't installed any modules
  252. that may execute malicious code at import time.
  253. """
  254. if ":" in fqp:
  255. mod, name = fqp.rsplit(":", 1)
  256. else:
  257. mod, name = fqp.rsplit(".", 1)
  258. is_s3 = mod == "s3fs"
  259. mod = importlib.import_module(mod)
  260. if is_s3 and mod.__version__.split(".") < ["0", "5"]:
  261. warnings.warn(s3_msg)
  262. for part in name.split("."):
  263. mod = getattr(mod, part)
  264. if not isinstance(mod, type):
  265. raise TypeError(f"{fqp} is not a class")
  266. return mod
  267. def filesystem(protocol, **storage_options):
  268. """Instantiate filesystems for given protocol and arguments
  269. ``storage_options`` are specific to the protocol being chosen, and are
  270. passed directly to the class.
  271. """
  272. if protocol == "arrow_hdfs":
  273. warnings.warn(
  274. "The 'arrow_hdfs' protocol has been deprecated and will be "
  275. "removed in the future. Specify it as 'hdfs'.",
  276. DeprecationWarning,
  277. )
  278. cls = get_filesystem_class(protocol)
  279. return cls(**storage_options)
  280. def available_protocols():
  281. """Return a list of the implemented protocols.
  282. Note that any given protocol may require extra packages to be importable.
  283. """
  284. return list(known_implementations)