asyn.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. import asyncio
  2. import asyncio.events
  3. import functools
  4. import inspect
  5. import io
  6. import numbers
  7. import os
  8. import re
  9. import threading
  10. from collections.abc import Iterable
  11. from glob import has_magic
  12. from typing import TYPE_CHECKING
  13. from .callbacks import DEFAULT_CALLBACK
  14. from .exceptions import FSTimeoutError
  15. from .implementations.local import LocalFileSystem, make_path_posix, trailing_sep
  16. from .spec import AbstractBufferedFile, AbstractFileSystem
  17. from .utils import glob_translate, is_exception, other_paths
  18. private = re.compile("_[^_]")
  19. iothread = [None] # dedicated fsspec IO thread
  20. loop = [None] # global event loop for any non-async instance
  21. _lock = None # global lock placeholder
  22. get_running_loop = asyncio.get_running_loop
  23. def get_lock():
  24. """Allocate or return a threading lock.
  25. The lock is allocated on first use to allow setting one lock per forked process.
  26. """
  27. global _lock
  28. if not _lock:
  29. _lock = threading.Lock()
  30. return _lock
  31. def reset_lock():
  32. """Reset the global lock.
  33. This should be called only on the init of a forked process to reset the lock to
  34. None, enabling the new forked process to get a new lock.
  35. """
  36. global _lock
  37. iothread[0] = None
  38. loop[0] = None
  39. _lock = None
  40. async def _runner(event, coro, result, timeout=None):
  41. timeout = timeout if timeout else None # convert 0 or 0.0 to None
  42. if timeout is not None:
  43. coro = asyncio.wait_for(coro, timeout=timeout)
  44. try:
  45. result[0] = await coro
  46. except Exception as ex:
  47. result[0] = ex
  48. finally:
  49. event.set()
  50. def sync(loop, func, *args, timeout=None, **kwargs):
  51. """
  52. Make loop run coroutine until it returns. Runs in other thread
  53. Examples
  54. --------
  55. >>> fsspec.asyn.sync(fsspec.asyn.get_loop(), func, *args,
  56. timeout=timeout, **kwargs)
  57. """
  58. timeout = timeout if timeout else None # convert 0 or 0.0 to None
  59. # NB: if the loop is not running *yet*, it is OK to submit work
  60. # and we will wait for it
  61. if loop is None or loop.is_closed():
  62. raise RuntimeError("Loop is not running")
  63. try:
  64. loop0 = asyncio.events.get_running_loop()
  65. if loop0 is loop:
  66. raise NotImplementedError("Calling sync() from within a running loop")
  67. except NotImplementedError:
  68. raise
  69. except RuntimeError:
  70. pass
  71. coro = func(*args, **kwargs)
  72. result = [None]
  73. event = threading.Event()
  74. asyncio.run_coroutine_threadsafe(_runner(event, coro, result, timeout), loop)
  75. while True:
  76. # this loops allows thread to get interrupted
  77. if event.wait(1):
  78. break
  79. if timeout is not None:
  80. timeout -= 1
  81. if timeout < 0:
  82. raise FSTimeoutError
  83. return_result = result[0]
  84. if isinstance(return_result, asyncio.TimeoutError):
  85. # suppress asyncio.TimeoutError, raise FSTimeoutError
  86. raise FSTimeoutError from return_result
  87. elif isinstance(return_result, BaseException):
  88. raise return_result
  89. else:
  90. return return_result
  91. def sync_wrapper(func, obj=None):
  92. """Given a function, make so can be called in blocking contexts
  93. Leave obj=None if defining within a class. Pass the instance if attaching
  94. as an attribute of the instance.
  95. """
  96. @functools.wraps(func)
  97. def wrapper(*args, **kwargs):
  98. self = obj or args[0]
  99. return sync(self.loop, func, *args, **kwargs)
  100. return wrapper
  101. def get_loop():
  102. """Create or return the default fsspec IO loop
  103. The loop will be running on a separate thread.
  104. """
  105. if loop[0] is None:
  106. with get_lock():
  107. # repeat the check just in case the loop got filled between the
  108. # previous two calls from another thread
  109. if loop[0] is None:
  110. loop[0] = asyncio.new_event_loop()
  111. th = threading.Thread(target=loop[0].run_forever, name="fsspecIO")
  112. th.daemon = True
  113. th.start()
  114. iothread[0] = th
  115. return loop[0]
  116. def reset_after_fork():
  117. global lock
  118. loop[0] = None
  119. iothread[0] = None
  120. lock = None
  121. if hasattr(os, "register_at_fork"):
  122. # should be posix; this will do nothing for spawn or forkserver subprocesses
  123. os.register_at_fork(after_in_child=reset_after_fork)
  124. if TYPE_CHECKING:
  125. import resource
  126. ResourceError = resource.error
  127. else:
  128. try:
  129. import resource
  130. except ImportError:
  131. resource = None
  132. ResourceError = OSError
  133. else:
  134. ResourceError = getattr(resource, "error", OSError)
  135. _DEFAULT_BATCH_SIZE = 128
  136. _NOFILES_DEFAULT_BATCH_SIZE = 1280
  137. def _get_batch_size(nofiles=False):
  138. from fsspec.config import conf
  139. if nofiles:
  140. if "nofiles_gather_batch_size" in conf:
  141. return conf["nofiles_gather_batch_size"]
  142. else:
  143. if "gather_batch_size" in conf:
  144. return conf["gather_batch_size"]
  145. if nofiles:
  146. return _NOFILES_DEFAULT_BATCH_SIZE
  147. if resource is None:
  148. return _DEFAULT_BATCH_SIZE
  149. try:
  150. soft_limit, _ = resource.getrlimit(resource.RLIMIT_NOFILE)
  151. except (ImportError, ValueError, ResourceError):
  152. return _DEFAULT_BATCH_SIZE
  153. if soft_limit == resource.RLIM_INFINITY:
  154. return -1
  155. else:
  156. return soft_limit // 8
  157. def running_async() -> bool:
  158. """Being executed by an event loop?"""
  159. try:
  160. asyncio.get_running_loop()
  161. return True
  162. except RuntimeError:
  163. return False
  164. async def _run_coros_in_chunks(
  165. coros,
  166. batch_size=None,
  167. callback=DEFAULT_CALLBACK,
  168. timeout=None,
  169. return_exceptions=False,
  170. nofiles=False,
  171. ):
  172. """Run the given coroutines in chunks.
  173. Parameters
  174. ----------
  175. coros: list of coroutines to run
  176. batch_size: int or None
  177. Number of coroutines to submit/wait on simultaneously.
  178. If -1, then it will not be any throttling. If
  179. None, it will be inferred from _get_batch_size()
  180. callback: fsspec.callbacks.Callback instance
  181. Gets a relative_update when each coroutine completes
  182. timeout: number or None
  183. If given, each coroutine times out after this time. Note that, since
  184. there are multiple batches, the total run time of this function will in
  185. general be longer
  186. return_exceptions: bool
  187. Same meaning as in asyncio.gather
  188. nofiles: bool
  189. If inferring the batch_size, does this operation involve local files?
  190. If yes, you normally expect smaller batches.
  191. """
  192. if batch_size is None:
  193. batch_size = _get_batch_size(nofiles=nofiles)
  194. if batch_size == -1:
  195. batch_size = len(coros)
  196. assert batch_size > 0
  197. async def _run_coro(coro, i):
  198. try:
  199. return await asyncio.wait_for(coro, timeout=timeout), i
  200. except Exception as e:
  201. if not return_exceptions:
  202. raise
  203. return e, i
  204. finally:
  205. callback.relative_update(1)
  206. i = 0
  207. n = len(coros)
  208. results = [None] * n
  209. pending = set()
  210. while pending or i < n:
  211. while len(pending) < batch_size and i < n:
  212. pending.add(asyncio.ensure_future(_run_coro(coros[i], i)))
  213. i += 1
  214. if not pending:
  215. break
  216. done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
  217. while done:
  218. result, k = await done.pop()
  219. results[k] = result
  220. return results
  221. # these methods should be implemented as async by any async-able backend
  222. async_methods = [
  223. "_ls",
  224. "_cat_file",
  225. "_get_file",
  226. "_put_file",
  227. "_rm_file",
  228. "_cp_file",
  229. "_pipe_file",
  230. "_expand_path",
  231. "_info",
  232. "_isfile",
  233. "_isdir",
  234. "_exists",
  235. "_walk",
  236. "_glob",
  237. "_find",
  238. "_du",
  239. "_size",
  240. "_mkdir",
  241. "_makedirs",
  242. ]
  243. class AsyncFileSystem(AbstractFileSystem):
  244. """Async file operations, default implementations
  245. Passes bulk operations to asyncio.gather for concurrent operation.
  246. Implementations that have concurrent batch operations and/or async methods
  247. should inherit from this class instead of AbstractFileSystem. Docstrings are
  248. copied from the un-underscored method in AbstractFileSystem, if not given.
  249. """
  250. # note that methods do not have docstring here; they will be copied
  251. # for _* methods and inferred for overridden methods.
  252. async_impl = True
  253. mirror_sync_methods = True
  254. disable_throttling = False
  255. def __init__(self, *args, asynchronous=False, loop=None, batch_size=None, **kwargs):
  256. self.asynchronous = asynchronous
  257. self._pid = os.getpid()
  258. if not asynchronous:
  259. self._loop = loop or get_loop()
  260. else:
  261. self._loop = None
  262. self.batch_size = batch_size
  263. super().__init__(*args, **kwargs)
  264. @property
  265. def loop(self):
  266. if self._pid != os.getpid():
  267. raise RuntimeError("This class is not fork-safe")
  268. return self._loop
  269. async def _rm_file(self, path, **kwargs):
  270. if (
  271. inspect.iscoroutinefunction(self._rm)
  272. and type(self)._rm is not AsyncFileSystem._rm
  273. ):
  274. return await self._rm(path, recursive=False, batch_size=1, **kwargs)
  275. raise NotImplementedError
  276. async def _rm(self, path, recursive=False, batch_size=None, **kwargs):
  277. # TODO: implement on_error
  278. batch_size = batch_size or self.batch_size
  279. path = await self._expand_path(path, recursive=recursive)
  280. return await _run_coros_in_chunks(
  281. [self._rm_file(p, **kwargs) for p in reversed(path)],
  282. batch_size=batch_size,
  283. nofiles=True,
  284. )
  285. async def _cp_file(self, path1, path2, **kwargs):
  286. raise NotImplementedError
  287. async def _mv_file(self, path1, path2):
  288. await self._cp_file(path1, path2)
  289. await self._rm_file(path1)
  290. async def _copy(
  291. self,
  292. path1,
  293. path2,
  294. recursive=False,
  295. on_error=None,
  296. maxdepth=None,
  297. batch_size=None,
  298. **kwargs,
  299. ):
  300. if on_error is None and recursive:
  301. on_error = "ignore"
  302. elif on_error is None:
  303. on_error = "raise"
  304. if isinstance(path1, list) and isinstance(path2, list):
  305. # No need to expand paths when both source and destination
  306. # are provided as lists
  307. paths1 = path1
  308. paths2 = path2
  309. else:
  310. source_is_str = isinstance(path1, str)
  311. paths1 = await self._expand_path(
  312. path1, maxdepth=maxdepth, recursive=recursive
  313. )
  314. if source_is_str and (not recursive or maxdepth is not None):
  315. # Non-recursive glob does not copy directories
  316. paths1 = [
  317. p for p in paths1 if not (trailing_sep(p) or await self._isdir(p))
  318. ]
  319. if not paths1:
  320. return
  321. source_is_file = len(paths1) == 1
  322. dest_is_dir = isinstance(path2, str) and (
  323. trailing_sep(path2) or await self._isdir(path2)
  324. )
  325. exists = source_is_str and (
  326. (has_magic(path1) and source_is_file)
  327. or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1))
  328. )
  329. paths2 = other_paths(
  330. paths1,
  331. path2,
  332. exists=exists,
  333. flatten=not source_is_str,
  334. )
  335. batch_size = batch_size or self.batch_size
  336. coros = [self._cp_file(p1, p2, **kwargs) for p1, p2 in zip(paths1, paths2)]
  337. result = await _run_coros_in_chunks(
  338. coros, batch_size=batch_size, return_exceptions=True, nofiles=True
  339. )
  340. for ex in filter(is_exception, result):
  341. if on_error == "ignore" and isinstance(ex, FileNotFoundError):
  342. continue
  343. raise ex
  344. async def _pipe_file(self, path, value, mode="overwrite", **kwargs):
  345. raise NotImplementedError
  346. async def _pipe(self, path, value=None, batch_size=None, **kwargs):
  347. if isinstance(path, str):
  348. path = {path: value}
  349. batch_size = batch_size or self.batch_size
  350. return await _run_coros_in_chunks(
  351. [self._pipe_file(k, v, **kwargs) for k, v in path.items()],
  352. batch_size=batch_size,
  353. nofiles=True,
  354. )
  355. async def _process_limits(self, url, start, end):
  356. """Helper for "Range"-based _cat_file"""
  357. size = None
  358. suff = False
  359. if start is not None and start < 0:
  360. # if start is negative and end None, end is the "suffix length"
  361. if end is None:
  362. end = -start
  363. start = ""
  364. suff = True
  365. else:
  366. size = size or (await self._info(url))["size"]
  367. start = size + start
  368. elif start is None:
  369. start = 0
  370. if not suff:
  371. if end is not None and end < 0:
  372. if start is not None:
  373. size = size or (await self._info(url))["size"]
  374. end = size + end
  375. elif end is None:
  376. end = ""
  377. if isinstance(end, numbers.Integral):
  378. end -= 1 # bytes range is inclusive
  379. return f"bytes={start}-{end}"
  380. async def _cat_file(self, path, start=None, end=None, **kwargs):
  381. raise NotImplementedError
  382. async def _cat(
  383. self, path, recursive=False, on_error="raise", batch_size=None, **kwargs
  384. ):
  385. paths = await self._expand_path(path, recursive=recursive)
  386. coros = [self._cat_file(path, **kwargs) for path in paths]
  387. batch_size = batch_size or self.batch_size
  388. out = await _run_coros_in_chunks(
  389. coros, batch_size=batch_size, nofiles=True, return_exceptions=True
  390. )
  391. if on_error == "raise":
  392. ex = next(filter(is_exception, out), False)
  393. if ex:
  394. raise ex
  395. if (
  396. len(paths) > 1
  397. or isinstance(path, list)
  398. or paths[0] != self._strip_protocol(path)
  399. ):
  400. return {
  401. k: v
  402. for k, v in zip(paths, out)
  403. if on_error != "omit" or not is_exception(v)
  404. }
  405. else:
  406. return out[0]
  407. async def _cat_ranges(
  408. self,
  409. paths,
  410. starts,
  411. ends,
  412. max_gap=None,
  413. batch_size=None,
  414. on_error="return",
  415. **kwargs,
  416. ):
  417. """Get the contents of byte ranges from one or more files
  418. Parameters
  419. ----------
  420. paths: list
  421. A list of of filepaths on this filesystems
  422. starts, ends: int or list
  423. Bytes limits of the read. If using a single int, the same value will be
  424. used to read all the specified files.
  425. """
  426. # TODO: on_error
  427. if max_gap is not None:
  428. # use utils.merge_offset_ranges
  429. raise NotImplementedError
  430. if not isinstance(paths, list):
  431. raise TypeError
  432. if not isinstance(starts, Iterable):
  433. starts = [starts] * len(paths)
  434. if not isinstance(ends, Iterable):
  435. ends = [ends] * len(paths)
  436. if len(starts) != len(paths) or len(ends) != len(paths):
  437. raise ValueError
  438. coros = [
  439. self._cat_file(p, start=s, end=e, **kwargs)
  440. for p, s, e in zip(paths, starts, ends)
  441. ]
  442. batch_size = batch_size or self.batch_size
  443. return await _run_coros_in_chunks(
  444. coros, batch_size=batch_size, nofiles=True, return_exceptions=True
  445. )
  446. async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs):
  447. raise NotImplementedError
  448. async def _put(
  449. self,
  450. lpath,
  451. rpath,
  452. recursive=False,
  453. callback=DEFAULT_CALLBACK,
  454. batch_size=None,
  455. maxdepth=None,
  456. **kwargs,
  457. ):
  458. """Copy file(s) from local.
  459. Copies a specific file or tree of files (if recursive=True). If rpath
  460. ends with a "/", it will be assumed to be a directory, and target files
  461. will go within.
  462. The put_file method will be called concurrently on a batch of files. The
  463. batch_size option can configure the amount of futures that can be executed
  464. at the same time. If it is -1, then all the files will be uploaded concurrently.
  465. The default can be set for this instance by passing "batch_size" in the
  466. constructor, or for all instances by setting the "gather_batch_size" key
  467. in ``fsspec.config.conf``, falling back to 1/8th of the system limit .
  468. """
  469. if isinstance(lpath, list) and isinstance(rpath, list):
  470. # No need to expand paths when both source and destination
  471. # are provided as lists
  472. rpaths = rpath
  473. lpaths = lpath
  474. else:
  475. source_is_str = isinstance(lpath, str)
  476. if source_is_str:
  477. lpath = make_path_posix(lpath)
  478. fs = LocalFileSystem()
  479. lpaths = fs.expand_path(lpath, recursive=recursive, maxdepth=maxdepth)
  480. if source_is_str and (not recursive or maxdepth is not None):
  481. # Non-recursive glob does not copy directories
  482. lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))]
  483. if not lpaths:
  484. return
  485. source_is_file = len(lpaths) == 1
  486. dest_is_dir = isinstance(rpath, str) and (
  487. trailing_sep(rpath) or await self._isdir(rpath)
  488. )
  489. rpath = self._strip_protocol(rpath)
  490. exists = source_is_str and (
  491. (has_magic(lpath) and source_is_file)
  492. or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath))
  493. )
  494. rpaths = other_paths(
  495. lpaths,
  496. rpath,
  497. exists=exists,
  498. flatten=not source_is_str,
  499. )
  500. is_dir = {l: os.path.isdir(l) for l in lpaths}
  501. rdirs = [r for l, r in zip(lpaths, rpaths) if is_dir[l]]
  502. file_pairs = [(l, r) for l, r in zip(lpaths, rpaths) if not is_dir[l]]
  503. await asyncio.gather(*[self._makedirs(d, exist_ok=True) for d in rdirs])
  504. batch_size = batch_size or self.batch_size
  505. coros = []
  506. callback.set_size(len(file_pairs))
  507. for lfile, rfile in file_pairs:
  508. put_file = callback.branch_coro(self._put_file)
  509. coros.append(put_file(lfile, rfile, **kwargs))
  510. return await _run_coros_in_chunks(
  511. coros, batch_size=batch_size, callback=callback
  512. )
  513. async def _get_file(self, rpath, lpath, **kwargs):
  514. raise NotImplementedError
  515. async def _get(
  516. self,
  517. rpath,
  518. lpath,
  519. recursive=False,
  520. callback=DEFAULT_CALLBACK,
  521. maxdepth=None,
  522. **kwargs,
  523. ):
  524. """Copy file(s) to local.
  525. Copies a specific file or tree of files (if recursive=True). If lpath
  526. ends with a "/", it will be assumed to be a directory, and target files
  527. will go within. Can submit a list of paths, which may be glob-patterns
  528. and will be expanded.
  529. The get_file method will be called concurrently on a batch of files. The
  530. batch_size option can configure the amount of futures that can be executed
  531. at the same time. If it is -1, then all the files will be uploaded concurrently.
  532. The default can be set for this instance by passing "batch_size" in the
  533. constructor, or for all instances by setting the "gather_batch_size" key
  534. in ``fsspec.config.conf``, falling back to 1/8th of the system limit .
  535. """
  536. if isinstance(lpath, list) and isinstance(rpath, list):
  537. # No need to expand paths when both source and destination
  538. # are provided as lists
  539. rpaths = rpath
  540. lpaths = lpath
  541. else:
  542. source_is_str = isinstance(rpath, str)
  543. # First check for rpath trailing slash as _strip_protocol removes it.
  544. source_not_trailing_sep = source_is_str and not trailing_sep(rpath)
  545. rpath = self._strip_protocol(rpath)
  546. rpaths = await self._expand_path(
  547. rpath, recursive=recursive, maxdepth=maxdepth
  548. )
  549. if source_is_str and (not recursive or maxdepth is not None):
  550. # Non-recursive glob does not copy directories
  551. rpaths = [
  552. p for p in rpaths if not (trailing_sep(p) or await self._isdir(p))
  553. ]
  554. if not rpaths:
  555. return
  556. lpath = make_path_posix(lpath)
  557. source_is_file = len(rpaths) == 1
  558. dest_is_dir = isinstance(lpath, str) and (
  559. trailing_sep(lpath) or LocalFileSystem().isdir(lpath)
  560. )
  561. exists = source_is_str and (
  562. (has_magic(rpath) and source_is_file)
  563. or (not has_magic(rpath) and dest_is_dir and source_not_trailing_sep)
  564. )
  565. lpaths = other_paths(
  566. rpaths,
  567. lpath,
  568. exists=exists,
  569. flatten=not source_is_str,
  570. )
  571. [os.makedirs(os.path.dirname(lp), exist_ok=True) for lp in lpaths]
  572. batch_size = kwargs.pop("batch_size", self.batch_size)
  573. coros = []
  574. callback.set_size(len(lpaths))
  575. for lpath, rpath in zip(lpaths, rpaths):
  576. get_file = callback.branch_coro(self._get_file)
  577. coros.append(get_file(rpath, lpath, **kwargs))
  578. return await _run_coros_in_chunks(
  579. coros, batch_size=batch_size, callback=callback
  580. )
  581. async def _isfile(self, path):
  582. try:
  583. return (await self._info(path))["type"] == "file"
  584. except: # noqa: E722
  585. return False
  586. async def _isdir(self, path):
  587. try:
  588. return (await self._info(path))["type"] == "directory"
  589. except OSError:
  590. return False
  591. async def _size(self, path):
  592. return (await self._info(path)).get("size", None)
  593. async def _sizes(self, paths, batch_size=None):
  594. batch_size = batch_size or self.batch_size
  595. return await _run_coros_in_chunks(
  596. [self._size(p) for p in paths], batch_size=batch_size
  597. )
  598. async def _exists(self, path, **kwargs):
  599. try:
  600. await self._info(path, **kwargs)
  601. return True
  602. except FileNotFoundError:
  603. return False
  604. async def _info(self, path, **kwargs):
  605. raise NotImplementedError
  606. async def _ls(self, path, detail=True, **kwargs):
  607. raise NotImplementedError
  608. async def _walk(self, path, maxdepth=None, on_error="omit", **kwargs):
  609. if maxdepth is not None and maxdepth < 1:
  610. raise ValueError("maxdepth must be at least 1")
  611. path = self._strip_protocol(path)
  612. full_dirs = {}
  613. dirs = {}
  614. files = {}
  615. detail = kwargs.pop("detail", False)
  616. try:
  617. listing = await self._ls(path, detail=True, **kwargs)
  618. except (FileNotFoundError, OSError) as e:
  619. if on_error == "raise":
  620. raise
  621. elif callable(on_error):
  622. on_error(e)
  623. if detail:
  624. yield path, {}, {}
  625. else:
  626. yield path, [], []
  627. return
  628. for info in listing:
  629. # each info name must be at least [path]/part , but here
  630. # we check also for names like [path]/part/
  631. pathname = info["name"].rstrip("/")
  632. name = pathname.rsplit("/", 1)[-1]
  633. if info["type"] == "directory" and pathname != path:
  634. # do not include "self" path
  635. full_dirs[name] = pathname
  636. dirs[name] = info
  637. elif pathname == path:
  638. # file-like with same name as give path
  639. files[""] = info
  640. else:
  641. files[name] = info
  642. if detail:
  643. yield path, dirs, files
  644. else:
  645. yield path, list(dirs), list(files)
  646. if maxdepth is not None:
  647. maxdepth -= 1
  648. if maxdepth < 1:
  649. return
  650. for d in dirs:
  651. async for _ in self._walk(
  652. full_dirs[d], maxdepth=maxdepth, detail=detail, **kwargs
  653. ):
  654. yield _
  655. async def _glob(self, path, maxdepth=None, **kwargs):
  656. if maxdepth is not None and maxdepth < 1:
  657. raise ValueError("maxdepth must be at least 1")
  658. import re
  659. seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,)
  660. ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash
  661. path = self._strip_protocol(path)
  662. append_slash_to_dirname = ends_with_sep or path.endswith(
  663. tuple(sep + "**" for sep in seps)
  664. )
  665. idx_star = path.find("*") if path.find("*") >= 0 else len(path)
  666. idx_qmark = path.find("?") if path.find("?") >= 0 else len(path)
  667. idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
  668. min_idx = min(idx_star, idx_qmark, idx_brace)
  669. detail = kwargs.pop("detail", False)
  670. withdirs = kwargs.pop("withdirs", True)
  671. if not has_magic(path):
  672. if await self._exists(path, **kwargs):
  673. if not detail:
  674. return [path]
  675. else:
  676. return {path: await self._info(path, **kwargs)}
  677. else:
  678. if not detail:
  679. return [] # glob of non-existent returns empty
  680. else:
  681. return {}
  682. elif "/" in path[:min_idx]:
  683. min_idx = path[:min_idx].rindex("/")
  684. root = path[: min_idx + 1]
  685. depth = path[min_idx + 1 :].count("/") + 1
  686. else:
  687. root = ""
  688. depth = path[min_idx + 1 :].count("/") + 1
  689. if "**" in path:
  690. if maxdepth is not None:
  691. idx_double_stars = path.find("**")
  692. depth_double_stars = path[idx_double_stars:].count("/") + 1
  693. depth = depth - depth_double_stars + maxdepth
  694. else:
  695. depth = None
  696. allpaths = await self._find(
  697. root, maxdepth=depth, withdirs=withdirs, detail=True, **kwargs
  698. )
  699. pattern = glob_translate(path + ("/" if ends_with_sep else ""))
  700. pattern = re.compile(pattern)
  701. out = {
  702. p: info
  703. for p, info in sorted(allpaths.items())
  704. if pattern.match(
  705. p + "/"
  706. if append_slash_to_dirname and info["type"] == "directory"
  707. else p
  708. )
  709. }
  710. if detail:
  711. return out
  712. else:
  713. return list(out)
  714. async def _du(self, path, total=True, maxdepth=None, **kwargs):
  715. sizes = {}
  716. # async for?
  717. for f in await self._find(path, maxdepth=maxdepth, **kwargs):
  718. info = await self._info(f)
  719. sizes[info["name"]] = info["size"]
  720. if total:
  721. return sum(sizes.values())
  722. else:
  723. return sizes
  724. async def _find(self, path, maxdepth=None, withdirs=False, **kwargs):
  725. path = self._strip_protocol(path)
  726. out = {}
  727. detail = kwargs.pop("detail", False)
  728. # Add the root directory if withdirs is requested
  729. # This is needed for posix glob compliance
  730. if withdirs and path != "" and await self._isdir(path):
  731. out[path] = await self._info(path)
  732. # async for?
  733. async for _, dirs, files in self._walk(path, maxdepth, detail=True, **kwargs):
  734. if withdirs:
  735. files.update(dirs)
  736. out.update({info["name"]: info for name, info in files.items()})
  737. if not out and (await self._isfile(path)):
  738. # walk works on directories, but find should also return [path]
  739. # when path happens to be a file
  740. out[path] = {}
  741. names = sorted(out)
  742. if not detail:
  743. return names
  744. else:
  745. return {name: out[name] for name in names}
  746. async def _expand_path(self, path, recursive=False, maxdepth=None):
  747. if maxdepth is not None and maxdepth < 1:
  748. raise ValueError("maxdepth must be at least 1")
  749. if isinstance(path, str):
  750. out = await self._expand_path([path], recursive, maxdepth)
  751. else:
  752. out = set()
  753. path = [self._strip_protocol(p) for p in path]
  754. for p in path: # can gather here
  755. if has_magic(p):
  756. bit = set(await self._glob(p, maxdepth=maxdepth))
  757. out |= bit
  758. if recursive:
  759. # glob call above expanded one depth so if maxdepth is defined
  760. # then decrement it in expand_path call below. If it is zero
  761. # after decrementing then avoid expand_path call.
  762. if maxdepth is not None and maxdepth <= 1:
  763. continue
  764. out |= set(
  765. await self._expand_path(
  766. list(bit),
  767. recursive=recursive,
  768. maxdepth=maxdepth - 1 if maxdepth is not None else None,
  769. )
  770. )
  771. continue
  772. elif recursive:
  773. rec = set(await self._find(p, maxdepth=maxdepth, withdirs=True))
  774. out |= rec
  775. if p not in out and (recursive is False or (await self._exists(p))):
  776. # should only check once, for the root
  777. out.add(p)
  778. if not out:
  779. raise FileNotFoundError(path)
  780. return sorted(out)
  781. async def _mkdir(self, path, create_parents=True, **kwargs):
  782. pass # not necessary to implement, may not have directories
  783. async def _makedirs(self, path, exist_ok=False):
  784. pass # not necessary to implement, may not have directories
  785. async def open_async(self, path, mode="rb", **kwargs):
  786. if "b" not in mode or kwargs.get("compression"):
  787. raise ValueError
  788. raise NotImplementedError
  789. def mirror_sync_methods(obj):
  790. """Populate sync and async methods for obj
  791. For each method will create a sync version if the name refers to an async method
  792. (coroutine) and there is no override in the child class; will create an async
  793. method for the corresponding sync method if there is no implementation.
  794. Uses the methods specified in
  795. - async_methods: the set that an implementation is expected to provide
  796. - default_async_methods: that can be derived from their sync version in
  797. AbstractFileSystem
  798. - AsyncFileSystem: async-specific default coroutines
  799. """
  800. from fsspec import AbstractFileSystem
  801. for method in async_methods + dir(AsyncFileSystem):
  802. if not method.startswith("_"):
  803. continue
  804. smethod = method[1:]
  805. if private.match(method):
  806. isco = inspect.iscoroutinefunction(getattr(obj, method, None))
  807. unsync = getattr(getattr(obj, smethod, False), "__func__", None)
  808. is_default = unsync is getattr(AbstractFileSystem, smethod, "")
  809. if isco and is_default:
  810. mth = sync_wrapper(getattr(obj, method), obj=obj)
  811. setattr(obj, smethod, mth)
  812. if not mth.__doc__:
  813. mth.__doc__ = getattr(
  814. getattr(AbstractFileSystem, smethod, None), "__doc__", ""
  815. )
  816. class FSSpecCoroutineCancel(Exception):
  817. pass
  818. def _dump_running_tasks(
  819. printout=True, cancel=True, exc=FSSpecCoroutineCancel, with_task=False
  820. ):
  821. import traceback
  822. tasks = [t for t in asyncio.tasks.all_tasks(loop[0]) if not t.done()]
  823. if printout:
  824. [task.print_stack() for task in tasks]
  825. out = [
  826. {
  827. "locals": task._coro.cr_frame.f_locals,
  828. "file": task._coro.cr_frame.f_code.co_filename,
  829. "firstline": task._coro.cr_frame.f_code.co_firstlineno,
  830. "linelo": task._coro.cr_frame.f_lineno,
  831. "stack": traceback.format_stack(task._coro.cr_frame),
  832. "task": task if with_task else None,
  833. }
  834. for task in tasks
  835. ]
  836. if cancel:
  837. for t in tasks:
  838. cbs = t._callbacks
  839. t.cancel()
  840. asyncio.futures.Future.set_exception(t, exc)
  841. asyncio.futures.Future.cancel(t)
  842. [cb[0](t) for cb in cbs] # cancels any dependent concurrent.futures
  843. try:
  844. t._coro.throw(exc) # exits coro, unless explicitly handled
  845. except exc:
  846. pass
  847. return out
  848. class AbstractAsyncStreamedFile(AbstractBufferedFile):
  849. # no read buffering, and always auto-commit
  850. # TODO: readahead might still be useful here, but needs async version
  851. async def read(self, length=-1):
  852. """
  853. Return data from cache, or fetch pieces as necessary
  854. Parameters
  855. ----------
  856. length: int (-1)
  857. Number of bytes to read; if <0, all remaining bytes.
  858. """
  859. length = -1 if length is None else int(length)
  860. if self.mode != "rb":
  861. raise ValueError("File not in read mode")
  862. if length < 0:
  863. length = self.size - self.loc
  864. if self.closed:
  865. raise ValueError("I/O operation on closed file.")
  866. if length == 0:
  867. # don't even bother calling fetch
  868. return b""
  869. out = await self._fetch_range(self.loc, self.loc + length)
  870. self.loc += len(out)
  871. return out
  872. async def write(self, data):
  873. """
  874. Write data to buffer.
  875. Buffer only sent on flush() or if buffer is greater than
  876. or equal to blocksize.
  877. Parameters
  878. ----------
  879. data: bytes
  880. Set of bytes to be written.
  881. """
  882. if self.mode not in {"wb", "ab"}:
  883. raise ValueError("File not in write mode")
  884. if self.closed:
  885. raise ValueError("I/O operation on closed file.")
  886. if self.forced:
  887. raise ValueError("This file has been force-flushed, can only close")
  888. out = self.buffer.write(data)
  889. self.loc += out
  890. if self.buffer.tell() >= self.blocksize:
  891. await self.flush()
  892. return out
  893. async def close(self):
  894. """Close file
  895. Finalizes writes, discards cache
  896. """
  897. if getattr(self, "_unclosable", False):
  898. return
  899. if self.closed:
  900. return
  901. if self.mode == "rb":
  902. self.cache = None
  903. else:
  904. if not self.forced:
  905. await self.flush(force=True)
  906. if self.fs is not None:
  907. self.fs.invalidate_cache(self.path)
  908. self.fs.invalidate_cache(self.fs._parent(self.path))
  909. self.closed = True
  910. async def flush(self, force=False):
  911. if self.closed:
  912. raise ValueError("Flush on closed file")
  913. if force and self.forced:
  914. raise ValueError("Force flush cannot be called more than once")
  915. if force:
  916. self.forced = True
  917. if self.mode not in {"wb", "ab"}:
  918. # no-op to flush on read-mode
  919. return
  920. if not force and self.buffer.tell() < self.blocksize:
  921. # Defer write on small block
  922. return
  923. if self.offset is None:
  924. # Initialize a multipart upload
  925. self.offset = 0
  926. try:
  927. await self._initiate_upload()
  928. except:
  929. self.closed = True
  930. raise
  931. if await self._upload_chunk(final=force) is not False:
  932. self.offset += self.buffer.seek(0, 2)
  933. self.buffer = io.BytesIO()
  934. async def __aenter__(self):
  935. return self
  936. async def __aexit__(self, exc_type, exc_val, exc_tb):
  937. await self.close()
  938. async def _fetch_range(self, start, end):
  939. raise NotImplementedError
  940. async def _initiate_upload(self):
  941. pass
  942. async def _upload_chunk(self, final=False):
  943. raise NotImplementedError