dbfs.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. from __future__ import annotations
  2. import base64
  3. import urllib
  4. import requests
  5. from requests.adapters import HTTPAdapter, Retry
  6. from typing_extensions import override
  7. from fsspec import AbstractFileSystem
  8. from fsspec.spec import AbstractBufferedFile
  9. class DatabricksException(Exception):
  10. """
  11. Helper class for exceptions raised in this module.
  12. """
  13. def __init__(self, error_code, message, details=None):
  14. """Create a new DatabricksException"""
  15. super().__init__(message)
  16. self.error_code = error_code
  17. self.message = message
  18. self.details = details
  19. class DatabricksFileSystem(AbstractFileSystem):
  20. """
  21. Get access to the Databricks filesystem implementation over HTTP.
  22. Can be used inside and outside of a databricks cluster.
  23. """
  24. def __init__(self, instance, token, **kwargs):
  25. """
  26. Create a new DatabricksFileSystem.
  27. Parameters
  28. ----------
  29. instance: str
  30. The instance URL of the databricks cluster.
  31. For example for an Azure databricks cluster, this
  32. has the form adb-<some-number>.<two digits>.azuredatabricks.net.
  33. token: str
  34. Your personal token. Find out more
  35. here: https://docs.databricks.com/dev-tools/api/latest/authentication.html
  36. """
  37. self.instance = instance
  38. self.token = token
  39. self.session = requests.Session()
  40. self.retries = Retry(
  41. total=10,
  42. backoff_factor=0.05,
  43. status_forcelist=[408, 429, 500, 502, 503, 504],
  44. )
  45. self.session.mount("https://", HTTPAdapter(max_retries=self.retries))
  46. self.session.headers.update({"Authorization": f"Bearer {self.token}"})
  47. super().__init__(**kwargs)
  48. @override
  49. def _ls_from_cache(self, path) -> list[dict[str, str | int]] | None:
  50. """Check cache for listing
  51. Returns listing, if found (may be empty list for a directory that
  52. exists but contains nothing), None if not in cache.
  53. """
  54. self.dircache.pop(path.rstrip("/"), None)
  55. parent = self._parent(path)
  56. if parent in self.dircache:
  57. for entry in self.dircache[parent]:
  58. if entry["name"] == path.rstrip("/"):
  59. if entry["type"] != "directory":
  60. return [entry]
  61. return []
  62. raise FileNotFoundError(path)
  63. def ls(self, path, detail=True, **kwargs):
  64. """
  65. List the contents of the given path.
  66. Parameters
  67. ----------
  68. path: str
  69. Absolute path
  70. detail: bool
  71. Return not only the list of filenames,
  72. but also additional information on file sizes
  73. and types.
  74. """
  75. try:
  76. out = self._ls_from_cache(path)
  77. except FileNotFoundError:
  78. # This happens if the `path`'s parent was cached, but `path` is not
  79. # there. This suggests that `path` is new since the parent was
  80. # cached. Attempt to invalidate parent's cache before continuing.
  81. self.dircache.pop(self._parent(path), None)
  82. out = None
  83. if not out:
  84. try:
  85. r = self._send_to_api(
  86. method="get", endpoint="list", json={"path": path}
  87. )
  88. except DatabricksException as e:
  89. if e.error_code == "RESOURCE_DOES_NOT_EXIST":
  90. raise FileNotFoundError(e.message) from e
  91. raise
  92. files = r.get("files", [])
  93. out = [
  94. {
  95. "name": o["path"],
  96. "type": "directory" if o["is_dir"] else "file",
  97. "size": o["file_size"],
  98. }
  99. for o in files
  100. ]
  101. self.dircache[path] = out
  102. if detail:
  103. return out
  104. return [o["name"] for o in out]
  105. def makedirs(self, path, exist_ok=True):
  106. """
  107. Create a given absolute path and all of its parents.
  108. Parameters
  109. ----------
  110. path: str
  111. Absolute path to create
  112. exist_ok: bool
  113. If false, checks if the folder
  114. exists before creating it (and raises an
  115. Exception if this is the case)
  116. """
  117. if not exist_ok:
  118. try:
  119. # If the following succeeds, the path is already present
  120. self._send_to_api(
  121. method="get", endpoint="get-status", json={"path": path}
  122. )
  123. raise FileExistsError(f"Path {path} already exists")
  124. except DatabricksException as e:
  125. if e.error_code == "RESOURCE_DOES_NOT_EXIST":
  126. pass
  127. try:
  128. self._send_to_api(method="post", endpoint="mkdirs", json={"path": path})
  129. except DatabricksException as e:
  130. if e.error_code == "RESOURCE_ALREADY_EXISTS":
  131. raise FileExistsError(e.message) from e
  132. raise
  133. self.invalidate_cache(self._parent(path))
  134. def mkdir(self, path, create_parents=True, **kwargs):
  135. """
  136. Create a given absolute path and all of its parents.
  137. Parameters
  138. ----------
  139. path: str
  140. Absolute path to create
  141. create_parents: bool
  142. Whether to create all parents or not.
  143. "False" is not implemented so far.
  144. """
  145. if not create_parents:
  146. raise NotImplementedError
  147. self.mkdirs(path, **kwargs)
  148. def rm(self, path, recursive=False, **kwargs):
  149. """
  150. Remove the file or folder at the given absolute path.
  151. Parameters
  152. ----------
  153. path: str
  154. Absolute path what to remove
  155. recursive: bool
  156. Recursively delete all files in a folder.
  157. """
  158. try:
  159. self._send_to_api(
  160. method="post",
  161. endpoint="delete",
  162. json={"path": path, "recursive": recursive},
  163. )
  164. except DatabricksException as e:
  165. # This is not really an exception, it just means
  166. # not everything was deleted so far
  167. if e.error_code == "PARTIAL_DELETE":
  168. self.rm(path=path, recursive=recursive)
  169. elif e.error_code == "IO_ERROR":
  170. # Using the same exception as the os module would use here
  171. raise OSError(e.message) from e
  172. raise
  173. self.invalidate_cache(self._parent(path))
  174. def mv(
  175. self, source_path, destination_path, recursive=False, maxdepth=None, **kwargs
  176. ):
  177. """
  178. Move a source to a destination path.
  179. A note from the original [databricks API manual]
  180. (https://docs.databricks.com/dev-tools/api/latest/dbfs.html#move).
  181. When moving a large number of files the API call will time out after
  182. approximately 60s, potentially resulting in partially moved data.
  183. Therefore, for operations that move more than 10k files, we strongly
  184. discourage using the DBFS REST API.
  185. Parameters
  186. ----------
  187. source_path: str
  188. From where to move (absolute path)
  189. destination_path: str
  190. To where to move (absolute path)
  191. recursive: bool
  192. Not implemented to far.
  193. maxdepth:
  194. Not implemented to far.
  195. """
  196. if recursive:
  197. raise NotImplementedError
  198. if maxdepth:
  199. raise NotImplementedError
  200. try:
  201. self._send_to_api(
  202. method="post",
  203. endpoint="move",
  204. json={"source_path": source_path, "destination_path": destination_path},
  205. )
  206. except DatabricksException as e:
  207. if e.error_code == "RESOURCE_DOES_NOT_EXIST":
  208. raise FileNotFoundError(e.message) from e
  209. elif e.error_code == "RESOURCE_ALREADY_EXISTS":
  210. raise FileExistsError(e.message) from e
  211. raise
  212. self.invalidate_cache(self._parent(source_path))
  213. self.invalidate_cache(self._parent(destination_path))
  214. def _open(self, path, mode="rb", block_size="default", **kwargs):
  215. """
  216. Overwrite the base class method to make sure to create a DBFile.
  217. All arguments are copied from the base method.
  218. Only the default blocksize is allowed.
  219. """
  220. return DatabricksFile(self, path, mode=mode, block_size=block_size, **kwargs)
  221. def _send_to_api(self, method, endpoint, json):
  222. """
  223. Send the given json to the DBFS API
  224. using a get or post request (specified by the argument `method`).
  225. Parameters
  226. ----------
  227. method: str
  228. Which http method to use for communication; "get" or "post".
  229. endpoint: str
  230. Where to send the request to (last part of the API URL)
  231. json: dict
  232. Dictionary of information to send
  233. """
  234. if method == "post":
  235. session_call = self.session.post
  236. elif method == "get":
  237. session_call = self.session.get
  238. else:
  239. raise ValueError(f"Do not understand method {method}")
  240. url = urllib.parse.urljoin(f"https://{self.instance}/api/2.0/dbfs/", endpoint)
  241. r = session_call(url, json=json)
  242. # The DBFS API will return a json, also in case of an exception.
  243. # We want to preserve this information as good as possible.
  244. try:
  245. r.raise_for_status()
  246. except requests.HTTPError as e:
  247. # try to extract json error message
  248. # if that fails, fall back to the original exception
  249. try:
  250. exception_json = e.response.json()
  251. except Exception:
  252. raise e from None
  253. raise DatabricksException(**exception_json) from e
  254. return r.json()
  255. def _create_handle(self, path, overwrite=True):
  256. """
  257. Internal function to create a handle, which can be used to
  258. write blocks of a file to DBFS.
  259. A handle has a unique identifier which needs to be passed
  260. whenever written during this transaction.
  261. The handle is active for 10 minutes - after that a new
  262. write transaction needs to be created.
  263. Make sure to close the handle after you are finished.
  264. Parameters
  265. ----------
  266. path: str
  267. Absolute path for this file.
  268. overwrite: bool
  269. If a file already exist at this location, either overwrite
  270. it or raise an exception.
  271. """
  272. try:
  273. r = self._send_to_api(
  274. method="post",
  275. endpoint="create",
  276. json={"path": path, "overwrite": overwrite},
  277. )
  278. return r["handle"]
  279. except DatabricksException as e:
  280. if e.error_code == "RESOURCE_ALREADY_EXISTS":
  281. raise FileExistsError(e.message) from e
  282. raise
  283. def _close_handle(self, handle):
  284. """
  285. Close a handle, which was opened by :func:`_create_handle`.
  286. Parameters
  287. ----------
  288. handle: str
  289. Which handle to close.
  290. """
  291. try:
  292. self._send_to_api(method="post", endpoint="close", json={"handle": handle})
  293. except DatabricksException as e:
  294. if e.error_code == "RESOURCE_DOES_NOT_EXIST":
  295. raise FileNotFoundError(e.message) from e
  296. raise
  297. def _add_data(self, handle, data):
  298. """
  299. Upload data to an already opened file handle
  300. (opened by :func:`_create_handle`).
  301. The maximal allowed data size is 1MB after
  302. conversion to base64.
  303. Remember to close the handle when you are finished.
  304. Parameters
  305. ----------
  306. handle: str
  307. Which handle to upload data to.
  308. data: bytes
  309. Block of data to add to the handle.
  310. """
  311. data = base64.b64encode(data).decode()
  312. try:
  313. self._send_to_api(
  314. method="post",
  315. endpoint="add-block",
  316. json={"handle": handle, "data": data},
  317. )
  318. except DatabricksException as e:
  319. if e.error_code == "RESOURCE_DOES_NOT_EXIST":
  320. raise FileNotFoundError(e.message) from e
  321. elif e.error_code == "MAX_BLOCK_SIZE_EXCEEDED":
  322. raise ValueError(e.message) from e
  323. raise
  324. def _get_data(self, path, start, end):
  325. """
  326. Download data in bytes from a given absolute path in a block
  327. from [start, start+length].
  328. The maximum number of allowed bytes to read is 1MB.
  329. Parameters
  330. ----------
  331. path: str
  332. Absolute path to download data from
  333. start: int
  334. Start position of the block
  335. end: int
  336. End position of the block
  337. """
  338. try:
  339. r = self._send_to_api(
  340. method="get",
  341. endpoint="read",
  342. json={"path": path, "offset": start, "length": end - start},
  343. )
  344. return base64.b64decode(r["data"])
  345. except DatabricksException as e:
  346. if e.error_code == "RESOURCE_DOES_NOT_EXIST":
  347. raise FileNotFoundError(e.message) from e
  348. elif e.error_code in ["INVALID_PARAMETER_VALUE", "MAX_READ_SIZE_EXCEEDED"]:
  349. raise ValueError(e.message) from e
  350. raise
  351. def invalidate_cache(self, path=None):
  352. if path is None:
  353. self.dircache.clear()
  354. else:
  355. self.dircache.pop(path, None)
  356. super().invalidate_cache(path)
  357. class DatabricksFile(AbstractBufferedFile):
  358. """
  359. Helper class for files referenced in the DatabricksFileSystem.
  360. """
  361. DEFAULT_BLOCK_SIZE = 1 * 2**20 # only allowed block size
  362. def __init__(
  363. self,
  364. fs,
  365. path,
  366. mode="rb",
  367. block_size="default",
  368. autocommit=True,
  369. cache_type="readahead",
  370. cache_options=None,
  371. **kwargs,
  372. ):
  373. """
  374. Create a new instance of the DatabricksFile.
  375. The blocksize needs to be the default one.
  376. """
  377. if block_size is None or block_size == "default":
  378. block_size = self.DEFAULT_BLOCK_SIZE
  379. assert block_size == self.DEFAULT_BLOCK_SIZE, (
  380. f"Only the default block size is allowed, not {block_size}"
  381. )
  382. super().__init__(
  383. fs,
  384. path,
  385. mode=mode,
  386. block_size=block_size,
  387. autocommit=autocommit,
  388. cache_type=cache_type,
  389. cache_options=cache_options or {},
  390. **kwargs,
  391. )
  392. def _initiate_upload(self):
  393. """Internal function to start a file upload"""
  394. self.handle = self.fs._create_handle(self.path)
  395. def _upload_chunk(self, final=False):
  396. """Internal function to add a chunk of data to a started upload"""
  397. self.buffer.seek(0)
  398. data = self.buffer.getvalue()
  399. data_chunks = [
  400. data[start:end] for start, end in self._to_sized_blocks(len(data))
  401. ]
  402. for data_chunk in data_chunks:
  403. self.fs._add_data(handle=self.handle, data=data_chunk)
  404. if final:
  405. self.fs._close_handle(handle=self.handle)
  406. return True
  407. def _fetch_range(self, start, end):
  408. """Internal function to download a block of data"""
  409. return_buffer = b""
  410. length = end - start
  411. for chunk_start, chunk_end in self._to_sized_blocks(length, start):
  412. return_buffer += self.fs._get_data(
  413. path=self.path, start=chunk_start, end=chunk_end
  414. )
  415. return return_buffer
  416. def _to_sized_blocks(self, length, start=0):
  417. """Helper function to split a range from 0 to total_length into blocksizes"""
  418. end = start + length
  419. for data_chunk in range(start, end, self.blocksize):
  420. data_start = data_chunk
  421. data_end = min(end, data_chunk + self.blocksize)
  422. yield data_start, data_end