Harbor format: 871 coding_baseline tasks (part 54)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/async.rstAdded+188
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/changelog.rstAdded+1765
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/code-of-conduct.rstAdded+126
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/conf.pyAdded+193
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/copying.rstAdded+348
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/developer.rstAdded+130
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/features.rstAdded+470
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/img/gui.pngAdded
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/index.rstAdded+129
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/intro.rstAdded+99
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/usage.rstAdded+179
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/__init__.pyAdded+75
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/_version.pyAdded+24
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/archive.pyAdded+86
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/asyn.pyAdded+1335
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/caching.pyAdded+1158
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/callbacks.pyAdded+324
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/compression.pyAdded+185
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/config.pyAdded+131
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/conftest.pyAdded+125
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/core.pyAdded+765
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/dircache.pyAdded+125
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/exceptions.pyAdded+18
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/fuse.pyAdded+324
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/generic.pyAdded+409
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/gui.pyAdded+417
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/__init__.pyAdded
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/arrow.pyAdded+333
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/asyn_wrapper.pyAdded+135
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/cache_mapper.pyAdded+75
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/cache_metadata.pyAdded+217
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/cached.pyAdded+1224
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/chained.pyAdded+23
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/dask.pyAdded+152
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/data.pyAdded+73
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/dbfs.pyAdded+498
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/dirfs.pyAdded+492
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/ftp.pyAdded+445
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/gist.pyAdded+241
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/git.pyAdded+123
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/github.pyAdded+348
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/http.pyAdded+1069
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/http_sync.pyAdded+937
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/ia.pyAdded+230
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/jupyter.pyAdded+132
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/libarchive.pyAdded+219
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/local.pyAdded+537
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/memory.pyAdded+476
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/reference.pyAdded+1387
59 unmodified lines60616259 unmodified lines*.webm filter=lfs diff=lfs merge=lfs -textdata/tasks.jsonl filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-35d8641e8647/tests/source/docs/_static/social[[:space:]]card.afdesign filter=lfs diff=lfs merge=lfs -text59 unmodified lines6061626359 unmodified lines*.webm filter=lfs diff=lfs merge=lfs -textdata/tasks.jsonl filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-35d8641e8647/tests/source/docs/_static/social[[:space:]]card.afdesign filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-4ca6d2396445/tests/source/docs/_static/social[[:space:]]card.afdesign filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188Async=====
``fsspec`` supports asynchronous operations on certain implementations. Thisallows for concurrent calls within bulk operations such as ``cat`` (fetchthe contents of many files at once) even from normal code, and for the directuse of fsspec in async code without blocking.Async implementations derive from the class ``fsspec.asyn.AsyncFileSystem``.The class attribute ``async_impl`` can be used to test whether animplementation is async of not.
``AsyncFileSystem`` contains ``async def`` coroutine versions of the methods of``AbstractFileSystem``. By convention, these methods are prefixed with "_"to indicate that they are not to called directly in normal code, onlywhen you know what you are doing. In most cases, the code is identical orslightly modified by replacing sync calls with ``await`` calls to asyncfunctions.
The only async implementation built into ``fsspec`` is ``HTTPFileSystem``.
Synchronous API---------------
The methods of ``AbstractFileSystem`` are available and can be called fromnormal code. They call and wait on the corresponding async function. The*work* is carried out in a separate threads, so if there are many fsspecoperations in flight at once, launched from many threads, they will stillall be processed on the same IO-dedicated thread.
Most users should not be aware that their code is running async.
Note that the sync functions are wrapped using ``sync_wrapper``, whichcopies the docstrings from ``AbstractFileSystem``, unless they areexplicitly given in the implementation.
Example:
.. code-block:: python
fs = fsspec.filesystem("http") out = fs.cat([url1, url2, url3]) # fetches data concurrently
Coroutine batching------------------
The various methods which create many coroutines to be passed to the event loopfor processing may be batched: submitting a certain number in one go and waitingfor them to complete before launching more. This is important to work aroundlocal open-file limits (which can be <~100) and not to swamp the heap.
``fsspec.asyn._run_coros_in_chunks`` controls this process, but from the user's pointof view, there are three ways to affect it. In increasing order or precedence:
- the global variables ``fsspec.asyn._DEFAULT_BATCH_SIZE`` and ``fsspec.asyn._NOFILES_DEFAULT_BATCH_SIZE`` (for calls involving local files or not, respectively)
- config keys "gather_batch_size" and "nofiles_gather_batch_size"
- the ``batch_size`` keyword, accepted by the batch methods of an async filesystem.
Using from Async----------------
File system instances can be created with ``asynchronous=True``. Thisimplies that the instantiation is happening within a coroutine, sothe various async method can be called directly with ``await``, as isnormal in async code.
Note that, because ``__init__`` is a blocking function, any creationof asynchronous resources will be deferred. You will normally need toexplicitly ``await`` a coroutine to create them. Since garbage collectionalso happens in blocking code, you may wish to explicitly awaitresource destructors too. Example:
.. code-block:: python
async def work_coroutine(): fs = fsspec.filesystem("http", asynchronous=True) session = await fs.set_session() # creates client out = await fs._cat([url1, url2, url3]) # fetches data concurrently await session.close() # explicit destructor
asyncio.run(work_coroutine())
Bring your own loop-------------------
For the non-asynchronous case, ``fsspec`` will normally create an asyncioevent loop on a specific thread. However, the calling application may preferIO processes to run on a loop that is already around and running (in anotherthread). The loop needs to be asyncio compliant, but does not necessarily needto be an ``ayncio.events.AbstractEventLoop``. Example:
.. code-block:: python
loop = ... # however a loop was made, running on another thread fs = fsspec.filesystem("http", loop=loop) out = fs.cat([url1, url2, url3]) # fetches data concurrently
Implementing new backends-------------------------
Async file systems should derive from ``AsyncFileSystem``, and implement the``async def _*`` coroutines there. These functions will either have sync versionsautomatically generated if the name is in the ``async_methods`` list, orcan be directly created using ``sync_wrapper``.
.. code-block:: python
class MyFileSystem(AsyncFileSystem):
async def _my_method(self): ...
my_method = sync_wrapper(_my_method)
These functions must **not call** methods or functions which themselves are synced,but should instead ``await`` other coroutines. Calling methods which do not require sync,such as ``_strip_protocol`` is fine.
Note that ``__init__``, cannot be ``async``, so it might need to allocate asyncresources using the ``sync`` function, but *only* if ``asynchronous=False``. If itis ``True``, you probably need to require the caller to await a coroutine thatcreates those resources. Similarly, any destructor (e.g., ``__del__``) will run from normalcode, and possibly after the loop has stopped/closed.
To call ``sync``, you will need to pass the associated event loop, which will beavailable as the attribute ``.loop``.
.. autosummary:: fsspec.asyn.AsyncFileSystem fsspec.asyn.get_loop fsspec.asyn.sync fsspec.asyn.sync_wrapper
.. autoclass:: fsspec.asyn.AsyncFileSystem :members:
.. autofunction:: fsspec.asyn.get_loop
.. autofunction:: fsspec.asyn.sync
.. autofunction:: fsspec.asyn.sync_wrapper
.. raw:: html
<script data-goatcounter="https://fsspec.goatcounter.com/count" async src="//gc.zgo.at/count.js"></script>
AsyncFileSystemWrapper----------------------
The `AsyncFileSystemWrapper` class allows you to converta synchronous filesystem into an asynchronous one. This is useful for quickly integratingsynchronous filesystems into workflows that may expect `AsyncFileSystem` instances.
Basic Usage~~~~~~~~~~~
To use `AsyncFileSystemWrapper`, wrap any synchronous filesystem to work in an asynchronous context.In this example, the synchronous `LocalFileSystem` is wrapped, creating an `AsyncFileSystem` instancebacked by the normal, synchronous methods of `LocalFileSystem`:
.. code-block:: python
import asyncio import fsspec from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
async def async_copy_file(): sync_fs = fsspec.filesystem('file') # by-default synchronous, local filesystem async_fs = AsyncFileSystemWrapper(sync_fs) return await async_fs._copy('/source/file.txt', '/destination/file.txt')
asyncio.run(async_copy_file())
Limitations-----------
Users should not expect this wrapper to magically make things faster.It is primarily provided to allow usage of synchronous filesystems with interfaces that expect`AsyncFileSystem` instances.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765Changelog=========
Dev---
Enhancements
- Accept a ``callback=`` on the caching filesystems and pass it to the ``get`` operations that fill the cache on a miss, so ``filecache``/``simplecache`` opens can report download progress (#1623)
Fixes
- Reject Git paths below files and preserve complete file names in Git metadata.
- Honor exclusive creation mode in DBFS file opens instead of overwriting an existing file.
- Honor ``create_parents=False`` in ``MemoryFileSystem.mkdir`` when the parent directory does not exist.
- Leave out the passwords of nested FSs when serializing with ``include_password=False``.
- Raise an error when WebHDFS refuses a rename instead of reporting success (#2327).
- Close local transactional write handles before deleting their temporary files during rollback, avoiding Windows sharing errors and leaked handles.
- Omit unreachable references from ``ReferenceFileSystem.cat`` results when ``on_error="omit"``.
- Reject reads on closed asynchronous HTTP streams without reopening a request.
- Preserve explicit directory permissions when SFTP ``mkdir`` creates parents.
- Only send ``ia://`` credentials over https when the download URL is https.
- Honor ``block_size=0`` for direct and transactional SFTP file opens.
- Make FUSE CLI ``-f`` match its documented default (#1586).
- Preserve source and destination URL text within relative names during ``generic.rsync``.
- Accept equivalent binary update mode orderings in ``MemoryFileSystem.open``.
- Request a protected data channel again when ``FTPFileSystem`` reconnects with ``tls=True``
- Decompress cache downloads made by ``cat`` so subsequent cached reads use the same contents as ``open``.
- Retain the selected local file when a ``filecache`` entry expires during open.
- Fix the syntax and add a memory filesystem to the quick-start example (#2337).
- Preserve directory pruning in ``DirFileSystem.walk(detail=True)``
- Finalize zip-fs file contexts on explicit close (#2311).
- Close sync HTTP download files on success or failure, without closing caller-owned streams.
- Expose known buffered-file sizes through a ``len`` property for multipart encoders.
- Propagate backend removal errors from ``FSMap``
- Check known_hosts in ``SFTPFileSystem`` (#2308; issue #2119)
- Warn with the fingerprint when ``SFTPFileSystem`` accepts an unknown host key, and add the key to ``known_hosts`` if it is given (#2308)
- Require ``paramiko>=3.4`` for the ``sftp`` and ``ssh`` extras (#2308)- Handle explicit ``create`` and ``overwrite`` modes in ZIP ``pipe``
- Bound block-cache fetch ranges by the file size, including background reads.
- Drain pending adaptive prefetch tasks on close after the producer reaches EOF.
- Exclude URL fragments when decoding data URLs.
- Return empty results for HTTP reads ending at offset zero without sending an invalid range request.
- Correct the configuration directory variable and explain JSON parsing of environment overrides (#2324)
- Update contributor linting and formatting instructions for Ruff and pre-commit (#2325)
- Accept string-valued path-like objects in ``DirFileSystem`` delegated operations.
- Reject mixed source or destination backends in ``GenericFileSystem.copy``(#2302).
- Return the current position for accepted no-op seeks on HTTP streams (#2306)
- Complete DBFS partial-delete retries without re-raising a recovered error.
- Keep the HTTP link regex linear
- Preserve single-source copy semantics for Paths in sync batch ops
- Reject unsupported HTTP ``pipe_file`` modes defensively before writing, since PUT behavior depends on the server (#2294).
- Reject ``generic.rsync`` source names whose ".." segments would place copies outside the destination
- Avoid reference cycles when a synchronous call into an async filesystem fails, so its frames and the data they hold are freed straight away instead of waiting for the garbage collector (#2295)
- Reject read-only buffers in buffered-file ``readinto()`` before consuming file data (#2260)
- Honor ``maxdepth`` when copying recursively with ``ReferenceFileSystem.get``. (#2269)
- Support ``length=None`` in ``utils.read_block`` without a delimiter (#2262)
- Reject memory fs copies whose destination conflicts with an existing file or directory (#2268)
- Preserve ``None`` values when serializing filesystem arguments (#2264)
- Correct file name padding for large integer maxima so lexical order matches numeric order (#2263)
- Preserve caller-owned protocol options when merging per-call overrides (#2279)
- Return an empty block instead of passing a negative read length in read_block (#2261)
- Preserve per-call request options in HTTP directory listings (#2258)
- Refetch memory-mapped cache blocks when a missing backing file is recreated (#2257)
- Normalize single-dot and empty path components in libarchive member names and lookups.
- Read the last libarchive member consistently when duplicate names include empty files.
- Preserve caller-provided temporary directories during cross-filesystem copies.
- Raise ``FileExistsError`` when ``MemoryFileSystem.makedirs`` targets an existing file, even with ``exist_ok=True`` (#2266).
- Close memory-mapped cache resources when the owning buffered file is closed.
- Use the correct POST method in the Pyodide HTTP session shim.
- Decode URL-escaped base64 payloads in data URLs and distinguish the encoding flag from MIME metadata.
- Read empty GitHub files without requiring the HTTP extra or a second download.
- Accept PathLike local destinations in synchronous ``get`` (#896).
- Reject seeks that change position on async streaming HTTP files.
- Follow GitHub API pagination when listing tags, branches and repositories.
- Strip SFTP and SSH URL prefixes before recursively creating directories.
- Return ``created`` as a timestamp in ``MemoryFileSystem.info``, as ``ls`` and ``find`` already do.
- Strip the protocol from the path in ``LocalFileSystem.lexists``.
- Preserve Windows drive letters when parsing Git filesystem URLs (#1125).
- Return a list of paths when listing a single file with ``GithubFileSystem``.
- Recognize multi-byte delimiters spanning read blocks in buffered-file ``readuntil()``.
- Stop the fsspec IO loop and join its thread at interpreter exit, so a callback firing on it after ``Py_Finalize`` (e.g. a uvloop timer) cannot crash the process (#2241).
- Avoid deadlocks in ``sync()`` when the default IO thread has stopped (#1723).
- Percent-encode GitHub branch and tag names in API URLs so refs containing ``#``, ``&`` or ``%`` select the intended revision.
- Keep files deeper than ``maxdepth`` in a recursive ``LocalFileSystem.rm`` instead of deleting the whole tree.
- Keep directories that still hold files deeper than ``maxdepth`` in a recursive ``MemoryFileSystem.rm`` instead of raising ``OSError``.
- Read ini and json config files as UTF-8 instead of the locale encoding.
- Infer Zstandard compression for ``.zstd`` as well as ``.zst`` (#1589).
- Keep files deeper than ``maxdepth`` in the source of a recursive ``mv`` instead of deleting them uncopied.
- Accept local filesystem URLs in ``get_file`` when copying to a file-like object.
- Accept full FTP URLs in direct ``cat_file`` and ``get_file`` calls.
- Strip the protocol from the path in ``LocalFileSystem.chmod``.
- Forward the wrapped filesystem's ``local_file`` flag through ``DirFileSystem`` (#1110).
- Report ``DirFileSystem.async_impl`` from the wrapped filesystem instance.
- Request identity encoding for buffered HTTP range reads by default, while preserving explicitly configured request and session encodings (#1748).
- Avoid treating content-encoded transfer lengths as decoded file sizes in the synchronous HTTP filesystem.
- Resolve negative FTP read offsets relative to the end of the file.
- Return an empty list from buffered-file ``readlines()`` at end of file
- Normalize protocol prefixes and leading slashes before listing archive paths.
- Update memory file modification times after writes and truncation.
- Preserve binary bytes in percent-encoded data URLs without base64 encoding.
- Keep failed memory-mapped cache reads retriable without discarding completed ranges.
- Percent-encode GitHub file paths in contents API URLs so files named with ``#``, ``?`` or ``%`` can be read and removed.
- Make async loop lock initialization thread-safe (#1783)
- Create parent directories before ``FSMap.setitems`` writes, matching ``__setitem__`` and allowing deferred local transaction writes to commit to missing parents (#1041).
2026.9.0--------
Enhancements
- ``ia://`` filesystem for files in Internet Archive items: an ``HTTPFileSystem`` reading from ``archive.org/download`` with credentials from ``ia configure``'s ``ia.ini``- Allow instance-local memory stores with ``global_store=False`` while preserving normal instance caching and the default shared store (#2137; issue #1904)
- Add an adaptive readahead cache (#2093)
- Implement ``created`` and ``modified`` for ``SFTPFileSystem`` (#2104)
- Allow filesystem implementations to assign ``protocol`` per instance (#2117)
- Delegate ``sizes`` and ``cat_ranges`` from ``DirFileSystem`` to the wrapped filesystem (#2142)
- Delegate ``invalidate_cache``, ``ukey`` and ``checksum`` from ``DirFileSystem`` to the wrapped filesystem (#2144)
- Support negative offsets in ``TarFileSystem.cat_file`` (#2146)
- Mirror ``readinto`` from the PyArrow stream onto ``ArrowFile`` (#2111)
- Allow ``simplecache`` files to be removed by age using their modification times (#2118)
- HTTP: retry transient failures (408/425/429/5xx, dropped connections, timeouts, truncated range bodies, a 416 inside the file) of ``cat_file``, ``HTTPFile`` block reads and the size lookup behind ``open``, controlled by the new ``retries``, ``retry_wait``, ``retry_statuses`` and ``retry_exceptions`` options (#2124)
Fixes
- Compute ``HadoopFileSystem.fsid`` from its configured host and port instead of accessing attributes no longer exposed by PyArrow (issue #1870)
- Normalize dot path components in ``TarFileSystem`` listings and lookups, while preserving original archive names for reading (issue #1568)
- Make ``merge_offset_ranges`` ``O(n log n)`` and keep merged blocks within ``max_block``, replacing the quadratic nested-range filter added in #1982 (#2091)
- Fix transactions with compressed files (#2070)
- Make ``MemoryFileSystem.rm`` raise ``FileNotFoundError`` for a path that does not exist, as ``rm_file`` and the other filesystems do, so deleting a missing key from a memory-backed mapper raises ``KeyError`` (#2140)
- Create missing ZIP archives in append mode without truncating existing archives (#2139)
- Close cached readers when exiting an ``open_files`` context (#2131)
- Avoid mutating live ``BlockCache`` and ``BackgroundBlockCache`` instances when pickling (#2102)
- End the transaction even when a commit or discard raises, so the filesystem is not left in transaction mode and deferred temporary files are cleaned up (#2108)
- Honor a caller-owned output file in ``get_file`` (#2066)
- Preserve existing files when checking ``FSMap`` write access (#2122)
- Normalize ZIP paths in ``pipe_file`` and ``find`` (#2123)
- Reject ``get`` destinations that resolve above the target (#2103)
- Pass ``maxdepth`` through in ``AsyncFileSystem._rm`` (#2106)
- Do not let ``isfile`` swallow ``BaseException`` (#2125)
- Keep reference filesystem ``get`` destinations inside the target (#2129)
- Return relative names from ``DirFileSystem.glob`` and ``find`` (#2127)
- Raise ``FileNotFoundError`` for missing ZIP and TAR members (#2141)
- Stop collapsing three-character drive-relative paths to the drive root (#2143)
- Use ``/`` as the only glob separator on every platform (#2112)
- Distinguish omitted and ``None`` defaults in ``FSMap.pop`` (#2136)
- Forward an Arrow file's ``flush`` and ``closed`` state to its stream (#2134)
- Keep reference filesystem ``cat_file`` offsets inside the referenced part (#2147)
- Raise ``FileNotFoundError`` from archive ``ls`` for a missing path (#2145)
- Download uncached files in ``simplecache.cat_ranges`` (#2154)
- Fix ``tail`` on ``simplecache`` and ``filecache`` (#2155)
- Get whole-file reference sizes asynchronously in ``ReferenceFileSystem._info`` (#2156)
- Report the target size for links in ``TarFileSystem`` (#2157)
- Keep the async generator returned by ``AsyncFileSystemWrapper._walk`` (#2158)
- Join the default output filename with ``/`` in ``_expand_paths`` (#2162)
- Make names relative in ``DirFileSystem.walk(detail=True)`` (#2160)
- Ignore a leading slash in ``TarFileSystem`` paths (#2148)
- Fix ``cat_ranges`` on whole-file caches (#2163)
- Normalize paths in ``AsyncFileSystemWrapper`` like the wrapped filesystem (#2159)
- The SFTP host key policy is configurable with the new ``host_key_policy`` argument of ``SFTPFileSystem``, which accepts ``"auto_add"`` (default, unchanged behaviour), ``"warning"`` or ``"reject"``, or any ``paramiko.MissingHostKeyPolicy`` (#2126; issue #2119)
Other
- Use trusted publishing for releases and trigger the release workflow on tags (#2060)
- Remove the stale async wrapper documentation warning (#2098)
- Add Zarr to the ``test_downstream`` extra so the Xarray/Zarr test runs again (#2109)
- Clarify that ``rm`` handles directories (#2096)
- Fix grammar in ``features.rst`` (#2153)
- Patch ``HAS_CPYTHON_API`` where ``_fast_slice`` reads it in tests (#2164)
- Percent-decode the username and password parsed from URLs in ``infer_storage_options`` so that backends (ftp, sftp, smb, ...) receive the real credentials rather than their URL-encoded form; a password whose bare ``%`` produces bytes that are not valid UTF-8 (for example ``pass%ab``) is left untouched so that pre-existing URLs with unescaped ``%`` continue to work (#1871)
2026.7.0--------
Enhancements
- Single-pass ``MemoryFileSystem.find()`` to avoid O(n_dirs * n_entries) listing (#2055)- Permit composite URL protocol schemes in infer_storage_options (#2085)- Implement topdown in async walk() (#2052)
Fixes
- Fix incorrect glob docstring for '[!]' (#2084)- Propagate storage_options to all backends resolved by GenericFileSystem (#2083)- Handle end=None in FirstChunkCache._fetch like the other caches (#2082)- Clamp read end to file size in BlockCache and BackgroundBlockCache(#2081)- Create the parent dir for "x" and "a" modes under auto_mkdir (#2079)- Expand paths for mode="x" when urlpath is a list (#2078)- fix: correctly pass 'start' and 'end' parameters to super().cat_file() (#2077)- Fix LocalFileSystem directory symlink removal (#2074)- Fix ArrowFSWrapper parent paths for S3 (#2072)- Fix get_file_extension when a parent directory name contains a dot (#2071)- tar: make members with duplicate slashes reachable via ls/find/glob (#2063)- MemoryFileSystem: create the file when appending to a missing path (#2062)
Other
- fixes for pytest deprecation (#2076)- Shut down background cache workers on file close (#2069)- Forward ls kwargs from cached filesystems (#2068)- Fix bare except: use except Exception in upload cleanup handler (#2067)- fix: Make Cached metaclass instance instantiation thread-safe and fork-safe (#2064)- ci: fix test collection in fsspec_friends job (#2061)- ftp: Make deprecated TLS versions optional (#2056)- restrict cache storage directory permissions to owner (#2048)
2026.6.0--------
Fixes
- FTP: preserve filenames containing whitespace in _mlsd2 (#2043)- Prevent attribute error for 'forced' before flushing cache (#2042)- Reflect async _walk correctly (#2040)- Fix infinite recursion in expand_path with glob magic characters (#2038)- Do not strip trailing slashes from data URIs (#2037)- Fix referenceFS for new zarr and pandas (#2034)- Omit get_ident() from cache token for async impl in sync mode (#2028)
Other
- Fix AsyncFileSystem._cat_ranges on_error handling (#2045)- Forward kwargs from cat_ranges to cat_file (#2044)- Don't parse refFS templates by default (#2039, 2029)- fix s3fs ci (#2035)- fix: pass on_error when mv calls copy (#2030)
2026.4.0--------
Fixes
- proper install in ci to grab versions (#2025)- encode URLs in HTTP pipe_file (#2023)- implement delete and write_test for dirFS (#2022)- allow multiple local protocols (#2014)- context closing for tar and zip (#2012)- fix cat_file and cat_ranges for WholeFileCache (#2010)
Other
- usage warning to HTTP FS (#2024)- update adl: message following retirement (#2019)
2026.3.0--------
Fixes
- non-string types in individual cond kwarg value env-vars (#2004)- allow withdirs in glob (#1998)- multi-file put in sftp (#1991)
2026.2.0--------
Enhancements
- support append and update mode for cachedFSs (#1980)- implement created()/modified() for webHDFS (#1971)
Fixes
- recover support for old zstandard package (#1987)- remove prefetching loop in block-cache causing double read (#1984)- fixes to parquet and known-cache (#1982, 1988, 1979)- return None for streamed arrow file size (#1981)- correct find() for ZipFS (#1976)
2026.1.0--------
Put limits on install extras for s3fs/gcsfs to prevent installingancient versions via pip.
Enhancements
- configure TLS protocol version for FTP (#1958)
Fixes
- Respect auto_mkdir in mv for local (#1957)
Other
- link to pydantic, code and union implementations ($1956)- use backport.zstd or builtin (#1962)- docs typo (#1963)
2025.12.0---------
Enhancements
- fsspec.parquet to support filters and multiple files (#1945)
Fixes
- passing withdirs in aync _glob() (#1953)- fix _rm_file/_rm redirection in async (#1951)- allow arrowFile to be seekable (#1950)- add size attribute to arrowFile (#1944)
Other
- support py3.14 and drop 3.9 (#1946)- avoid ruff warning (#1942)
2025.10.0---------
Enhancements
- specify storage_options not use use for tokenising; test instance cache (#1933)- base class "chained" for FSs that pass through operations (#1929)
Fixes
- strip protocol for sftp (#1940)- use one-step mv in jupyterfs (#1937)- raise errors in jupyterfs, not return (#1936)- add protocol attribute to http(#1935)- allow ls() on a single file for arrowFS (#1931)- support kwargs in webhdfs ls() (#1928)- better discrimination for parquet in referenceFS (#1923)- accept all mode= types in memoryFS (#1922)- pass path list to put() in localtempfile for efficiency (#1920)- fix docs errors (#1917)
Other
- add CoC (#1924)- restrict github/gist tests because of rate limiting (#1918)
2025.9.0--------
Enhancements
- include Last_modified info from HTTP headers to info (#1909)- add optional semaphore to async-wrapper (#1908)
Fixes
- ensure cachingFSs show correct protocol (#1897)- fix simplecache cat_ranges (#1892)
Other
- Style (#1894)
2025.7.0--------
Enhancements
- only download HTML mime for http listing (#1889)- add tos:// to registry (#1878)
Fixes
- use st_birthtime in localFS, if available (#1883)- allow cat_* in simplecache (#1881)- remove deprecated asyncio use (#1862)- create event loop if it doesn't exist (#1857)
Other
- remove references to py38 (#1888)- ruff updates (#1887, 1864)- github rate limits in CI (#1879, 1877)- acknowledge Anaconda support (#1876)- add obstore to known implementations (#1875)- add Microsoft storage to known implementations (#1853)- use builtins zstd for py3.14 (#1874)- gdrivefs -> gdrive_fsspec (#1858)- windows version in CI (#1855)- error message typo (#1854)
2025.5.1--------
Enhancements
- file system for GitHub gists (#1791)
Other
- doc fixes (#1847, 1848)
2025.5.0--------
Enhancements
- add rm in github: (##1839)- cachingFS performance, don't ls every time (#1833)- pyscript: protocol and optional entrypoint (#1828)
Fixes
- improve cp in generic (#1835)- fix ls in dbfs (#1834)- fix parquet tests for pyarrow 20 (#1831)- fix crosslink for local tempfile (#1829)- keep permissions in local transaction (#1826)- signature compatibility in local cp() (#1820)
Other
- add "gs" at mention of gcsfs in docs (#1840)- lint style (#1837)- glob docstring to reflect reality (#1825)
2025.3.2--------
- drop support for py3.8
2025.3.1--------
Enhancements
- LFS support in github: (#1810)
Fixes
- json should be a method fo requests shim (#1814)- don't raise if known_implementation has no given error string (#1804)
Other
- rename protocols for sync-http (#1810)
2025.3.0--------
Enhancements
- add pipe_file to HTTP (#1799, 1801)- add sync http for pyodide (#1177)- ls performance for local and detail=False (#1789)
Fixes
- dir/info consistency in dirfs (#1798)- referenceFS async consistency (#1794, 1795)- CI (#1793)
2025.2.0--------
Enhancements
- add open() to referenceFS (#1778)
Fixes
- don't make async open() in async-wrapper (#1769)- fix CI following dask-expr upstream change (#1781)- cope with zarr3 "Buffer" objects in referenceFS (#1784)
Other
- use itemgetter in archiveFS (#1764)- document that newline is included in readline(s) (#1770)- format/spelling (#1774, 1779, 1780)
2024.12.0---------
Enhancements
- "exclusive" mode for writing (#1762, 1756, 174+)- "tree" text display of filesystem contents (#1750)- async wrapper for sync FSs (#1745)- new known implementation: tosfs (#1739)- consilidate block fetch requests (#1733)
Fixes
- better webHDFS proxies (#- syn FSs in referenceFS (#1755)- don't serialize file caches (#1753)- race condition in local ls() (#1744)- missing/nan references in parquet (#1738)- _un_chain kwargs (@1736)- async _cat_file in referenceFS (#1734)
Other
- fallback implementation for _fetch_range (#1732)
2024.10.0---------
Fixes
- Performance of memoryFS rm (#1725)- Performance of git FS info (#1712)- Avoid git hex for newer pygit (#1703)- tests fix for zip (#1700, 1691)- missing open_async for dirFS (#1698)- handle pathlib in zip (#1689)- skip tests needing kerchunk if not installed (#1689)- allow repeated kwargs in unchain (#1673)
Other
- Code style (#1704, 1706)- allow pyarrow in referenceFS parquet (#1692)- don't hardcode test port for parallel runs (#1690)
2024.9.0--------
Enhancements
- fewer stat calls in localFS (#1659)- faster find in ZIP (#1664)
Fixes
- paths without "/" in dirFS (#1638)- paths with "/" in FTS (#1643, 1644)- ls in parquet-based nested reference sets, and append (#1645, 1657)- exception handling for SMB (#1650)
Other
- style (#1640, 1641, 1660)- docs: xrootd (#1646)- CI back on miniconda (#1658)
2024.6.1--------
Fixes
- fix appending to non-dict reference sets (#1634)- don't let generic edit info dicts (#1633)- set https's loop before calling super (#1633)- cached write file doesn't need to update it's size on close (#1633)- fix JSON serialize for FSs with interior FSs (#1628, 1627)- option to strip "password" when pickling (#1625)- fix filecache write (#1622)
2024.6.0--------
Enhancements
- allow dicts (not just bytes) for referenceFS (#1616- make filesystems JSON serializeable (#1612)- implement multifile cat() for github (#1620)
Fixes
- implement auto_mkdir for SMB (#1604)
Other
- add doc deps to pyproject (#1613)- re-remove test from package (#1611)- formatting (#1610, 1608, 1602)- change monthly download badge (#1607)
2024.5.0--------
Enhancements
- log hits/misses in bytes cachers (#1566)
Fixes
- SMB flaky tests (#1597)- rsync: only delete files if there are some to delete (#1596)- don't let files equal bytes objects (#1594)- url_to_fs to stringify paths (#1591)- assert types in MemoryFS (#1574)- restore _strip_protocol signature for local (#1567)- convert list to set when loading cache metadata (#1556)
Other
- remove mv_file (#1585)- mv() should not swallow errors (#1576)- change versioning template, allows easier co-install of dev s3fs (#1569)- in ls_from_cache, avoid dounble lookup (#1561)- expand=True in open() (#1558)- build system to hatch (#1553)
2024.3.1--------
Fixes
- allow override of expand in open() (#1549)- root handling in local file paths, fix for windows (#1477)
2024.3.0--------
Enhancements
- coroutines throttle to stream pool rather than batches (#1544)- write transactions in simplecache (#1531)- allow deep nested refs in referenceFS/parquet (#1530)
Fixes
- Fixes bug (#1476) that made open_files ignore expand=False (#1536)- remove extra calling mapper contains (#1546)- connection retry for SMB (#1533)- zip64 should be on is allowZip64 is (#1532)
Other
- HTTP logging (#1547)- url_to_fs exposed in package root (#1540)- sort known_implementations (#1549)- code quality/stype (#1538, 1537, 1528, 1526)
2024.2.0--------
Enhancements
- add 9P known implementation (#1513)- allow TqdmCallback subclassing (#1497, 1480)- callbacks/branching kwargs handling and scopes (#1496, 1495, 1460)- add aluuxioFS to known implementations (#1469)- implement pipe_file for dirFS (#1465)
Fixes
- infer compression for .lzma files (#1514)- fix append to categorical/parquet references (#1510)- allow for FTP servers that list with leading "total" line (#1503)- convert FTP failure to FileNotFound (#1494)- out of order reference fix (#1492)- retry "backoff" response for DBFS (#1491)- referenceFS case for scalar arrays (#1487)- fix create_parents for SFTP (#1484)- fix local .ls() on files (#1479)- allow Path and similar in _expand_path (#1475)- make lazy references editable (#1468)- fix eq for abstract buffered files (#1466)- fit tqdm cleanup (#1463)- fix passing kwargs from cached file to underlying FS (#1462)
Other
- fix tests for supports_empty_directories=False (#1512)- don't read references in init for referenceFS (#1521)- code cleaning (#1518, 1502, 1499, 1493, 1481)- pass through "replication" for HDFS (#1486)- record more info for HTTP info() (#1483)- add timeout argument to githubFS (#1473)- add more security pars to webHDFS (#1472)
2023.12.2---------
Fixes
- top-level glob in ZIP (#1454)- append mode on local ZIP files/truncate (#1449)- restrict ":" as protocol marker to data: (#1452)- sftp relative paths (#1451)- http encoding in HTTP FS put_file (#1450)
2023.12.1---------
Fixes
- Remove trailing "/" from directory names in zipFS/archive (#1445)
2023.12.0---------
Enhancements
- allow HTTP size guess in more circumstances (#1440)- allow kwargs passed to GUI to be dict (#1437)- transaction support for writing via a cache FS (#1434)- make cached FSs work better with async backends (#1429)- allow FSs to set their transaction implementation (#1424)- add dataFS (#1421, 1415)- allow basic auth in webHDFS (#1409)
Fixes
- in referenceFS, maintain order when some keys are omitted in cat (#1436)- nested subdirectory listing in referenceFS (#1433)- allow "=" in webHDF paths (#1428)- fix file mode to consistent "r+b" format (#1426)- pass on kwargs in HTTP glob (#1422)- allow Path in can_be_local and open_local (#1419, #1418)- fix parent for cachedFS (#1413)- "ends" list in _cat_ranges was incorrect (#1402)
Other
- smarter handling of exceptions when doing auto_mkdir (#1406)
2023.10.0---------
Enhancements
- alias "local://" to "file://" (#1381)- get size of file cache (#1377)
Fixes
- stop unexpected kwargs for SMB (#1391)- dos formatting (#1383)
Other
- small optimisations in referenceFS (#1393)- define ordering behaviour for entrypoints (#1389)- style (#1387, 1386, 1385)- add LazyReferenceMapper to API docs (#1378)- add PyPI badge to README (#1376)
2023.9.2--------
Fixes
- revert #1358: auto_mkdir in open() (#1365)
Other
- code style updates (#1373, 1372, 1371, 1370, 1369, 1364)- update CI setup (#1386)
2023.9.1--------
Enhancements
- #1353, save file cache metadata in JSON- #1352, remove some unnecessary list iterations
Fixes
- #1361, re-allow None for default port for SMB- #1360, initialising GUI widget FS with kwargs- #1358, pass auto_mkdir vi url_to_fs again
Other
- #1354, auto delete temp cache directory
2023.9.0--------
Enhancements
- #1346, add ocilake protocol- #1345, implement async-sync and async-async generic cp and rsync- #1344, add lakefs protocol- #1337 add goatcounter to docs- #1323, 1328, add xethub protocol- #1320, in HTTP, check content-encoding when getting length- #1303, add on_error in walk- #1302, add dirfs attribute to mappers- #1293, configure port for smb
Fixes
- #1349, don't reorder paths in bulk ops if source and dest are both lists- #1333, allow mode="x" in get_fs_token_paths- #1324, allow generic to work with complex URLs- #1316, exclude bytes-cache kwargs in url_to_fs- #1314, remote utcnow/utcfromtimestamp- #1311, dirFS's protocol- #1305, use get_file rather than get in file caching- #1295, allow bz2 to be optional
Other
- #1340, 1339, 1329 more bulk ops testing- #1326, 1296 separate out classes in file caching for future enhancements
2023.6.0--------
Enhancements
- #1259, add maxdepth fo cp/get/put- #1263, allow dir modification during walk()- #1264, add boxfs to registry- #1266, optimise referenceFS lazy lookups, especially for writing parquet- #1287, 1288 "encoding" for FTP
Fixes
- #1273, (re)allow reading .zstd reference sets- #1275, resource.error for win32- #1278, range reads in dbfs- #1282, create parent directories in get_file- #1283, off-by-one in reference block writing- #1286, strip protocol in local rm_file
Other
- #1267, async bulk tests- #1268, types and mypy- #1277, 1279, drop outdated forms io.open, IOError
2023.5.0--------
Enhancements
- #1236, allow writing ReferenceFS references directly to parquet
Fixes
- #1255, copy of glob to single output directory- #1254, non-recursive copy of directory (no-op)- #1253, cleanup fix on close of ZIP FS- #1250, ignore dirs when copying list of files- #1249, don't error on register without clobber is registering same thing again- #1245, special case for other_files and relative path
Other
- #1248, add test harness into released wheel package- #1247, docs and tests around common bulk file operations
2023.4.0--------
Enhancements
- #1225, comprehensive docs of expected behaviour of cp/get/put and tests- #1216, test harness for any backend
Fixes
- #1224, small fixes in reference and dask FSs- #1218, mv is no-op when origin and destination are the same- #1217, await in AbstractStreamedFile- #1215, docbuild fixes- #1214, unneeded maxdepth manipulation in expand_path- #1213, pyarros and posixpath related test fixes- #1211, BackgroundBlockCache: keep a block longer if not yet used- #1210, webHDFS: location parameter
Other
- #1241, add HfFileSystem to registry- #1237, register_implementation clobber default changes to False- #1228, "full" and "devel" installation options- #1227, register_cache and reporting collision- #1221, docs about implementations and protocols
2023.3.0--------
Enhancements
- #1201, add directory FS to the registry and constructable from URLs- #1194, allow JSON for setting dict-like kwargs in the config- #1181, give arrow FS proper place in the registry- #1178, add experimental background-thread buffering cache- #1162, make ZipFS writable
Fixes
- #1202, fix on_error="omit" when using caching's cat- #1199, 1163, get/put/cp consistency and empty directories- #1197, 1183 use bytes for setting value on mapper using numpy- #1191, clean up open files in spec get_file- #1164, pass on kwargs correctly to http
Other
- #1186, make seekable=True default for pyarrow files- #1184, 1185, set minimum python version to 3.8
2023.1.0--------
Enhancements
- experimental DFReferenceFileSystem (#1157, 1138)- pyarrow seeking (#1154)- tar thread safety (#1132)- fsid method (#1122)
Fixes
- ReferenceFS order fix (#1158)- fix du and maxdepth (#1128, 1151)- http ranges (#1141)
Other
- coverage on referenceFS (#1133, 1123)- docs (#1152, 1150- remove code duplication in unchain (#1143, 1156, 1121)
2022.11.0---------
Enhancements
- Speed up FSMap._key_to_str (#1101)- Add modified/created to Memory and Arrow (#1096)- Clear expired cache method (#1092)- Allow seekable arrow file (#1091)- Allow append for arrow (#1089)- recursive for sftp.get (#1082)- topdown arg to walk() (#1081)
Fixes
- fix doc warnings (#1106, #1084)- Fix HDFS _strip_protocol (#1103)- Allow URLs with protocol for HDFS (#1099)- yarl in doc deps (#1095)- missing await in genericFS.cp (#1094)- explicit IPv4 for test HTTP server (#1088)- sort when merging ranges for referenceFS (#1087)
Other
- Check that snappy is snappy (#1079)
2022.10.0---------
Enhancements
- referenceFS consolidates reads in the same remote file (#1063)- localfs: add link/symlink/islink (#1059)- asyncfs: make mirroring methods optional (#1054)- local: info: provide st_ino and st_nlink from stat (#1053)- arrow_hdfs replaces hdfs (#1051)- Add read/write_text (#1047)- Add pipe/cat to genericFS (#1038)
Fixes
- SSH write doesn't return number of bytes (#1072)- wrap flush method for LocalFileOpened (#1070)- localfs: fix support for pathlib/os.PathLike objects in rm (#1058)- don't get_file remote FTP directory (#1056)- fix zip write to remote (#1046)- fix zip del following failed init (#1040)
Other
- add asynclocalfs to the registry (#1060)- add DVCFileSystem to the registry (#1049)- add downstream tests (#1037)- Don't auto-close OpenFiles (#1035)
2022.8.2--------
- don't close OpenFile on del (#1035)
2022.8.1--------
- revert #1024 (#1029), with strciter requirements on OpenFile usage
2022.8.0--------
Enhancements
- writable ZipFileSystem (#1017)- make OpenFile behave like files and remove dynamic closer in .open() (#1024)- use isal gunzip (#1008)
Fixes
- remove strip from _parent (#1022)- disallow aiohttp prereleases (#1018)- be sure to close cached file (#1016)- async rm in reverse order (#1014)- expose fileno in LocalFileOpener (#1010, #1005)- remove temp files with simplecache writing (#1006)- azure paths (#1003)- copy dircache keys before iter
2022.7.1--------
Fixes
- Remove fspath from LocalFileOpener (#1005)- Revert 988 (#1003)
2022.7.0--------
Enhancements
- added fsspec-xrootd implementation to registry (#1000)- memory file not to copy bytes (#999)- Filie details passed to FUSE (#972)
Fixes
- Return info for root path of archives (#996)- arbitrary kwargs passed through in pipe_file (#993)- special cases for host in URLs for azure (#988)- unstrip protocol criterion (#980)- HTTPFile serialisation (#973)
Other
- Show erroring path in FileNotFounds (#989)- Reference file info without searching directory tree (#985)- Truncate for local files (#975)
2022.5.0--------
Enhancements
- mutable ReferenceFS (#958)
Fixes
- Make archive FSs not cachable (#966)- glob fixes (#961)- generic copy with unknown size (#959)- zstd open (#956)- empty archive file (#954)- tar chaining (#950, 947)- missing exceptions in mapper (#940)
Other
- update registry (#852)- allow None cache (#942)- mappers to remember init arguments (#939)- cache docstrings (#933)
2022.03.0---------
Enhancements
- tqdm example callback with simple methods (#931, 902)- Allow empty root in get_mapper (#930)- implement real info for reference FS (#919)- list known implementations and compressions (#913)
Fixes
- git branch for testing git backend (#929)- maintain mem FS's root (#926)- kargs to FS in parquet module (#921)- fix on_error in references (#917)- tar ls consistency (#9114)- pyarrow: don't decompress twice (#911)- fix FUSE tests (#905)
2022.02.0---------
Enhancements
- reference FS performance (#892, 900)- directory/prefix FS (#745)
Fixes
- FUSE (#905, 891)- iteration in threads (#893)- OpenFiles slicing (#887)
Other
- drop py36 (#889, 901)
2022.01.0---------
Fixes
- blocks cache metadata (#746)- default SMB port (#853)- caching fixes (#856, 855)- explicit close for http files (#866)- put_file to continue when no bytes (#869, 870)
Other
- temporary files location (#851, 871)- async abstract methods (#858, 859, 860)- md5 for FIPS (#872)- remove deprecated pyarrow/distutils (#880, 881)
2021.11.1---------
Enhancements
- allow compression for fs.open (#826)- batch more async operations (#824)- allow github backend for alternate URL (#815)- speec up reference filesystem (#811)
Fixes
- fixes for parquet functionality (#821, 817)- typos and docs (#839, 833, 816)- local root (#829)
Other
- remove BlockSizeError for http (#830)
2021.11.0---------
Enhancement
- parquet-specific module and cache type (#813, #806)
Fixes
- empty ranges (#802, 801, 803)- doc typos (#791, 808)- entrypoints processing (#784)- cat in ZIP (#789)
Other
- move to fsspec org- doc deps (#786, 791)
2021.10.1---------
Fixes
- Removed inaccurate ``ZipFileSystem.cat()`` override so that the base class' version is used (#789)- fix entrypoint processing (#784)- case where no blocks of a block-cache have yet been loaded (#801)- don't fetch empty ranges (#802, 803)
Other
- simplify doc deps (#786, 791)
2021.10.0---------
Fixes
- only close http connector if present (#779)- hdfs strip protocol (#778)- fix filecache with check_files (#772)- put_file to use _parent (#771)
Other
- add kedro link (#781)
2021.09.0---------
Enhancement
- http put from file-like (#764)- implement webhdfs cp/rm_file (#762)- multiple (and concurrent) cat_ranges (#744)
Fixes
- sphinx warnings (#769)- lexists for links (#757)- update versioneer (#750)- hdfs updates (#749)- propagate async timeout error (#746)- fix local file seekable (#743)- fix http isdir when does not exist (#741)
Other
- ocifs, arrow added (#754, #765)- promote url_to_fs to top level (#753)
2021.08.1---------
Enhancements
- HTTP get_file/put_file APIs now support callbacks (#731)- New HTTP put_file method for transferring data to the remote server (chunked) (#731)- Customizable HTTP client initializers (through passing ``get_client`` argument) (#731, #701)- Support for various checksum / fingerprint headers in HTTP ``info()`` (#731)- local implementation of rm_file (#736)- local speed improvements (#711)- sharing options in SMB (#706)- streaming cat/get for ftp (#700)
Fixes
- check for remote directory when putting (#737)- storage_option update handling (#734(- await HTTP call before checking status (#726)- ftp connect (#722)- bytes conversion of times in mapper (#721)- variable overwrite in WholeFileCache cat (#719)- http file size again (#718)- rm and create directories in ftp (#716, #703)- list of files in async put (#713)- bytes to dict in cat (#710)
2021.07.0---------
Enhancements
- callbacks (#697)
2021.06.1---------
Enhancements
- Introduce ``fsspec.asyn.fsspec_loop`` to temporarily switch to the fsspec loop. (#671)- support list for local rm (#678)
Fixes
- error when local mkdir twice (#679)- fix local info regression for pathlike (#667)
Other
- link to wandbfs (#664)
2021.06.0---------
Enhancements
- Better testing and folder handling for Memory (#654)- Negative indexes for cat_file (#653)- optimize local file listing (#647)
Fixes
- FileNoteFound in http and range exception subclass (#649, 646)- async timeouts (#643, 645)- stringify path for pyarrow legacy (#630)
Other
- The ``fsspec.asyn.get_loop()`` will always return a loop of a selector policy (#658)- add helper to construct Range headers for cat_file (#655)
2021.05.0---------
Enhancements
- Enable listings cache for HTTP filesystem (#560)- Fold ZipFileSystem and LibArchiveFileSystem into a generic implementation and add new TarFileSystem (#561)- Use throttling for the ``get``/``put`` methods of ``AsyncFileSystem`` (#629)- rewrite for archive filesystems (#624)- HTTP listings caching (#623)
Fixes
- gcsfs tests (#638)- stringify_path for arrow (#630)
Other
- s3a:// alias
2021.04.0---------
Major changes
- calendar versioning
Enhancements
- better link and size finding for HTTP (#610, %99)- link following in Local (#608)- ReferenceFileSystem dev (#606, #604, #602)
Fixes
- drop metadata dep (#605)
0.9.0-----
Major Changes:
- avoid nested sync calls by copying code (#581, #586, docs #593)- release again for py36 (#564, #575)
Enhancements:
- logging in mmap cacher, explicitly close files (#559)- make LocalFileOpener an IOBase (#589)- better reference file system (#568, #582, #584, #585)- first-chunk cache (#580)- sftp listdir (#571)- http logging and fetch all (#551, #558)- doc: entry points (#548)
Fixes:
- get_mapper for caching filesystems (#559)- fix cross-device file move (#547)- store paths without trailing "/" for DBFS (#557)- errors that happen on ``_initiate_upload`` when closing the ``AbstractBufferedFile`` will now be propagated (#587)- infer_compressions with upper case suffix ($595)- file initialiser errors (#587)- CI fix (#563)- local file commit cross-device (#547)
Version 0.8.7-------------
Fixes:
- fix error with pyarrow metadata for some pythons (#546)
Version 0.8.6-------------
Features:
- Add dbfs:// support (#504, #514)
Enhancements
- don't import pyarrow (#503)- update entry points syntax (#515)- ci precommit hooks (#534)
Fixes:
- random appending of a directory within the filesystems ``find()`` method (#507, 537)- fix git tests (#501)- fix recursive memfs operations (#502)- fix recursive/maxdepth for cp (#508)- fix listings cache timeout (#513)- big endian bytes tests (#519)- docs syntax (#535, 524, 520, 542)- transactions and reads (#533)
Version 0.8.5-------------
Features:
- config system- libarchive implementation- add reference file system implementation
Version 0.8.4-------------
Features:
- function ``can_be_local`` to see whether URL is compatible with ``open_local``- concurrent cat with filecaches, if backend supports it- jupyter FS
Fixes:
- dircache expiry after transaction- blockcache garbage collection- close for HDFS- windows tests- glob depth with "**"
Version 0.8.3-------------
Features:
- error options for cat- memory fs created time in detailed ``ls```
Fixes:
- duplicate directories could appear in MemoryFileSystem- Added support for hat dollar lbrace rbrace regex character escapes in glob- Fix blockcache (was doing unnecessary work)- handle multibyte dtypes in readinto- Fix missing kwargs in call to _copy in asyn
Other:
- Stop inheriting from pyarrow.filesystem for pyarrow>=2.0- Raise low-level program friendly OSError.- Guard against instance reuse in new processes- Make hash_name a method on CachingFileSystem to make it easier to change.- Use get_event_loop for py3.6 compatibility
Version 0.8.2-------------
Fixes:
- More careful strip for caching
Version 0.8.1-------------
Features:
- add sign to base class- Allow calling of coroutines from normal code when running async- Implement writing for cached many files- Allow concurrent caching of remote files- Add gdrive:// protocol
Fixes:
- Fix memfs with exact ls- HTTPFileSystem requires requests and aiohttp in registry
Other:
- Allow http kwargs to clientSession- Use extras_require in setup.py for optional dependencies- Replacing md5 with sha256 for hash (CVE req)- Test against Python 3.8, drop 3.5 testing- add az alias for abfs
Version 0.8.0-------------
Major release allowing async implementations with concurrent batchoperations.
Features:
- async filesystem spec, first applied to HTTP- OpenFiles cContext for multiple files- Document async, and ensure docstrings- Make LocalFileOpener iterable- handle smb:// protocol using smbprotocol package- allow Path object in open- simplecache write mode
Fixes:
- test_local: fix username not in home path- Tighten cacheFS if dir deleted- Fix race condition of lzma import when using threads- properly rewind MemoryFile- OpenFile newline in reduce
Other:
- Add aiobotocore to deps for s3fs check- Set default clobber=True on impl register- Use _get_kwargs_from_url when unchaining- Add cache_type and cache_options to HTTPFileSystem constructor
Version 0.7.5-------------
* async implemented for HTTP as prototype (read-only)* write for simplecache* added SMB (Samba, protocol >=2) implementation
Version 0.7.4-------------
* panel-based GUI
0.7.3 series------------
* added ``git`` and ``github`` interfaces* added chained syntax for open, open_files and get_mapper* adapt webHDFS for HttpFS* added open_local* added ``simplecache``, and compression to both file caches
Version 0.6.2-------------
* Added ``adl`` and ``abfs`` protocols to the known implementations registry (:pr:`209`)* Fixed issue with whole-file caching and implementations providing multiple protocols (:pr:`219`)
Version 0.6.1-------------
* ``LocalFileSystem`` is now considered a filestore by pyarrow (:pr:`211`)* Fixed bug in HDFS filesystem with ``cache_options`` (:pr:`202`)* Fixed instance caching bug with multiple instances (:pr:`203`)
Version 0.6.0-------------
* Fixed issues with filesystem instance caching. This was causing authorization errors in downstream libraries like ``gcsfs`` and ``s3fs`` in multi-threaded code (:pr:`155`, :pr:`181`)* Changed the default file caching strategy to :class:`fsspec.caching.ReadAheadCache` (:pr:`193`)* Moved file caches to the new ``fsspec.caching`` module. They're still available from their old location in ``fsspec.core``, but we recommend using the new location for new code (:pr:`195`)* Added a new file caching strategy, :class:`fsspec.caching.BlockCache` for fetching and caching file reads in blocks (:pr:`191`).* Fixed equality checks for file system instance to return ``False`` when compared to objects other than file systems (:pr:`192`)* Fixed a bug in ``fsspec.FSMap.keys`` returning a generator, which was consumed upon iteration (:pr:`189`).* Removed the magic addition of aliases in ``AbstractFileSystem.__init__``. Now alias methods are always present (:pr:`177`)* Deprecated passing ``trim`` to :class:`fsspec.spec.AbstractBufferedFile`. Pass it in ``storage_options`` instead (:pr:`188`)* Improved handling of requests for :class:`fsspec.implementations.http.HTTPFileSystem` when the HTTP server responds with an (incorrect) content-length of 0 (:pr:`163`)* Added a ``detail=True`` parameter to :meth:`fsspec.spec.AbstractFileSystem.ls` (:pr:`168`)* Fixed handling of UNC/DFS paths (:issue:`154`)
.. raw:: html
<script data-goatcounter="https://fsspec.goatcounter.com/count" async src="//gc.zgo.at/count.js"></script>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126Code of Conduct===============
All participants in the fsspec community are expected to adhere to a Code of Conduct.
As contributors and maintainers of this project, and in the interest offostering an open and welcoming community, we pledge to respect all people whocontribute through reporting issues, posting feature requests, updatingdocumentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-freeexperience for everyone, treating everyone as unique humans deserving ofrespect.
Examples of unacceptable behaviour by participants include:
- The use of sexualized language or imagery- Personal attacks- Trolling or insulting/derogatory comments- Public or private harassment- Publishing other's private information, such as physical or electronic addresses, without explicit permission- Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, orreject comments, commits, code, wiki edits, issues, and other contributionsthat are not aligned to this Code of Conduct, or to ban temporarily orpermanently any contributor for other behaviours that they deem inappropriate,threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselvesto fairly and consistently applying these principles to every aspect ofmanaging this project. Project maintainers who do not follow or enforcethe Code of Conduct may be permanently removed from the project team.
This code of conduct applies both within project spaces and in publicspaces when an individual is representing the project or its community.
If you feel the code of conduct has been violated, please report theincident to the fsspec core team.
Reporting---------
If you believe someone is violating theCode of Conduct we ask that you report itto the Project by emailing community@anaconda.com. All reports will be keptconfidential. In some cases we may determine that a public statement will needto be made. If that's the case, the identities of all victims and reporterswill remain confidential unless those individuals instruct us otherwise.If you believe anyone is in physical danger, please notify appropriate lawenforcement first.
In your report please include:
- Your contact info- Names (real, nicknames, or pseudonyms) of any individuals involved. If there were other witnesses besides you, please try to include them as well.- When and where the incident occurred. Please be as specific as possible.- Your account of what occurred. If there is a publicly available record please include a link.- Any extra context you believe existed for the incident.- If you believe this incident is ongoing.- If you believe any member of the core team has a conflict of interest in adjudicating the incident.- What, if any, corrective response you believe would be appropriate.- Any other information you believe we should have.
Core team members are obligated to maintain confidentiality with regardto the reporter and details of an incident.
What happens next?~~~~~~~~~~~~~~~~~~
You will receive an email acknowledging receipt of your complaint.The core team will immediately meet to review the incident and determine:
- What happened.- Whether this event constitutes a code of conduct violation.- Who the bad actor was.- Whether this is an ongoing situation, or if there is a threat to anyone's physical safety.- If this is determined to be an ongoing incident or a threat to physical safety, the working groups' immediate priority will be to protect everyone involved.
If a member of the core team is one of the named parties, they will not beincluded in any discussions, and will not be provided with any confidentialdetails from the reporter.
If anyone on the core team believes they have a conflict of interest inadjudicating on a reported issue, they will inform the other core teammembers, and exempt themselves from any discussion about the issue.Following this declaration, they will not be provided with any confidentialdetails from the reporter.
Once the working group has a complete account of the events they will make adecision as to how to response. Responses may include:
- Nothing (if we determine no violation occurred).- A private reprimand from the working group to the individual(s) involved.- A public reprimand.- An imposed vacation- A permanent or temporary ban from some or all spaces (GitHub repositories, etc.)- A request for a public or private apology.
We'll respond within one week to the person who filed the report with either aresolution or an explanation of why the situation is not yet resolved.
Once we've determined our final action, we'll contact the original reporterto let them know what action (if any) we'll be taking. We'll take into accountfeedback from the reporter on the appropriateness of our response, but wedon't guarantee we'll act on it.
Acknowledgement---------------
This CoC is modified from the one by `BeeWare`_, which in turn refers tothe `Contributor Covenant`_ and the `Django`_ project.
.. _BeeWare: https://beeware.org/community/behavior/code-of-conduct/.. _Contributor Covenant: https://www.contributor-covenant.org/version/1/3/0/code-of-conduct/.. _Django: https://www.djangoproject.com/conduct/reporting/
.. raw:: html
<script data-goatcounter="https://projspec.goatcounter.com/count" async src="//gc.zgo.at/count.js"></script>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193# fsspec documentation build configuration file, created by# sphinx-quickstart on Mon Jan 15 18:11:02 2018.## This file is execfile()d with the current directory set to its# containing dir.## Note that not all possible configuration values are present in this# autogenerated file.## All configuration values have a default; values that are commented out# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,# add these directories to sys.path here. If the directory is relative to the# documentation root, use os.path.abspath to make it absolute, like shown here.#import osimport sys
sys.path.insert(0, os.path.abspath("../.."))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.## needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom# ones.extensions = [ "sphinx.ext.autodoc", "sphinx.ext.viewcode", "sphinx.ext.autosummary", "sphinx.ext.extlinks", "numpydoc", "sphinx_design",]
numpydoc_show_class_members = False
# Add any paths that contain templates here, relative to this directory.templates_path = ["_templates"]
# The suffix(es) of source filenames.# You can specify multiple suffix as a list of string:## source_suffix = ['.rst', '.md']source_suffix = ".rst"
# The master toctree document.master_doc = "index"
# General information about the project.project = "fsspec"copyright = "2018, Martin Durant"author = "Martin Durant"
# The version info for the project you're documenting, acts as replacement for# |version| and |release|, also used in various other places throughout the# built documents.## The short X.Y version.
import fsspec
version = fsspec.__version__# The full version, including alpha/beta/rc tags.release = fsspec.__version__
# List of patterns, relative to source directory, that match files and# directories to ignore when looking for source files.# This patterns also effect to html_static_path and html_extra_pathexclude_patterns = []
# The name of the Pygments (syntax highlighting) style to use.pygments_style = "sphinx"
# If true, `todo` and `todoList` produce output, else they produce nothing.todo_include_todos = False
default_role = "py:obj"autodoc_mock_imports = [ "aiohttp", "dask", "distributed", "fuse", "libarchive", "panel", "paramiko", "pyarrow", "pygit2", "requests", "smbprotocol", "smbclient",]
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for# a list of builtin themes.#html_theme = "sphinx_rtd_theme"
# Theme options are theme-specific and customize the look and feel of a theme# further. For a list of options available for each theme, see the# documentation.## html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,# relative to this directory. They are copied after the builtin static files,# so a file named "default.css" will overwrite the builtin "default.css".html_static_path = ["_static"]
# Custom sidebar templates, must be a dictionary that maps document names# to template names.## This is required for the alabaster theme# refs: https://alabaster.readthedocs.io/en/latest/installation.html#sidebarshtml_sidebars = { "**": [ "relations.html", # needs 'show_related': True theme option to display "searchbox.html", ]}
# Custom CSS file to override read the docs default CSS.# Contains workaround for issue #790.html_css_files = ["custom.css"]
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.htmlhelp_basename = "fsspecdoc"
# -- Options for LaTeX output ---------------------------------------------
latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp',}
# Grouping the document tree into LaTeX files. List of tuples# (source start file, target name, title,# author, documentclass [howto, manual, or own class]).latex_documents = [ (master_doc, "fsspec.tex", "fsspec Documentation", "Joseph Crail", "manual")]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples# (source start file, name, description, authors, manual section).man_pages = [(master_doc, "fsspec", "fsspec Documentation", [author], 1)]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples# (source start file, target name, title, author,# dir menu entry, description, category)texinfo_documents = [ ( master_doc, "fsspec", "fsspec Documentation", author, "fsspec", "One line description of project.", "Miscellaneous", )]
extlinks = { "issue": ("https://github.com/fsspec/filesystem_spec/issues/%s", "GH#%s"), "pr": ("https://github.com/fsspec/filesystem_spec/pull/%s", "GH#%s"),}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348Copying files and directories=============================
This documents the expected behavior of the ``fsspec`` file and directory copying functions.There are three functions of interest here: :meth:`~fsspec.spec.AbstractFileSystem.copy`,:meth:`~fsspec.spec.AbstractFileSystem.get` and :meth:`~fsspec.spec.AbstractFileSystem.put`.Each of these copies files and/or directories from a ``source`` to a ``target`` location.If we refer to our filesystem of interest, derived from :class:`~fsspec.spec.AbstractFileSystem`,as the remote filesystem (even though it may be local) then the difference between the threefunctions is:
- :meth:`~fsspec.spec.AbstractFileSystem.copy` copies from a remote ``source`` to a remote ``target`` - :meth:`~fsspec.spec.AbstractFileSystem.get` copies from a remote ``source`` to a local ``target`` - :meth:`~fsspec.spec.AbstractFileSystem.put` copies from a local ``source`` to a remote ``target``
The ``source`` and ``target`` are the first two arguments passed to these functions, and eachconsists of one or more files, directories and/or ``glob`` (wildcard) patterns.The behavior of the ``fsspec`` copy functions is intended to be the same as that obtained usingPOSIX command line ``cp`` but ``fsspec`` functions have extra functionality because:
- They support more than one ``target`` whereas command line ``cp`` is restricted to one. - They can create new directories, either automatically or via the ``auto_mkdir=True`` keyword argument, whereas command line ``cp`` only does this as part of a recursive copy.
Expected behavior-----------------
There follows a comprehensive list of the expected behavior of the ``fsspec`` copying functionsthat also forms the basis of a set of tests that all classes that derive from:class:`~fsspec.spec.AbstractFileSystem` can be tested against to check that they conform.For all scenarios the ``source`` filesystem contains the following directories and files::
📁 source ├── 📄 file1 ├── 📄 file2 └── 📁 subdir ├── 📄 subfile1 ├── 📄 subfile2 └── 📁 nesteddir └── 📄 nestedfile
and before each scenario the ``target`` directory exists and is empty unless otherwise noted::
📁 target
All example code uses :meth:`~fsspec.spec.AbstractFileSystem.cp` which is an alias of:meth:`~fsspec.spec.AbstractFileSystem.copy`; equivalent behavior is expected by:meth:`~fsspec.spec.AbstractFileSystem.get` and :meth:`~fsspec.spec.AbstractFileSystem.put`.Forward slashes are used for directory separators throughout.
1. Single source to single target---------------------------------
.. dropdown:: 1a. File to existing directory
.. code-block:: python
cp("source/subdir/subfile1", "target/")
results in::
📁 target └── 📄 subfile1
The trailing slash on ``"target/"`` is optional but recommended as it explicitly indicates that the target is a directory.
.. dropdown:: 1b. File to new directory
.. code-block:: python
cp("source/subdir/subfile1", "target/newdir/")
results in::
📁 target └── 📁 newdir └── 📄 subfile1
This fails if the ``target`` file system is not capable of creating the directory, for example if it is write-only or if ``auto_mkdir=False``. There is no command line equivalent of this scenario without an explicit ``mkdir`` to create the new directory.
The trailing slash is required on the new directory otherwise it is interpreted as a filename which is a different scenario (1d. File to file in new directory).
.. dropdown:: 1c. File to file in existing directory
.. code-block:: python
cp("source/subdir/subfile1", "target/newfile")
results in::
📁 target └── 📄 newfile
The target cannot have a trailing slash as ``"newfile/"`` is interpreted as a new directory which is a different scenario (1b. File to new directory).
.. dropdown:: 1d. File to file in new directory
.. code-block:: python
cp("source/subdir/subfile1", "target/newdir/newfile")
creates the new directory and copies the file into it::
📁 target └── 📁 newdir └── 📄 newfile
This fails if the ``target`` file system is not capable of creating the directory, for example if it is write-only or if ``auto_mkdir=False``. There is no command line equivalent of this scenario without an explicit ``mkdir`` to create the new directory.
If there is a trailing slash on the target ``target/newdir/newfile/`` then it is interpreted as a new directory which is a different scenario (1b. File to new directory).
.. dropdown:: 1e. Directory to existing directory
.. code-block:: python
cp("source/subdir/", "target/", recursive=True)
results in::
��� target ├── 📄 subfile1 └── 📄 subfile2 └── 📁 nesteddir └── 📄 nestedfile
The ``recursive=True`` keyword argument is required otherwise the call does nothing. The depth of recursion can be controlled using the ``maxdepth`` keyword argument, for example:
.. code-block:: python
cp("source/subdir/", "target/", recursive=True, maxdepth=1)
results in::
📁 target ├── 📄 subfile1 └── 📄 subfile2
The trailing slash on ``"target/"`` is optional but recommended as it explicitly indicates that the target is a directory.
If the trailing slash is omitted from ``"source/subdir"`` then the ``subdir`` is also copied, not just its contents:
.. code-block:: python
cp("source/subdir", "target/", recursive=True)
results in::
📁 target └── 📁 subdir ├── 📄 subfile1 └── 📄 subfile2 └── 📁 nesteddir └── 📄 nestedfile
Again the depth of recursion can be controlled using the ``maxdepth`` keyword argument, for example:
.. code-block:: python
cp("source/subdir", "target/", recursive=True, maxdepth=1)
results in::
📁 target └── 📁 subdir ├── 📄 subfile1 └── 📄 subfile2
.. dropdown:: 1f. Directory to new directory
.. code-block:: python
cp("source/subdir/", "target/newdir/", recursive=True)
results in::
📁 target └── 📁 newdir ├── 📄 subfile1 └── 📄 subfile2 └── 📁 nesteddir └── 📄 nestedfile
Trailing slashes on both ``source`` and ``target`` are optional and do not affect the result. They are recommended to explicitly indicate both are directories.
The ``recursive=True`` keyword argument is required otherwise the call does nothing. The depth of recursion can be controlled using the ``maxdepth`` keyword argument, for example:
.. code-block:: python
cp("source/subdir/", "target/newdir/", recursive=True, maxdepth=1)
results in::
📁 target └── 📁 newdir ├── 📄 subfile1 └── 📄 subfile2
.. dropdown:: 1g. Glob to existing directory
Nonrecursive
.. code-block:: python
cp("source/subdir/*", "target/")
copies files from the top-level directory only and results in::
📁 target ├── 📄 subfile1 └── 📄 subfile2
Recursive
.. code-block:: python
cp("source/subdir/*", "target/", recursive=True)
results in::
📁 target ├── 📄 subfile1 └── 📄 subfile2 └── 📁 nesteddir └── 📄 nestedfile
The trailing slash on ``"target/"`` is optional but recommended as it explicitly indicates that the target is a directory.
The depth of recursion can be controlled by the ``maxdepth`` keyword argument, for example:
.. code-block:: python
cp("source/subdir/*", "target/", recursive=True, maxdepth=1)
results in::
📁 target ├── 📄 subfile1 └── 📄 subfile2
.. dropdown:: 1h. Glob to new directory
Nonrecursive
.. code-block:: python
cp("source/subdir/*", "target/newdir/")
copies files from the top-level directory only and results in::
📁 target └── 📁 newdir ├── 📄 subfile1 └── 📄 subfile2
Recursive
.. code-block:: python
cp("source/subdir/*", "target/newdir/", recursive=True)
results in::
📁 target └── 📁 newdir ├── 📄 subfile1 └── 📄 subfile2 └── 📁 nesteddir └── 📄 nestedfile
The trailing slash on the ``target`` is optional but recommended as it explicitly indicates that it is a directory.
The depth of recursion can be controlled by the ``maxdepth`` keyword argument, for example:
.. code-block:: python
cp("source/subdir/*", "target/newdir/", recursive=True, maxdepth=1)
results in::
📁 target └── 📁 newdir ├── 📄 subfile1 └── 📄 subfile2
These calls fail if the ``target`` file system is not capable of creating the directory, for example if it is write-only or if ``auto_mkdir=False``. There is no command line equivalent of this scenario without an explicit ``mkdir`` to create the new directory.
2. Multiple source to single target-----------------------------------
.. dropdown:: 2a. List of files to existing directory
.. code-block:: python
cp(["source/file1", "source/file2", "source/subdir/subfile1"], "target/")
results in::
📁 target ├── 📄 file1 ├── 📄 file2 └── 📄 subfile1
All of the files are copied to the target directory regardless of their relative paths in the source filesystem. The trailing slash on the ``target`` is optional but recommended as it explicitly indicates that it is a directory.
.. dropdown:: 2b. List of files to new directory
.. code-block:: python
cp(["source/file1", "source/file2", "source/subdir/subfile1"], "target/newdir/")
results in::
📁 target └── 📁 newdir ├── 📄 file1 ├── 📄 file2 └── 📄 subfile1
All of the files are copied to the target directory regardless of their relative paths in the source filesystem.
The trailing slash is required on the new directory otherwise it is interpreted as a filename rather than a directory.
.. raw:: html
<script data-goatcounter="https://fsspec.goatcounter.com/count" async src="//gc.zgo.at/count.js"></script>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130Developing with fsspec----------------------
Whereas the majority of the documentation describes the use of ``fsspec``from the end-user's point of view, ``fsspec`` is used by many librariesas the primary/only interface to file operations.
Clients of the library~~~~~~~~~~~~~~~~~~~~~~
The most common entrance point for libraries which wish to rely on ``fsspec``will be ``open`` or ``open_files``, as a way of generating an object compatiblewith the python file interface. This actually produces an ``OpenFile`` instance,which can be serialised across a network, and resources are only engaged whenentering a context, e.g.
.. code-block:: python
with fsspec.open("protocol://path", 'rb', param=value) as f: process_file(f)
Note the backend-specific parameters that can be passed in this call.
In cases where the caller wants to control the context directly, they can use the``open`` method of the ``OpenFile``, or get the filesystem object directly,skipping the ``OpenFile`` route. In the latter case, text encoding and compressionare **not** handled for you. The file-like object can also be used as a contextmanager, or the ``close()`` method must be called explicitly to release resources.
.. code-block:: python
# OpenFile route of = fsspec.open("protocol://path", 'rb', param=value) f = of.open() process_file(f) f.close()
# filesystem class route, context fs = fsspec.filesystem("protocol", param=value) with fs.open("path", "rb") as f: process_file(f)
# filesystem class route, explicit close fs = fsspec.filesystem("protocol", param=value) f = fs.open("path", "rb") process_file(f) f.close()
Implementing a backend~~~~~~~~~~~~~~~~~~~~~~
The class ``AbstractFileSystem`` provides a template of the methodsthat a potential implementation should supply, as well as defaultimplementation of functionality that depends on these. Methods that*could* be implemented are marked with ``NotImplementedError`` or``pass`` (the latter specifically for directory operations that mightnot be required for some backends where directories are emulated.
Note that not all of the methods need to be implemented: for example,some implementations may be read-only, in which case things like ``pipe``,``put``, ``touch``, ``rm``, etc., can be left as not-implemented(or you might implement them and raise PermissionError, OSError 30 or someread-only exception).
We may eventually refactor ``AbstractFileSystem`` to split the default implementation,the set of methods that you might implement in a new backend, and thedocumented end-user API.
In order to register a new backend with fsspec, new backends should registerthemselves using the `entry_points <https://setuptools.readthedocs.io/en/latest/userguide/quickstart.html#entry-points-and-automatic-script-creation>`_facility from setuptools. In particular, if you want to register a newfilesystem protocol ``myfs`` which is provided by the ``MyFS`` class inthe ``myfs`` package, add the following to your ``setup.py``:
.. code-block:: python
setuptools.setup( ... entry_points={ 'fsspec.specs': [ 'myfs=myfs.MyFS', ], }, ... )
Alternatively, the previous method of registering a new backend can be used.That is, new backends must register themselves on import(``register_implementation``) or post a PR to the ``fsspec`` repoasking to be included in ``fsspec.registry.known_implementations``.
Implementing async~~~~~~~~~~~~~~~~~~
Starting in version 0.7.5, we provide async operations for some methodsof some implementations. Async support in storage implementations isoptional. Special considerations are required for asyncdevelopment, see :doc:`async`.
Developing the library~~~~~~~~~~~~~~~~~~~~~~
The following can be used to install ``fsspec`` in development mode
.. code-block::
git clone https://github.com/fsspec/filesystem_spec cd filesystem_spec pip install -e .[dev,doc,test]
A number of additional dependencies are required to run tests in full, see "ci/environment*.yml", aswell as Docker. Most implementation-specific tests should skip if their requirements arenot met.
Development happens by submitting pull requests (PRs) on github.This repo uses Ruff for Python linting and formatting. Run ``ruff check fsspec``and ``ruff format --check fsspec`` from the repository root to check your changes.Run ``ruff format fsspec`` to apply formatting. You may wish to installthe project's commit hooks with ``pre-commit install --install-hooks``, aslinting is done as part of the CI. Run ``pre-commit run --all-files`` to run allconfigured hooks without making a commit.
Docs use sphinx and the numpy docstring style. Please add an entry to the changelogalong with any PR.
.. raw:: html
<script data-goatcounter="https://fsspec.goatcounter.com/count" async src="//gc.zgo.at/count.js"></script>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470Features of fsspec==================
Here follows a brief description of some features of note of ``fsspec`` that provides to makeit an interesting project beyond some other file-system abstractions.
Serialisability---------------
Coming out of the Dask stable, it was an important design decision that file-system instancesbe serialisable, so that they could be created in one process (e.g., the client) and used inother processes (typically the workers). These other processes may even be on other machines,so in many cases they would need to be able to re-establish credentials, ideally without passingsensitive tokens in the pickled binary data.
``fsspec`` instances, generally speaking, abide by these rules, do not include locks, files and otherthread-local material, and where possible, use local credentials (such as a token file)for re-establishing sessions upon de-serialisation. (While making use of cached instances, wherethey exist, see below).
``OpenFile`` instances----------------------
The :func:`fsspec.core.OpenFile` class provides a convenient way to prescribe the manner toopen some file (local,remote, in a compressed store, etc.) which is portable, and can also apply any compression andtext-mode to the file. These instances are also serialisable, because they do not contain any openfiles.
The way to work with ``OpenFile`` s is to isolate interaction with in a ``with`` context. It isthe initiation of the context which actually does the work of creating file-like instances.
.. code-block:: python
of = fsspec.open(url, ...) # of is just a place-holder with of as f: # f is now a real file-like object holding resources f.read(...)
File Buffering and random access--------------------------------
Most implementations create file objects which derive from ``fsspec.spec.AbstractBufferedFile``, andhave many behaviours in common. A subclass of ``AbstractBufferedFile`` providesrandom access for the underlying file-like data (without downloading the whole thing).This is a critical feature in the big-data access model, where each sub-task of an operationmay need on a small part of a file, and does not, therefore want to be forced into downloading thewhole thing.
These files offer buffering of both read and write operations, so thatcommunication with the remote resource is limited. The size of the buffer is generally configuredwith the ``blocksize=`` kwarg at open time, although the implementation may have some minimum ormaximum sizes that need to be respected.
For reading, a number of buffering schemes are available, listed in ``fsspec.caching.caches``(see :ref:`readbuffering`), or "none" for no buffering at all, e.g., for a simple read-aheadbuffer, you can do
.. code-block:: python
fs = fsspec.filesystem(...) with fs.open(path, mode='rb', cache_type='readahead') as f: use_for_something(f)
Transparent text-mode and compression-------------------------------------
As mentioned above, the ``OpenFile`` class allows for the opening of files on a binary store,which appear to be in text mode and/or allow for a compression/decompression layer between thecaller and the back-end storage system. The list of ``fsspec`` supported codeccan be retrieved using :func:`fsspec.available_compressions`.From the user's point of view, this is achieved simply by passing arguments tothe :func:`fsspec.open_files` or :func:`fsspec.open` functions, andthereafter happens transparently.
Key-value stores----------------
File-systems are naturally like dict-like key-value mappings: each (string) path corresponds to somebinary data on the storage back-end. For some use-cases, it is very convenient to be able toview some path within the file-system as a dict-like store, and the function :func:`fsspec.get_mapper`gives a one-stop way to return such an object. This has become useful, for example, in thecontext of the `zarr`_ project, which stores it array chunks in keys in any arbitrary mapping-likeobject.
.. code-block:: python
mapper = fsspec.get_mapper('protocol://server/path', args) list(mapper) mapper[k] = b'some data'
.. _zarr: https://zarr.readthedocs.io/en/stable/
PyArrow integration-------------------
`pyarrow`_ has its own internal idea of what a file-system is (``pyarrow.fs.FileSystem``),and some functions, particularly the loading of parquet, require that the target be compatible.As it happens, the design of the file-system interface in ``pyarrow`` *is* compatible with ``fsspec``(this is not by accident).
At import time, ``fsspec`` checks for the existence of ``pyarrow``, and, if ``pyarrow < 2.0`` isfound, adds its base filesystem to the superclasses of the spec base-class.For ``pyarrow >= 2.0``, ``fsspec`` file systems can simply be passed to ``pyarrow`` functionsthat expect ``pyarrow`` filesystems, and ``pyarrow`` `will automatically wrap them<https://arrow.apache.org/docs/python/filesystems.html#using-fsspec-compatible-filesystems>`_.
In this manner, all ``fsspec``-derived file-systems are also ``pyarrow`` file-systems, and can be usedby ``pyarrow`` functions.
.. _pyarrow: https://arrow.apache.org/docs/python/
Transactions------------
``fsspec`` supports *transactions*, during which writing to files on a remote store is deferred(typically put into a temporary location) until the transaction is over, whereupon the wholetransaction is finalised in a semi-atomic way, and all the files are moved/committed to theirfinal destination. The implementation of the details is file-system specific (and not allsupport it yet), but the idea is,that all files should get written or none, to mitigate against data corruption. The featurecan be used like
.. code-block:: python
fs = fsspec.filesystem(...) with fs.transaction: with fs.open('file1', 'wb') as f: f.write(b'some data') with fs.open('file2', 'wb') as f: f.write(b'more data')
Here, files 1 and 2 do not get moved to the target location until the transaction context finishes.If the context finishes due to an (uncaught) exception, then the files are discarded and thefile target locations untouched.
The class :func:`fsspec.spec.Transaction` allows for fine-tuning of the operation, and every``fsspec`` instance has an instance of this as an attribute ``.transaction`` to give access.
Note that synchronising transactions across multiple instances, perhaps across a cluster,is a harder problem to solve, and the implementation described here is only part of the solution.
Mount anything with FUSE------------------------
Any path of any file-system can be mapped to a local directory using `fusepy <https://pypi.org/project/fusepy/>`_ and:func:`fsspec.fuse.run`. This feature is experimental, but basic file listing withdetails, and read/write should generally be available to the extent that theremote file-system provides enough information. Naturally, if a file-system is read-only,then write operations will fail - but they will tend to fail late and with obscureerror messages such as "bad address".
Some specific quirks of some file-systems may cause confusion for FUSE. For example,it is possible for a given path on s3 to be both a valid key (i.e., containing binarydata, like a file) and a valid prefix (i.e., can be listed to find subkeys, like adirectory). Since this breaks the assumptions of a normal file-system, it may notbe possible to reach all paths on the remote.
Instance Caching----------------
If a file-system implementation class is marked as *cachable* (attribute ``.cachable``),then its instances willget stored in a class attribute, to enable quick look-up instead of needing to regeneratepotentially expensive connections and sessions. They key in the cache is a tokenisation ofthe arguments to create the instance. The cache itself (attribute ``._cache``)is currently a simple dict, but could in the future be LRU, or something more complicated,to fine-tune instance lifetimes.
Since files can hold on to write caches and read buffers,the instance cache may cause excessive memory usage in some situations; but normally, files'``close`` methods will be called, discarding the data. Only when there is also an unfinalised transaction orcaptured traceback might this be anticipated becoming a problem.
To disable instance caching, i.e., get a fresh instance which is not in the cacheeven for a cachable class, pass ``skip_instance_cache=True``.
Memory filesystems------------------
Memory filesystem instances share their files and directories by default anduse the normal instance cache. To create independent stores, pass``global_store=False, skip_instance_cache=True`` and retain the instance forsubsequent operations. Without ``skip_instance_cache=True``, the normal instancecache applies: repeated calls with the same arguments reuse the same instanceand its store:
.. code-block:: python
first = fsspec.filesystem("memory", global_store=False, skip_instance_cache=True) second = fsspec.filesystem("memory", global_store=False, skip_instance_cache=True) first.pipe("file", b"data") assert not second.exists("file")
Pickling an independent memory filesystem copies its files and directories.The default global filesystem continues to use the global store in the processwhere it is unpickled.
Listings Caching----------------
For some implementations, getting file listings (i.e., ``ls`` and anything thatdepends on it) is expensive. These implementations use dict-like instances of:class:`fsspec.dircache.DirCache` to manage the listings.
The cache allows for time-based expiry of entries with the ``listings_expiry_time``parameter, or LRU expiry with the ``max_paths`` parameter. These can beset on any implementation instance that uses listings caching; or to skip thecaching altogether, use ``use_listings_cache=False``. That would be appropriatewhen the target location is known to be volatile because it is being writtento from other sources.
When the ``fsspec`` instance writes to the backend, the method ``invalidate_cache``is called, so that subsequent listing of the given paths will force a refresh. Inaddition, some methods like ``ls`` have a ``refresh`` parameter to force fetchingthe listing again.
URL chaining------------
Some implementations proxy or otherwise make use of another filesystem implementation, suchas locally caching remote files, i.e., finding out what files exist using the remote implementation,but actually opening the local copies upon access. Other examples include reading from a Dask workerwhich can see file-systems the client cannot, and accessing a zip file which is being read fromanother backend.
In such cases, you can specify the parameters exactly as specified in the implementation docstrings,for the dask case something like
.. code-block:: python
of = fsspec.open('dask://bucket/key', target_protocol='s3', target_options={'anon': True})
As a shorthand, particularly useful where you have multiple hops, is to "chain" the URLs withthe special separator ``"::"``. The arguments to be passed on to each of the implementations referencedare keyed by the protocol names included in the URL. Here is the equivalent to the line above:
.. code-block:: python
of = fsspec.open('dask::s3://bucket/key', s3={'anon': True})
A couple of more complicated cases:
.. code-block:: python
of = fsspec.open_files('zip://*.csv::simplecache::gcs://bucket/afile.zip', simplecache={'cache_storage': '/stored/zip/files'}, gcs={'project': 'my-project'})
reads a zip-file from google, stores it locally, and gives access to the contained CSV files. Conversely,
.. code-block:: python
of = fsspec.open_files('simplecache::zip://*.csv::gcs://bucket/afile.zip', simplecache={'cache_storage': '/stored/csv/files'}, gcs={'project': 'my-project'})
reads the same zip-file, but extracts the CSV files and stores them locally in the cache.
**For developers**: this "chaining" methods works by formatting the arguments passed to ``open_*``into ``target_protocol`` (a simple string) and ``target_options`` (a dict) and also optionally``fo`` (target path, if a specific file is required). In order for an implementation to chainsuccessfully like this, it must look for exactly those named arguments. Implementations thatrequire access to the target path of their nested targets should inherit from ``ChainedFileSystem``,which will trigger pass-through of the nested path automatically.
Caching Files Locally---------------------
``fsspec`` allows you to access data on remote file systems, that is its purpose. However, suchaccess can often be rather slow compared to local storage, so as well as buffering (see above), theoption exists to copy files locally when you first access them, and thereafter to use the local data.This local cache of data might be temporary (i.e., attached to the process and discarded when theprocess ends) or at some specific location in your local storage.
Two mechanisms are provided, and both involve wrapping a ``target`` filesystem. The following examplecreates a file-based cache.
.. code-block:: python
fs = fsspec.filesystem("filecache", target_protocol='s3', target_options={'anon': True}, cache_storage='/tmp/files/')
Each time you open a remote file on S3, it will first copy it toa local temporary directory, and then all further access will use the local file. Since we specifya particular local location, the files will persist and can be reused from future sessions, althoughyou can also set policies to have cached files expire after some time, or to check the remote file systemon each open, to see if the target file has changed since it was copied.
With the top-level functions ``open``, ``open_local`` and ``open_files``, you can use thesame set of kwargs as the example above, or you can chain the URL - the following wouldbe the equivalent
.. code-block:: python
of = fsspec.open("filecache::s3://bucket/key", s3={'anon': True}, filecache={'cache_storage':'/tmp/files'})
With the "blockcache" variant, data is downloaded block-wise: only the specific parts of the remote filewhich are accessed. This means that the local copy of the file might end up being much smaller than theremote one, if only certain parts of it are required.
Whereas "filecache" works for all file system implementations, and provides a real local file for otherlibraries to use, "blockcache" has restrictions: that you have a storage/OS combination which supportssparse files, that the backend implementation uses files which derive ``from AbstractBufferedFile``,and that the library you pass the resultant object to accepts generic python file-like objects. Youshould not mix block- and file-caches in the same directory. "simplecache" is the same as "filecache",except without the options for cache expiry and to check the original source - it can be used where thetarget can be considered static, and particularly where a large number of target files are expected(because no metadata is written to disc). Only "simplecache" is guaranteed thread/process-safe.Cached files can still be removed by age using their local modification times, for example``fs.clear_expired_cache(expiry_time=7 * 24 * 60 * 60)``. This only changes the writable cachelocation when multiple cache directories are configured.
With "filecache" and "simplecache", each file is downloaded to a temporary ``*.part`` file in thecache directory and renamed into place once complete, so a partial download is never visible. Thetemporary file is removed if the download fails, but not if the process is killed mid-download;leftover ``*.part`` files are ignored by the cache and safe to delete.
Remote Write Caching--------------------
You can cache files to local files to send to remote using the "simplecache" protocol.The following example demonstrates how this might look
.. code-block:: python
with fsspec.open('simplecache::s3://mybucket/myfile', 'wb', s3={"profile": "writer"}) as f: f.write(b"some data")
This will open a local file for writing, and when this file is closed, it will be uploadedto the target URL, in this case on S3. The file-like object ``f`` can be passed to anylibrary expecting to write to a file. Note that we pass parameters to ``S3FileSystem`` usingthe key ``"s3"``, the same as the name of the protocol.
File Selector (GUI)-------------------
The module ``fsspec.gui`` contains a graphical file selector interface. It is builtusing `panel`_, which must be installed in order to use the GUI. Upon instantiation,you can provide the initial URL location (which can be returned to with the "🏠" button),arguments and filters.
.. _panel: https://panel.holoviz.org/
.. image:: img/gui.png
Clicking on a directory will descend into it, and selecting a file will mark it asthe output of the interface. You can select any of the known protocols, but shouldprovide any required arguments in the "kwargs" box (as a dictionary) and anyabsolute URL location before clicking "⇨" to go to that location. If using file filters,they will appear as a list of checkboxes; only those file-endings selected will beshown (or if none are selected, all files are shown).
The interface provides the following outputs:
#. ``.urlpath``: the currently selected item (if any)#. ``.storage_options``: the value of the kwargs box#. ``.fs``: the current filesystem instance#. ``.open_file()``: produces an ``OpenFile`` instance for the current selection
Configuration-------------
You can set default keyword arguments to pass to any fsspec backend by editingconfig files, providing environment variables, or editing the contents ofthe dictionary ``fsspec.config.conf``.
Files are stored in the directory pointed to by ``FSSPEC_CONFIG_DIR``,``~/.config/fsspec/`` by default. Set ``FSSPEC_CONFIG_DIR`` before importing``fsspec`` to read configuration from a different directory. All \*.ini and\*.json files will be loaded as UTF-8, parsed from their respective formats and fed into the config dictat import time. For example, if there is a file "~/.config/fsspec/conf.json"containing
.. code-block:: json
{"file": {"auto_mkdir": true}}
then any instance of the file system whose protocol is "file" (i.e.,``LocalFileSystem``) with be passed the kwargs ``auto_mkdir=True``**unless** the user supplies the kwarg themselves.
For instance:
.. code-block:: python
import fsspec fs = fsspec.filesystem("file") assert fs.auto_mkdir == True fs = fsspec.filesystem("file", auto_mkdir=False) assert fs.auto_mkdir == False
Obviously, you should only define default values that are appropriate fora given file system implementation. INI files only support string values.
Alternatively, you can provide overrides with environment variables of the style``FSSPEC_{protocol}=<json_dict_value>`` and``FSSPEC_{protocol}_{kwargname}=<value>``. Values are parsed as JSON whenpossible; otherwise they remain strings. For example, in a POSIX shell:
.. code-block:: sh
export FSSPEC_FILE='{"auto_mkdir": true}' export FSSPEC_FILE_AUTO_MKDIR=false
The per-option variable overrides the protocol dictionary, so this sets``auto_mkdir`` to the boolean ``False``, not the string ``"false"``. Set thesevariables before importing ``fsspec`` too.
Configuration is determined in the following order, with later items winning:
#. ini and json files in the config directory (``FSSPEC_CONFIG_DIR`` or ``$HOME/.config/fsspec/``), sorted lexically by filename#. ``FSSPEC_{protocol}`` environment variables#. ``FSSPEC_{protocol}_{kwargname}`` environment variables#. the contents of ``fsspec.config.conf``, which can be edited at runtime#. kwargs explicitly passed, whether with ``fsspec.open``, ``fsspec.filesystem`` or directly instantiating the implementation class.
Asynchronous------------
Some implementations, those deriving from ``fsspec.asyn.AsyncFileSystem``, haveasync/coroutine implementations of some file operations. The async methods havenames beginning with ``_``, and listed in the ``asyn`` module; synchronous orblocking functions are automatically generated, which will operate via anevent loop in another thread, by default.
See :doc:`async` for modes of operation and how to implement such file systems.
Callbacks---------
Some methods support a ``callback=`` argument, which is the entry point toproviding feedback on transfers to the user or any other logging service. Thisfeature is new and experimental and supported by varying amounts in thebackends.
See the docstrings in the callbacks module for further details.``fsspec.callbacks.TqdmCallback`` can be used to display a progress bar usingtqdm.
.. raw:: html
<script data-goatcounter="https://fsspec.goatcounter.com/count" async src="//gc.zgo.at/count.js"></script>
Exclusive write---------------
Some backends support writing to a file only if it doesn't already exist. This may beimplemented for the following methods:- pipe_file (with argument ``mode=='create'``)- put_file (with argument ``mode=='create'``)- open (with argument ``mode="xb"``)Since some writes will be achieved in blocks, the timing of when the check is done isnot defined - it may be at the start or at the completion of the operation, dependingon the backend.
If using exclusive mode on a file that does already exist, a ``FileExistsError`` willbe raised.
This feature is currently included on a trial basis and may change in the future.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129``fsspec``: Filesystem interfaces for Python============================================
Filesystem Spec (``fsspec``) is a project to provide a unified pythonic interface tolocal, remote and embedded file systems and bytes storage.
Brief Overview--------------
There are many places to store bytes, from in memory, to the local disk, clusterdistributed storage, to the cloud. Many files also contain internal mappings of names to bytes,maybe in a hierarchical directory-oriented tree. Working with all these differentstorage media, and their associated libraries, is a pain. ``fsspec`` exists toprovide a familiar API that will work the same whatever the storage backend.As much as possible, we iron out the quirks specific to each implementation,so you need do no more than provide credentials for each service you access(if needed) and thereafter not have to worry about the implementation again.
Why---
``fsspec`` provides two main concepts: a set of filesystem classes with uniform APIs(i.e., functions such as ``cp``, ``rm``, ``cat``, ``mkdir``, ...) supplying operations on a range ofstorage systems; and top-level convenience functions like :func:`fsspec.open`, to allowyou to quickly get from a URL to a file-like object that you can use with a third-partylibrary or your own code.
The section :doc:`intro` gives motivation and history of this project, butmost users will want to skip straight to :doc:`usage` to find out how to usethe package and :doc:`features` to see the long list of added functionalityincluded along with the basic file-system interface.
Who uses ``fsspec``?--------------------
You can use ``fsspec``'s file objects with any python function that acceptsfile objects, because of *duck typing*.
You may well be using ``fsspec`` already without knowing it.The following libraries use ``fsspec`` internally for path and file handling:
#. `Dask`_, the parallel, out-of-core and distributed programming platform#. `Intake`_, the data source cataloguing and loading library and its plugins#. `pandas`_, the tabular data analysis package#. `xarray`_ and `zarr`_, multidimensional array storage and labelled operations#. `DVC`_, version control system for machine learning projects#. `Kedro`_, a Python framework for reproducible, maintainable and modular data science code#. `Huggingface🤗 Datasets`_, a popular library to load&manipulate data for Deep Learning models
``fsspec`` filesystems are also supported by:
#. `pyarrow`_, the in-memory data layout engine#. `petl`_, a general purpose package for extracting, transforming and loading tables of data.
... plus many more that we don't know about.
.. _Dask: https://dask.org/.. _Intake: https://intake.readthedocs.io/.. _pandas: https://pandas.pydata.org/.. _xarray: https://docs.xarray.dev/.. _zarr: https://zarr.readthedocs.io/.. _DVC: https://dvc.org/.. _kedro: https://docs.kedro.org/en/stable/tutorial/set_up_data.html#supported-data-locations.. _pyxet: https://github.com/xetdata/pyxet.. _Huggingface🤗 Datasets: https://github.com/huggingface/datasets.. _pyarrow: https://arrow.apache.org/docs/python/.. _petl: https://petl.readthedocs.io/en/stable/io.html#petl.io.remotes.RemoteSource
Installation------------
``fsspec`` can be installed from PyPI or conda and has no dependencies of its own
.. code-block:: sh
pip install fsspec conda install -c conda-forge fsspec
Not all filesystem implementations are available without installing extradependencies. For example to be able to access data in GCS, you can use the optionalpip install syntax below, or install the specific package required
.. code-block:: sh
pip install fsspec[gcs] conda install -c conda-forge gcsfs
``fsspec`` attempts to provide the right message when you attempt to use a filesystemfor which you need additional dependencies.The current list of known implementations can be found as follows
.. code-block:: python
from fsspec.registry import known_implementations
known_implementations
.. toctree:: :maxdepth: 1 :caption: Contents:
intro.rst usage.rst features.rst copying.rst developer.rst async.rst api.rst changelog.rst code-of-conduct.rst
These docs pages collect anonymous tracking data using goatcounter, and thedashboard is available to the public: https://fsspec.goatcounter.com/ .
.. raw:: html
<script data-goatcounter="https://fsspec.goatcounter.com/count" async src="//gc.zgo.at/count.js"></script>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899Background==========
Python provides a standard interface for open files, so that alternate implementations of file-like object canwork seamlessly with many function which rely only on the methods of that standard interface. A number of librarieshave implemented a similar concept for file-systems, where file operations can be performed on a logical file-systemwhich may be local, structured data store or some remote service.
This repository is intended to be a place to define a standard interface that such file-systems should adhere to,such that code using them should not have to know the details of the implementation in order to operate on any ofa number of backends. With hope, the community can come together todefine an interface that is the best for the highest number of users, and having the specification, makes developingother file-system implementations simpler.
History-------
We have been involved in building a number of remote-data file-system implementations, principallyin the context of the `Dask`_ project. In particular, several are listedin `docs`_ with links to the specific repositories.With common authorship, there is much that is similar between the implementations, for example posix-like namingof the operations, and this has allowed Dask to be able to interact with the various backends and parse genericURLs in order to select amongst them. However, *some* extra code was required in each case to adapt the peculiaritiesof each implementation with the generic usage that Dask demanded. People may find the`code`_ which parses URLs and creates file-systeminstances interesting.
.. _Dask: https://dask.pydata.org/en/latest/.. _docs: https://dask.pydata.org/en/latest/how-to/connect-to-remote-data.html.. _code: https://github.com/fsspec/filesystem_spec/blob/4f0eb48/fsspec/core.py#L525
At the same time, the Apache `Arrow`_ project was also concerned with a similar problem,particularly a common interface to local and HDFS files, for example the`hdfs`_ interface (which actually communicated with HDFSwith a choice of driver). These are mostly used internally within Arrow, but Dask was modified in order to be ableto use the alternate HDFS interface (which solves some security issues with ``hdfs3``). In the process, a`conversation`_was started, and I invite all interested parties to continue the conversation in this location.
.. _Arrow: https://arrow.apache.org/.. _hdfs: https://arrow.apache.org/docs/python/filesystems.html.. _conversation: https://github.com/dask/dask/issues/2880
There is a good argument that this type of code has no place in Dask, which is concerned with making graphsrepresenting computations, and executing those graphs on a scheduler. Indeed, the file-systems are generally useful,and each has a user-base wider than just those that work via Dask.
Influences----------
The following places to consider, when choosing the definitions of how we would like the file-system specificationto look:
#. python's `os`_ module and its `path`_ namespace; also other file-connected functionality in the standard library#. posix/bash method naming conventions that linux/unix/osx users are familiar with; or perhaps their Windows variants#. the existing implementations for the various backends (e.g., `gcsfs`_ or Arrow's `hdfs`_)#. `pyfilesystems`_, an attempt to do something similar, with a plugin architecture. This conception has several types of local file-system, and a lot of well-thought-out validation code.
.. _os: https://docs.python.org/3/library/os.html.. _path: https://docs.python.org/3/library/os.path.html.. _gcsfs: https://gcsfs.readthedocs.io/en/latest/api.html#gcsfs.core.GCSFileSystem.. _pyfilesystems: https://docs.pyfilesystem.org/en/latest/index.html
Other similar work------------------
It might have been conceivable to reuse code in ``pyfilesystems``, which has an established interface and severalimplementations of its own. However, it supports none of the **critical** features forcloud and parallel access, and would not be easy tocoerce. Following on the success of ``s3fs`` and ``gcsfs``, and their use within Dask, it seemed best tohave an interface as close to those as possible. See a`discussion`_ on the topic.
.. _discussion: https://github.com/fsspec/filesystem_spec/issues/5
Other newer technologies such as `smart_open`_ and ``pyarrow``'s newer file-system rewrite also have someparts of the functionality presented here, that might suit some use cases better.
.. _smart_open: https://github.com/RaRe-Technologies/smart_open
Structure of the package------------------------
The best place to get a feel for the contents of ``fsspec`` is by looking through the :doc:`usage` and:doc:`api` sections. In addition, the source code will be interesting for those who wish to subclass anddevelop new file-system implementations. ``fsspec/spec.py`` contains the main abstract file-system classto derive from, ``AbstractFileSystem``.
.. _zarr: https://zarr.readthedocs.io
.. raw:: html
<script data-goatcounter="https://fsspec.goatcounter.com/count" async src="//gc.zgo.at/count.js"></script>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179Usage=====
This is quick-start documentation to help people get familiar with the layout and functioning of ``fsspec``.
Instantiate a file-system-------------------------
``fsspec`` provides an abstract file-system interface as a base class, to be used by other filesystems.A file-system instance is an object for manipulating files on someremote store, local files, files within some wrapper, or anything else that is capable of producingfile-like objects.
Some concrete implementations are bundled with ``fsspec`` and others can be installed separately. Theycan be instantiated directly, or the ``registry`` can be used to find them.
Direct instantiation using the name of the class such as ``LocalFileSystem``, ``ZipFileSystem`` or``S3FileSystem``:
.. code-block:: python
from fsspec.implementations.local import LocalFileSystem
fs = LocalFileSystem()
Look-up via registry:
.. code-block:: python
import fsspec
fs = fsspec.filesystem('file')
The argument passed here is the protocol name which maps across to the corresponding implementationclass ``LocalFileSystem``. Other examples are ``zip`` which maps across to ``ZipFileSystem`` and``s3`` which maps across to ``S3FileSystem``.
Many filesystems also take extra parameters, some of which may be options - see :doc:`api`, or use:func:`fsspec.get_filesystem_class` to get the class object and inspect its docstring.
.. code-block:: python
import fsspec
fs = fsspec.filesystem('ftp', host=host, port=port, username=user, password=pw)
The list of implemented ``fsspec`` protocols can be retrieved using :func:`fsspec.available_protocols`.
.. note::
The full list of the available protocols and the implementations that they map across to is divided into two sections:
- Implementations built into ``fsspec``: :ref:`implementations` - Implementations in separate packages: :ref:`external_implementations`
Use a file-system-----------------
File-system instances offer a large number of methods for getting information about and manipulating filesfor the given back-end. Although some specific implementations may not offer all features (e.g., ``http``is read-only), generally all normal operations, such as ``ls``, ``rm``, should be expected to work (see thefull list: :class:`fsspec.spec.AbstractFileSystem`).Note that this quick-start will prefer posix-style naming, butmany common operations are aliased: ``cp()`` and ``copy()`` are identical, for instance.Functionality is generally chosen to be as close to the builtin ``os`` module's working for things like``glob`` as possible. The following example uses an in-memory file-system, so itcan run without a remote service or credentials.
.. code-block:: python
import fsspec
fs = fsspec.filesystem("memory", global_store=False, skip_instance_cache=True) fs.mkdir("/remote/output") fs.touch("/remote/output/success") # creates empty file assert fs.exists("/remote/output/success") assert fs.isfile("/remote/output/success") assert fs.cat("/remote/output/success") == b"" # get content as bytestring fs.copy("/remote/output/success", "/remote/output/copy") assert fs.ls("/remote/output", detail=False) == [ "/remote/output/copy", "/remote/output/success", ] fs.rm("/remote/output", recursive=True)
The ``open()`` method will return a file-like object which can be passed to any other library that expectsto work with python files, or used by your own code as you would a normal python file object.These will normally be binary-mode only, but may implement internal bufferingin order to limit the number of reads from a remote source. They respect the use of ``with`` contexts. Ifyou have ``pandas`` installed, for example, you can do the following:
.. code-block:: python
f = fs.open("/remote/path/notes.txt", "rb") lines = f.readline() # read to first b"\n" f.seek(-10, 2) foot = f.read() # read last 10 bytes of file f.close()
import pandas as pd with fs.open('/remote/data/myfile.csv') as f: df = pd.read_csv(f, sep='|', header=None)
Higher-level------------
For many situations, the only function that will be needed is :func:`fsspec.open_files()`, which will return:class:`fsspec.core.OpenFile` instances created from a single URL and parameters to pass to the backend(s).This supports text-mode and compression on the fly, and the objects can be serialized for passing betweenprocesses or machines (so long as each has access to the same backend file-system). The protocol (i.e.,backend) is inferred from the URL passed, and glob characters are expanded in read mode (search for files)or write mode (create names). Critically, the file on the backend system is not actually opened until the``OpenFile`` instance is used in a ``with`` context.
.. code-block:: python
of = fsspec.open("github://dask:fastparquet@main/test-data/nation.csv", "rt") # of is an OpenFile container object. The "with" context below actually opens it with of as f: # now f is a text-mode file for line in f: # iterate text lines print(line) if "KENYA" in line: break
Compressed files----------------
Use the ``compression`` argument to :func:`fsspec.open` to read or write anindividual compressed file. This wraps the file object; it does not compress thewhole file-system. For example, write a gzip-compressed text file and read it back:
.. code-block:: python
import fsspec
with fsspec.open("example.txt.gz", "wt", compression="gzip", encoding="utf-8") as f: f.write("Hello from fsspec!\n")
with fsspec.open("example.txt.gz", "rt", compression="infer", encoding="utf-8") as f: assert f.read() == "Hello from fsspec!\n"
``compression="infer"`` selects a registered codec from the filename suffix,such as ``.gz`` for gzip. Compression is not inferred by default:``compression=None`` leaves the bytes unchanged, even if the filename ends in``.gz``. The same ``compression`` argument is available on :func:`fsspec.open_files`.
Available codecs depend on your Python installation and optional packages.Call :func:`fsspec.available_compressions` to see the codecs registered in thecurrent process. For example, ``"gzip"`` is a codec name, while ``None`` means nocompression.
For Zstandard (``compression="zstd"``, or ``compression="infer"`` with a ``.zst``filename), fsspec first tries the standard-library ``compression.zstd`` moduleon Python 3.14 and later. On older Python versions, install ``backports.zstd``:
.. code-block:: console
python -m pip install backports.zstd
If that backend is unavailable, fsspec also supports the ``zstandard`` packageas a fallback. Other optional codecs include ``lz4`` (install ``lz4``) and``snappy`` (install ``python-snappy``). Install optional packages before importingfsspec, or restart your Python process after installation so the codecs can beregistered.
Explicitly requesting an unavailable codec raises ``ValueError`` with a messagesuch as ``Compression type zstd not supported``. Inference only recognizessuffixes registered by available codecs: if a suffix is not recognized,``compression="infer"`` passes through the stored bytes without compression ordecompression. Use an explicit codec namewhen you want a missing dependency to produce an error.
.. raw:: html
<script data-goatcounter="https://fsspec.goatcounter.com/count" async src="//gc.zgo.at/count.js"></script>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475from . import cachingfrom .callbacks import Callbackfrom .compression import available_compressionsfrom .core import get_fs_token_paths, open, open_files, open_local, url_to_fsfrom .exceptions import FSTimeoutErrorfrom .mapping import FSMap, get_mapperfrom .registry import ( available_protocols, filesystem, get_filesystem_class, register_implementation, registry,)from .spec import AbstractFileSystem
try: from ._version import __version__ # noqa: F401except ImportError: __version__ = "unknown"
__all__ = [ "AbstractFileSystem", "FSTimeoutError", "FSMap", "filesystem", "register_implementation", "get_filesystem_class", "get_fs_token_paths", "get_mapper", "open", "open_files", "open_local", "registry", "caching", "Callback", "available_protocols", "available_compressions", "url_to_fs",]
def process_entries(): try: from importlib.metadata import entry_points except ImportError: return if entry_points is not None: try: eps = entry_points() except TypeError: pass # importlib-metadata < 0.8 else: if hasattr(eps, "select"): # Python 3.10+ / importlib_metadata >= 3.9.0 specs = eps.select(group="fsspec.specs") else: specs = eps.get("fsspec.specs", []) registered_names = {} for spec in specs: err_msg = f"Unable to load filesystem from {spec}" name = spec.name if name in registered_names: continue registered_names[name] = True register_implementation( name, spec.value.replace(":", "."), errtxt=err_msg, # We take our implementations as the ones to overload with if # for some reason we encounter some, may be the same, already # registered clobber=True, )
process_entries()123456789101112131415161718192021222324# file generated by vcs-versioning# don't change, don't track in version controlfrom __future__ import annotations
__all__ = [ "__version__", "__version_tuple__", "version", "version_tuple", "__commit_id__", "commit_id",]
version: str__version__: str__version_tuple__: tuple[int | str, ...]version_tuple: tuple[int | str, ...]commit_id: str | None__commit_id__: str | None
__version__ = version = '0.0.0'__version_tuple__ = version_tuple = (0, 0, 0)
__commit_id__ = commit_id = None1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import operator
from fsspec import AbstractFileSystemfrom fsspec.utils import tokenize
class AbstractArchiveFileSystem(AbstractFileSystem): """ A generic superclass for implementing Archive-based filesystems.
Currently, it is shared amongst :class:`~fsspec.implementations.zip.ZipFileSystem`, :class:`~fsspec.implementations.libarchive.LibArchiveFileSystem` and :class:`~fsspec.implementations.tar.TarFileSystem`. """
def __str__(self): return f"<Archive-like object {type(self).__name__} at {id(self)}>"
__repr__ = __str__
def ukey(self, path): return tokenize(path, self.fo, self.protocol)
def _not_a_file(self, path): """The error for opening ``path``, which is not a file member.""" return IsADirectoryError(path) if self.isdir(path) else FileNotFoundError(path)
def _all_dirnames(self, paths): """Returns *all* directory names for each path in paths, including intermediate ones.
Parameters ---------- paths: Iterable of path strings """ if len(paths) == 0: return set()
dirnames = {self._parent(path) for path in paths} - {self.root_marker} return dirnames | self._all_dirnames(dirnames)
def info(self, path, **kwargs): self._get_dirs() path = self._strip_protocol(path) if path in {"", "/"} and self.dir_cache: return {"name": "", "type": "directory", "size": 0} if path in self.dir_cache: return self.dir_cache[path] elif path + "/" in self.dir_cache: return self.dir_cache[path + "/"] else: raise FileNotFoundError(path)
def ls(self, path, detail=True, **kwargs): path = self._strip_protocol(path) self._get_dirs() paths = {} for p, f in self.dir_cache.items(): p = p.rstrip("/") if "/" in p: root = p.rsplit("/", 1)[0] else: root = "" if root == path.rstrip("/"): paths[p] = f elif all( (a == b) for a, b in zip(path.split("/"), [""] + p.strip("/").split("/")) ): # root directory entry ppath = p.rstrip("/").split("/", 1)[0] if ppath not in paths: out = {"name": ppath, "size": 0, "type": "directory"} paths[ppath] = out if not paths and path.strip("/"): # Nothing is listed under ``path``, so it is a file, an empty # directory or missing; ``info`` raises FileNotFoundError for the last. info = self.info(path) if info["type"] != "directory": paths[info["name"]] = info if detail: out = sorted(paths.values(), key=operator.itemgetter("name")) return out else: return sorted(paths)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335import asyncioimport asyncio.eventsimport atexitimport concurrent.futuresimport functoolsimport inspectimport ioimport loggingimport numbersimport osimport reimport sysimport threadingfrom collections.abc import Iterablefrom glob import has_magicfrom typing import TYPE_CHECKING
from .callbacks import DEFAULT_CALLBACKfrom .exceptions import FSTimeoutErrorfrom .implementations.local import LocalFileSystem, make_path_posix, trailing_sepfrom .spec import AbstractBufferedFile, AbstractFileSystemfrom .utils import check_contained, glob_translate, is_exception, other_paths
private = re.compile("_[^_]")iothread = [None] # dedicated fsspec IO threadloop = [None] # global event loop for any non-async instance_lock = threading.Lock()get_running_loop = asyncio.get_running_loop
def get_lock(): """Return the process-local threading lock.""" return _lock
def reset_lock(): """Reset the global loop and lock after forking.""" global _lock
iothread[0] = None loop[0] = None _lock = threading.Lock()
async def _runner(event, coro, result, timeout=None): timeout = timeout if timeout else None # convert 0 or 0.0 to None if timeout is not None: coro = asyncio.wait_for(coro, timeout=timeout) try: result[0] = await coro except Exception as ex: result[0] = ex finally: event.set()
def sync(loop, func, *args, timeout=None, **kwargs): """ Make loop run coroutine until it returns. Runs in other thread
Examples -------- >>> fsspec.asyn.sync(fsspec.asyn.get_loop(), func, *args, timeout=timeout, **kwargs) """ timeout = timeout if timeout else None # convert 0 or 0.0 to None # NB: if the loop is not running *yet*, it is OK to submit work # and we will wait for it if loop is None or loop.is_closed(): raise RuntimeError("Loop is not running") if iothread[0] is not None and ( loop is globals()["loop"][0] or (getattr(loop, "_thread_id", 0) or 0) == iothread[0].ident ): if not iothread[0].is_alive(): raise RuntimeError("fsspec IO thread has already stopped.") try: loop0 = asyncio.events.get_running_loop() if loop0 is loop: raise NotImplementedError("Calling sync() from within a running loop") except NotImplementedError: raise except RuntimeError: pass coro = func(*args, **kwargs) result = [None] event = threading.Event() asyncio.run_coroutine_threadsafe(_runner(event, coro, result, timeout), loop) while True: # this loops allows thread to get interrupted if event.wait(1): break if timeout is not None: timeout -= 1 if timeout < 0: raise FSTimeoutError
return_result = result[0] # the traceback of a stored exception includes _runner's frame, which holds # ``result``: empty it so that frame does not refer back to the exception result[0] = None try: if isinstance(return_result, asyncio.TimeoutError): # suppress asyncio.TimeoutError, raise FSTimeoutError raise FSTimeoutError from return_result elif isinstance(return_result, BaseException): raise return_result else: return return_result finally: # the traceback also includes this frame, so don't keep the exception # in a local either: that would be a reference cycle del return_result
_deferred_close_tasks = set()_deferred_close_lock = threading.Lock()
def _on_loop_thread(loop): """Returns True if the current thread is servicing the given event loop.""" if loop is None: return False try: return asyncio.get_running_loop() is loop except RuntimeError: return False
def _defer_task( loop, coro, description="deferred task", logger=None, log_level=logging.WARNING,): """Schedules a coroutine as a tracked background task on ``loop``.
Retains a strong reference in ``_deferred_close_tasks`` until completion to prevent asyncio garbage collection from discarding pending tasks mid-flight, and ensures unhandled task exceptions are retrieved and logged. """ task = loop.create_task(coro) with _deferred_close_lock: _deferred_close_tasks.add(task)
def _on_done(t): with _deferred_close_lock: _deferred_close_tasks.discard(t) if not t.cancelled(): exc = t.exception() if exc: log = logger or logging.getLogger("fsspec.asyn") log.log( log_level, "%s failed during asynchronous execution: %s", description, exc, exc_info=exc, )
task.add_done_callback(_on_done) return task
def sync_teardown( loop, func_or_coro, *args, timeout=None, description="teardown", **kwargs,): """Safely runs an async teardown coroutine on ``loop`` from synchronous context.
Schedules via :func:`asyncio.run_coroutine_threadsafe` or defers on the loop thread to prevent deadlocks. """ coro = func_or_coro(*args, **kwargs) if callable(func_or_coro) else func_or_coro if not asyncio.iscoroutine(coro): return
if sys.is_finalizing(): coro.close() return
if loop is None or not loop.is_running() or loop.is_closed(): coro.close() raise RuntimeError(f"Skipping {description}: no usable IO loop available.")
if _on_loop_thread(loop): _defer_task(loop, coro, description=description, log_level=logging.ERROR) return
try: future = asyncio.run_coroutine_threadsafe(coro, loop) except RuntimeError: coro.close() raise RuntimeError(f"Skipping {description}: event loop is closed.") from None
if timeout is not None and timeout <= 0: return
try: return future.result(timeout) except concurrent.futures.TimeoutError: raise FSTimeoutError( f"{description} did not complete within {timeout}s." ) from None
def sync_wrapper(func, obj=None): """Given a function, make so can be called in blocking contexts
Leave obj=None if defining within a class. Pass the instance if attaching as an attribute of the instance. """
@functools.wraps(func) def wrapper(*args, **kwargs): self = obj or args[0] return sync(self.loop, func, *args, **kwargs)
return wrapper
def async_gen_wrapper(func, obj=None): """Given a async generator, make so can be called in blocking contexts"""
@functools.wraps(func) def wrapper(*args, **kwargs): self = obj or args[0] gen = func(*args, **kwargs) while True: try: yield sync(self.loop, gen.__anext__) except StopAsyncIteration: break
return wrapper
def get_loop(): """Create or return the default fsspec IO loop
The loop will be running on a separate thread. """ if loop[0] is None: with get_lock(): # repeat the check just in case the loop got filled between the # previous two calls from another thread if loop[0] is None: loop[0] = asyncio.new_event_loop() th = threading.Thread(target=loop[0].run_forever, name="fsspecIO") th.daemon = True th.start() iothread[0] = th return loop[0]
# How long to wait for the IO thread at exit before warning that it is stuck_STOP_IO_LOOP_WARN_SECONDS = 1
def _stop_io_loop(): """Stop the fsspec IO loop, if one was started, and wait for its thread.
The IO thread is a daemon, so nothing else stops it before interpreter shutdown. It must not outlive ``Py_Finalize``: a callback firing on it afterwards (for example a uvloop timer) re-enters the finalized interpreter and crashes the process (#2241). atexit hooks run before finalization, while the thread can still take the GIL to process the stop.
The stop takes effect once the running callback returns, so the wait only lasts if a callback blocks the loop. That case is logged, then waited out: letting the thread survive finalization would reintroduce the crash. """ if loop[0] is None or iothread[0] is None or not iothread[0].is_alive(): return try: loop[0].call_soon_threadsafe(loop[0].stop) except RuntimeError: # the loop was closed by its user return iothread[0].join(timeout=_STOP_IO_LOOP_WARN_SECONDS) if iothread[0].is_alive(): logging.getLogger("fsspec.asyn").warning( "fsspec IO loop is still running %ss after interpreter exit began; " "a callback is blocking it. Waiting for it to finish.", _STOP_IO_LOOP_WARN_SECONDS, ) iothread[0].join()
# Registered at import, so it runs after any atexit hook registered later# that may still use the loop. A forked child inherits this registration;# the fork guard below clears ``loop``/``iothread`` there, so in the child it# only stops a loop the child started itself, never the parent's thread.atexit.register(_stop_io_loop)
def reset_after_fork(): reset_lock()
if hasattr(os, "register_at_fork"): # should be posix; this will do nothing for spawn or forkserver subprocesses os.register_at_fork(after_in_child=reset_after_fork)
if TYPE_CHECKING: import resource
ResourceError = resource.errorelse: try: import resource except ImportError: resource = None ResourceError = OSError else: ResourceError = getattr(resource, "error", OSError)
_DEFAULT_BATCH_SIZE = 128_NOFILES_DEFAULT_BATCH_SIZE = 1280
def _get_batch_size(nofiles=False): from fsspec.config import conf
if nofiles: if "nofiles_gather_batch_size" in conf: return conf["nofiles_gather_batch_size"] else: if "gather_batch_size" in conf: return conf["gather_batch_size"] if nofiles: return _NOFILES_DEFAULT_BATCH_SIZE if resource is None: return _DEFAULT_BATCH_SIZE
try: soft_limit, _ = resource.getrlimit(resource.RLIMIT_NOFILE) except (ImportError, ValueError, ResourceError): return _DEFAULT_BATCH_SIZE
if soft_limit == resource.RLIM_INFINITY: return -1 else: return soft_limit // 8
def running_async() -> bool: """Being executed by an event loop?""" try: asyncio.get_running_loop() return True except RuntimeError: return False
async def _run_coros_in_chunks( coros, batch_size=None, callback=DEFAULT_CALLBACK, timeout=None, return_exceptions=False, nofiles=False,): """Run the given coroutines in chunks.
Parameters ---------- coros: list of coroutines to run batch_size: int or None Number of coroutines to submit/wait on simultaneously. If -1, then it will not be any throttling. If None, it will be inferred from _get_batch_size() callback: fsspec.callbacks.Callback instance Gets a relative_update when each coroutine completes timeout: number or None If given, each coroutine times out after this time. Note that, since there are multiple batches, the total run time of this function will in general be longer return_exceptions: bool Same meaning as in asyncio.gather nofiles: bool If inferring the batch_size, does this operation involve local files? If yes, you normally expect smaller batches. """
if batch_size is None: batch_size = _get_batch_size(nofiles=nofiles)
if batch_size == -1: batch_size = len(coros) elif batch_size <= 0: raise ValueError
async def _run_coro(coro, i): try: return await asyncio.wait_for(coro, timeout=timeout), i except Exception as e: if not return_exceptions: raise return e, i finally: callback.relative_update(1)
i = 0 n = len(coros) results = [None] * n pending = set()
while pending or i < n: while len(pending) < batch_size and i < n: pending.add(asyncio.ensure_future(_run_coro(coros[i], i))) i += 1
if not pending: break
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) first_exc = None while done: task = done.pop() try: result, k = await task results[k] = result except Exception as exc: if first_exc is None: first_exc = exc
if first_exc is not None: for task in pending: task.cancel() if pending: await asyncio.gather(*pending, return_exceptions=True) try: raise first_exc finally: # the traceback includes this frame, so it must not refer back # to the exception: directly or through the finished task del first_exc, task
return results
# these methods should be implemented as async by any async-able backendasync_methods = [ "_ls", "_cat_file", "_get_file", "_put_file", "_rm_file", "_cp_file", "_pipe_file", "_expand_path", "_info", "_isfile", "_isdir", "_exists", "_walk", "_glob", "_find", "_du", "_size", "_mkdir", "_makedirs",]
class AsyncFileSystem(AbstractFileSystem): """Async file operations, default implementations
Passes bulk operations to asyncio.gather for concurrent operation.
Implementations that have concurrent batch operations and/or async methods should inherit from this class instead of AbstractFileSystem. Docstrings are copied from the un-underscored method in AbstractFileSystem, if not given. """
# note that methods do not have docstring here; they will be copied # for _* methods and inferred for overridden methods.
async_impl = True mirror_sync_methods = True disable_throttling = False
def __init__(self, *args, asynchronous=False, loop=None, batch_size=None, **kwargs): self.asynchronous = asynchronous self._pid = os.getpid() if not asynchronous: self._loop = loop or get_loop() else: self._loop = None self.batch_size = batch_size super().__init__(*args, **kwargs)
@property def loop(self): if self._pid != os.getpid(): raise RuntimeError("This class is not fork-safe") return self._loop
async def _rm_file(self, path, **kwargs): if ( inspect.iscoroutinefunction(self._rm) and type(self)._rm is not AsyncFileSystem._rm ): return await self._rm(path, recursive=False, batch_size=1, **kwargs) raise NotImplementedError
async def _rm( self, path, recursive=False, batch_size=None, maxdepth=None, **kwargs ): # TODO: implement on_error batch_size = batch_size or self.batch_size path = await self._expand_path(path, recursive=recursive, maxdepth=maxdepth) return await _run_coros_in_chunks( [self._rm_file(p, **kwargs) for p in reversed(path)], batch_size=batch_size, nofiles=True, )
async def _cp_file(self, path1, path2, **kwargs): raise NotImplementedError
async def _mv_file(self, path1, path2): await self._cp_file(path1, path2) await self._rm_file(path1)
async def _copy( self, path1, path2, recursive=False, on_error=None, maxdepth=None, batch_size=None, **kwargs, ): if on_error is None and recursive: on_error = "ignore" elif on_error is None: on_error = "raise"
if isinstance(path1, list) and isinstance(path2, list): # No need to expand paths when both source and destination # are provided as lists paths1 = path1 paths2 = path2 else: source_is_str = isinstance(path1, str) paths1 = await self._expand_path( path1, maxdepth=maxdepth, recursive=recursive ) if source_is_str and (not recursive or maxdepth is not None): # Non-recursive glob does not copy directories paths1 = [ p for p in paths1 if not (trailing_sep(p) or await self._isdir(p)) ] if not paths1: return
source_is_file = len(paths1) == 1 dest_is_dir = isinstance(path2, str) and ( trailing_sep(path2) or await self._isdir(path2) )
exists = source_is_str and ( (has_magic(path1) and source_is_file) or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1)) ) paths2 = other_paths( paths1, path2, exists=exists, flatten=not source_is_str, )
batch_size = batch_size or self.batch_size coros = [self._cp_file(p1, p2, **kwargs) for p1, p2 in zip(paths1, paths2)] result = await _run_coros_in_chunks( coros, batch_size=batch_size, return_exceptions=True, nofiles=True )
for ex in filter(is_exception, result): if on_error == "ignore" and isinstance(ex, FileNotFoundError): continue try: raise ex finally: del ex, result
async def _pipe_file(self, path, value, mode="overwrite", **kwargs): raise NotImplementedError
async def _pipe(self, path, value=None, batch_size=None, **kwargs): if isinstance(path, str): path = {path: value} batch_size = batch_size or self.batch_size return await _run_coros_in_chunks( [self._pipe_file(k, v, **kwargs) for k, v in path.items()], batch_size=batch_size, nofiles=True, )
async def _process_limits(self, url, start, end): """Helper for "Range"-based _cat_file""" size = None suff = False if start is not None and start < 0: # if start is negative and end None, end is the "suffix length" if end is None: end = -start start = "" suff = True else: size = size or (await self._info(url))["size"] start = size + start elif start is None: start = 0 if not suff: if end is not None and end < 0: if start is not None: size = size or (await self._info(url))["size"] end = size + end elif end is None: end = "" if isinstance(end, numbers.Integral): end -= 1 # bytes range is inclusive return f"bytes={start}-{end}"
async def _cat_file(self, path, start=None, end=None, **kwargs): raise NotImplementedError
async def _cat( self, path, recursive=False, on_error="raise", batch_size=None, **kwargs ): paths = await self._expand_path(path, recursive=recursive) coros = [self._cat_file(path, **kwargs) for path in paths] batch_size = batch_size or self.batch_size out = await _run_coros_in_chunks( coros, batch_size=batch_size, nofiles=True, return_exceptions=True ) if on_error == "raise": ex = next(filter(is_exception, out), False) if ex: try: raise ex finally: del ex, out if ( len(paths) > 1 or isinstance(path, list) or paths[0] != self._strip_protocol(path) ): return { k: v for k, v in zip(paths, out) if on_error != "omit" or not is_exception(v) } else: return out[0]
async def _cat_ranges( self, paths, starts, ends, max_gap=None, batch_size=None, on_error="return", **kwargs, ): """Get the contents of byte ranges from one or more files
Parameters ---------- paths: list A list of of filepaths on this filesystems starts, ends: int or list Bytes limits of the read. If using a single int, the same value will be used to read all the specified files. on_error: "return" or "raise" If "return" (default), any per-range exception is placed in the output list at the corresponding position. Otherwise the first such exception is raised. Matches ``AbstractFileSystem.cat_ranges``. """ if max_gap is not None: # use utils.merge_offset_ranges raise NotImplementedError if not isinstance(paths, list): raise TypeError if not isinstance(starts, Iterable): starts = [starts] * len(paths) if not isinstance(ends, Iterable): ends = [ends] * len(paths) if len(starts) != len(paths) or len(ends) != len(paths): raise ValueError coros = [ self._cat_file(p, start=s, end=e, **kwargs) for p, s, e in zip(paths, starts, ends) ] batch_size = batch_size or self.batch_size out = await _run_coros_in_chunks( coros, batch_size=batch_size, nofiles=True, return_exceptions=True ) if on_error != "return": ex = next(filter(is_exception, out), None) if ex is not None: try: raise ex finally: del ex, out return out
async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs): raise NotImplementedError
async def _put( self, lpath, rpath, recursive=False, callback=DEFAULT_CALLBACK, batch_size=None, maxdepth=None, **kwargs, ): """Copy file(s) from local.
Copies a specific file or tree of files (if recursive=True). If rpath ends with a "/", it will be assumed to be a directory, and target files will go within.
The put_file method will be called concurrently on a batch of files. The batch_size option can configure the amount of futures that can be executed at the same time. If it is -1, then all the files will be uploaded concurrently. The default can be set for this instance by passing "batch_size" in the constructor, or for all instances by setting the "gather_batch_size" key in ``fsspec.config.conf``, falling back to 1/8th of the system limit . """ if isinstance(lpath, list) and isinstance(rpath, list): # No need to expand paths when both source and destination # are provided as lists rpaths = rpath lpaths = lpath else: source_is_str = isinstance(lpath, str) if source_is_str: lpath = make_path_posix(lpath) fs = LocalFileSystem() lpaths = fs.expand_path(lpath, recursive=recursive, maxdepth=maxdepth) if source_is_str and (not recursive or maxdepth is not None): # Non-recursive glob does not copy directories lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))] if not lpaths: return
source_is_file = len(lpaths) == 1 dest_is_dir = isinstance(rpath, str) and ( trailing_sep(rpath) or await self._isdir(rpath) )
rpath = self._strip_protocol(rpath) exists = source_is_str and ( (has_magic(lpath) and source_is_file) or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath)) ) rpaths = other_paths( lpaths, rpath, exists=exists, flatten=not source_is_str, )
is_dir = {l: os.path.isdir(l) for l in lpaths} rdirs = [r for l, r in zip(lpaths, rpaths) if is_dir[l]] file_pairs = [(l, r) for l, r in zip(lpaths, rpaths) if not is_dir[l]]
await asyncio.gather(*[self._makedirs(d, exist_ok=True) for d in rdirs]) batch_size = batch_size or self.batch_size
coros = [] callback.set_size(len(file_pairs)) for lfile, rfile in file_pairs: put_file = callback.branch_coro(self._put_file) coros.append(put_file(lfile, rfile, **kwargs))
return await _run_coros_in_chunks( coros, batch_size=batch_size, callback=callback )
async def _get_file(self, rpath, lpath, **kwargs): raise NotImplementedError
async def _get( self, rpath, lpath, recursive=False, callback=DEFAULT_CALLBACK, maxdepth=None, **kwargs, ): """Copy file(s) to local.
Copies a specific file or tree of files (if recursive=True). If lpath ends with a "/", it will be assumed to be a directory, and target files will go within. Can submit a list of paths, which may be glob-patterns and will be expanded.
The get_file method will be called concurrently on a batch of files. The batch_size option can configure the amount of futures that can be executed at the same time. If it is -1, then all the files will be uploaded concurrently. The default can be set for this instance by passing "batch_size" in the constructor, or for all instances by setting the "gather_batch_size" key in ``fsspec.config.conf``, falling back to 1/8th of the system limit . """ if isinstance(lpath, list) and isinstance(rpath, list): # No need to expand paths when both source and destination # are provided as lists rpaths = rpath lpaths = lpath else: source_is_str = isinstance(rpath, str) # First check for rpath trailing slash as _strip_protocol removes it. source_not_trailing_sep = source_is_str and not trailing_sep(rpath) rpath = self._strip_protocol(rpath) rpaths = await self._expand_path( rpath, recursive=recursive, maxdepth=maxdepth ) if source_is_str and (not recursive or maxdepth is not None): # Non-recursive glob does not copy directories rpaths = [ p for p in rpaths if not (trailing_sep(p) or await self._isdir(p)) ] if not rpaths: return
lpath = make_path_posix(lpath) source_is_file = len(rpaths) == 1 dest_is_dir = isinstance(lpath, str) and ( trailing_sep(lpath) or LocalFileSystem().isdir(lpath) )
exists = source_is_str and ( (has_magic(rpath) and source_is_file) or (not has_magic(rpath) and dest_is_dir and source_not_trailing_sep) ) lpaths = other_paths( rpaths, lpath, exists=exists, flatten=not source_is_str, ) if isinstance(lpath, str): # The names came from the source listing; ".." in one of them # would otherwise place the copy above the destination. When # lpath is a list the caller named every destination itself. check_contained(lpath, lpaths)
[os.makedirs(os.path.dirname(lp), exist_ok=True) for lp in lpaths] batch_size = kwargs.pop("batch_size", self.batch_size)
coros = [] callback.set_size(len(lpaths)) for lpath, rpath in zip(lpaths, rpaths): get_file = callback.branch_coro(self._get_file) coros.append(get_file(rpath, lpath, **kwargs)) return await _run_coros_in_chunks( coros, batch_size=batch_size, callback=callback )
async def _isfile(self, path): try: return (await self._info(path))["type"] == "file" except Exception: return False
async def _isdir(self, path): try: return (await self._info(path))["type"] == "directory" except OSError: return False
async def _size(self, path): return (await self._info(path)).get("size", None)
async def _sizes(self, paths, batch_size=None): batch_size = batch_size or self.batch_size return await _run_coros_in_chunks( [self._size(p) for p in paths], batch_size=batch_size )
async def _exists(self, path, **kwargs): try: await self._info(path, **kwargs) return True except FileNotFoundError: return False
async def _info(self, path, **kwargs): raise NotImplementedError
async def _ls(self, path, detail=True, **kwargs): raise NotImplementedError
async def _walk(self, path, maxdepth=None, topdown=True, on_error="omit", **kwargs): if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1")
path = self._strip_protocol(path) full_dirs = {} dirs = {} files = {}
detail = kwargs.pop("detail", False) try: listing = await self._ls(path, detail=True, **kwargs) except (FileNotFoundError, OSError) as e: if on_error == "raise": raise elif callable(on_error): on_error(e) if detail: yield path, {}, {} else: yield path, [], [] return
for info in listing: # each info name must be at least [path]/part , but here # we check also for names like [path]/part/ pathname = info["name"].rstrip("/") name = pathname.rsplit("/", 1)[-1] if info["type"] == "directory" and pathname != path: # do not include "self" path full_dirs[name] = pathname dirs[name] = info elif pathname == path: # file-like with same name as give path files[""] = info else: files[name] = info
if not detail: dirs = list(dirs) files = list(files)
if topdown: # Yield before recursion if walking top down yield path, dirs, files
if maxdepth is not None: maxdepth -= 1 if maxdepth < 1: if not topdown: yield path, dirs, files return
for d in dirs: async for _ in self._walk( full_dirs[d], maxdepth=maxdepth, detail=detail, topdown=topdown, on_error=on_error, **kwargs, ): yield _
if not topdown: # Yield after recursion if walking bottom up yield path, dirs, files
async def _glob(self, path, maxdepth=None, **kwargs): if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1")
import re
seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,) ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash path = self._strip_protocol(path) append_slash_to_dirname = ends_with_sep or path.endswith( tuple(sep + "**" for sep in seps) ) idx_star = path.find("*") if path.find("*") >= 0 else len(path) idx_qmark = path.find("?") if path.find("?") >= 0 else len(path) idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
min_idx = min(idx_star, idx_qmark, idx_brace)
detail = kwargs.pop("detail", False) withdirs = kwargs.pop("withdirs", True)
if not has_magic(path): if await self._exists(path, **kwargs): if not detail: return [path] else: return {path: await self._info(path, **kwargs)} else: if not detail: return [] # glob of non-existent returns empty else: return {} elif "/" in path[:min_idx]: first_wildcard_idx = min_idx min_idx = path[:min_idx].rindex("/") root = path[ : min_idx + 1 ] # everything up to the last / before the first wildcard prefix = path[ min_idx + 1 : first_wildcard_idx ] # stem between last "/" and first wildcard depth = path[min_idx + 1 :].count("/") + 1 else: root = "" prefix = path[:min_idx] # stem up to the first wildcard depth = path[min_idx + 1 :].count("/") + 1
if "**" in path: if maxdepth is not None: idx_double_stars = path.find("**") depth_double_stars = path[idx_double_stars:].count("/") + 1 depth = depth - depth_double_stars + maxdepth else: depth = None
# Pass the filename stem as prefix= so backends that support it such as # gcsfs, s3fs and adlfs can filter server-side up to the first wildcard. if prefix: kwargs["prefix"] = prefix allpaths = await self._find( root, maxdepth=depth, withdirs=withdirs, detail=True, **kwargs )
pattern = glob_translate(path + ("/" if ends_with_sep else "")) pattern = re.compile(pattern)
out = { p: info for p, info in sorted(allpaths.items()) if pattern.match( p + "/" if append_slash_to_dirname and info["type"] == "directory" else p ) }
if detail: return out else: return list(out)
async def _du(self, path, total=True, maxdepth=None, **kwargs): sizes = {} # async for? for f in await self._find(path, maxdepth=maxdepth, **kwargs): info = await self._info(f) sizes[info["name"]] = info["size"] if total: return sum(sizes.values()) else: return sizes
async def _find(self, path, maxdepth=None, withdirs=False, **kwargs): path = self._strip_protocol(path) out = {} detail = kwargs.pop("detail", False)
# Add the root directory if withdirs is requested # This is needed for posix glob compliance if withdirs and path != "" and await self._isdir(path): out[path] = await self._info(path)
# async for? async for _, dirs, files in self._walk(path, maxdepth, detail=True, **kwargs): if withdirs: files.update(dirs) out.update({info["name"]: info for name, info in files.items()}) if not out and (await self._isfile(path)): # walk works on directories, but find should also return [path] # when path happens to be a file out[path] = {} names = sorted(out) if not detail: return names else: return {name: out[name] for name in names}
async def _expand_path( self, path, recursive=False, maxdepth=None, assume_literal=False ): if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1")
if isinstance(path, str): out = await self._expand_path([path], recursive, maxdepth) else: out = set() path = [self._strip_protocol(p) for p in path] for p in path: # can gather here if not assume_literal and has_magic(p): bit = set(await self._glob(p, maxdepth=maxdepth)) out |= bit if recursive: # glob call above expanded one depth so if maxdepth is defined # then decrement it in expand_path call below. If it is zero # after decrementing then avoid expand_path call. if maxdepth is not None and maxdepth <= 1: continue out |= set( await self._expand_path( list(bit), recursive=recursive, maxdepth=maxdepth - 1 if maxdepth is not None else None, assume_literal=True, ) ) continue elif recursive: rec = set(await self._find(p, maxdepth=maxdepth, withdirs=True)) out |= rec if p not in out and (recursive is False or (await self._exists(p))): # should only check once, for the root out.add(p) if not out: raise FileNotFoundError(path) return sorted(out)
async def _mkdir(self, path, create_parents=True, **kwargs): pass # not necessary to implement, may not have directories
async def _makedirs(self, path, exist_ok=False): pass # not necessary to implement, may not have directories
async def open_async(self, path, mode="rb", **kwargs): if "b" not in mode or kwargs.get("compression"): raise ValueError raise NotImplementedError
def mirror_sync_methods(obj): """Populate sync and async methods for obj
For each method will create a sync version if the name refers to an async method (coroutine) and there is no override in the child class; will create an async method for the corresponding sync method if there is no implementation.
Uses the methods specified in - async_methods: the set that an implementation is expected to provide - default_async_methods: that can be derived from their sync version in AbstractFileSystem - AsyncFileSystem: async-specific default coroutines """ from fsspec import AbstractFileSystem
for method in set(async_methods + dir(AsyncFileSystem)): if not method.startswith("_"): continue smethod = method[1:] if private.match(method): isco = inspect.iscoroutinefunction(getattr(obj, method, None)) unsync = getattr(getattr(obj, smethod, False), "__func__", None) is_default = unsync is getattr(AbstractFileSystem, smethod, "") if isco and is_default: mth = sync_wrapper(getattr(obj, method), obj=obj) elif inspect.isasyncgenfunction(getattr(obj, method, None)) and is_default: mth = async_gen_wrapper(getattr(obj, method), obj=obj) else: continue setattr(obj, smethod, mth) if not mth.__doc__: mth.__doc__ = getattr( getattr(AbstractFileSystem, smethod, None), "__doc__", "" )
class FSSpecCoroutineCancel(Exception): pass
def _dump_running_tasks( printout=True, cancel=True, exc=FSSpecCoroutineCancel, with_task=False): import traceback
tasks = [t for t in asyncio.tasks.all_tasks(loop[0]) if not t.done()] if printout: [task.print_stack() for task in tasks] out = [ { "locals": task._coro.cr_frame.f_locals, "file": task._coro.cr_frame.f_code.co_filename, "firstline": task._coro.cr_frame.f_code.co_firstlineno, "linelo": task._coro.cr_frame.f_lineno, "stack": traceback.format_stack(task._coro.cr_frame), "task": task if with_task else None, } for task in tasks ] if cancel: for t in tasks: cbs = t._callbacks t.cancel() asyncio.futures.Future.set_exception(t, exc) asyncio.futures.Future.cancel(t) [cb[0](t) for cb in cbs] # cancels any dependent concurrent.futures try: t._coro.throw(exc) # exits coro, unless explicitly handled except exc: pass return out
class AbstractAsyncStreamedFile(AbstractBufferedFile): # no read buffering, and always auto-commit # TODO: readahead might still be useful here, but needs async version
async def read(self, length=-1): """ Return data from cache, or fetch pieces as necessary
Parameters ---------- length: int (-1) Number of bytes to read; if <0, all remaining bytes. """ length = -1 if length is None else int(length) if self.mode != "rb": raise ValueError("File not in read mode") if length < 0: length = self.size - self.loc if self.closed: raise ValueError("I/O operation on closed file.") if length == 0: # don't even bother calling fetch return b"" out = await self._fetch_range(self.loc, self.loc + length) self.loc += len(out) return out
async def write(self, data): """ Write data to buffer.
Buffer only sent on flush() or if buffer is greater than or equal to blocksize.
Parameters ---------- data: bytes Set of bytes to be written. """ if self.mode not in {"wb", "ab"}: raise ValueError("File not in write mode") if self.closed: raise ValueError("I/O operation on closed file.") if self.forced: raise ValueError("This file has been force-flushed, can only close") out = self.buffer.write(data) self.loc += out if self.buffer.tell() >= self.blocksize: await self.flush() return out
async def close(self): """Close file
Finalizes writes, discards cache """ if getattr(self, "_unclosable", False): return if self.closed: return if self.mode == "rb": self.cache = None else: if not self.forced: await self.flush(force=True)
if self.fs is not None: self.fs.invalidate_cache(self.path) self.fs.invalidate_cache(self.fs._parent(self.path))
self.closed = True
async def flush(self, force=False): if self.closed: raise ValueError("Flush on closed file") if force and self.forced: raise ValueError("Force flush cannot be called more than once") if force: self.forced = True
if self.mode not in {"wb", "ab"}: # no-op to flush on read-mode return
if not force and self.buffer.tell() < self.blocksize: # Defer write on small block return
if self.offset is None: # Initialize a multipart upload self.offset = 0 try: await self._initiate_upload() except: self.closed = True raise
if await self._upload_chunk(final=force) is not False: self.offset += self.buffer.seek(0, 2) self.buffer = io.BytesIO()
async def __aenter__(self): return self
async def __aexit__(self, exc_type, exc_val, exc_tb): await self.close()
async def _fetch_range(self, start, end): raise NotImplementedError
async def _initiate_upload(self): pass
async def _upload_chunk(self, final=False): raise NotImplementedError123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158from __future__ import annotations
import asyncioimport collectionsimport functoolsimport loggingimport mathimport osimport threadingfrom collections import OrderedDictfrom collections.abc import Callablefrom concurrent.futures import Future, ThreadPoolExecutorfrom itertools import groupbyfrom operator import itemgetterfrom typing import TYPE_CHECKING, Any, ClassVar, Generic, NamedTuple, TypeVar
if TYPE_CHECKING: import mmap
from typing_extensions import ParamSpec
P = ParamSpec("P")else: P = TypeVar("P")
T = TypeVar("T")
logger = logging.getLogger("fsspec.caching")
Fetcher = Callable[[int, int], bytes] # Maps (start, end) to bytesMultiFetcher = Callable[[list[int, int]], bytes] # Maps [(start, end)] to bytes
class BaseCache: """Pass-though cache: doesn't keep anything, calls every time
Acts as base class for other cachers
Parameters ---------- blocksize: int How far to read ahead in numbers of bytes fetcher: func Function of the form f(start, end) which gets bytes from remote as specified size: int How big this file is """
name: ClassVar[str] = "none"
def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None: self.blocksize = blocksize self.nblocks = 0 self.fetcher = fetcher self.size = size self.hit_count = 0 self.miss_count = 0 # the bytes that we actually requested self.total_requested_bytes = 0
def _fetch(self, start: int | None, stop: int | None) -> bytes: if start is None: start = 0 if stop is None: stop = self.size if start >= self.size or start >= stop: return b"" return self.fetcher(start, stop)
def _reset_stats(self) -> None: """Reset hit and miss counts for a more ganular report e.g. by file.""" self.hit_count = 0 self.miss_count = 0 self.total_requested_bytes = 0
def _log_stats(self) -> str: """Return a formatted string of the cache statistics.""" if self.hit_count == 0 and self.miss_count == 0: # a cache that does nothing, this is for logs only return "" return f" , {self.name}: {self.hit_count} hits, {self.miss_count} misses, {self.total_requested_bytes} total requested bytes"
def __repr__(self) -> str: # TODO: use rich for better formatting return f""" <{self.__class__.__name__}: block size : {self.blocksize} block count : {self.nblocks} file size : {self.size} cache hits : {self.hit_count} cache misses: {self.miss_count} total requested bytes: {self.total_requested_bytes}> """
class MMapCache(BaseCache): """memory-mapped sparse file cache
Opens temporary file, which is filled blocks-wise when data is requested. Ensure there is enough disc space in the temporary location.
This cache method might only work on posix
Parameters ---------- blocksize: int How far to read ahead in numbers of bytes fetcher: Fetcher Function of the form f(start, end) which gets bytes from remote as specified size: int How big this file is location: str Where to create the temporary file. If None, a temporary file is created using tempfile.TemporaryFile(). blocks: set[int] Set of block numbers that have already been fetched. If None, an empty set is created. multi_fetcher: MultiFetcher Function of the form f([(start, end)]) which gets bytes from remote as specified. This function is used to fetch multiple blocks at once. If not specified, the fetcher function is used instead. """
name = "mmap"
def __init__( self, blocksize: int, fetcher: Fetcher, size: int, location: str | None = None, blocks: set[int] | None = None, multi_fetcher: MultiFetcher | None = None, ) -> None: super().__init__(blocksize, fetcher, size) self.blocks = set() if blocks is None else blocks self.location = location self.multi_fetcher = multi_fetcher self.cache = self._makefile()
def _makefile(self) -> mmap.mmap | bytearray: import mmap import tempfile
if self.size == 0: return bytearray()
# posix version if self.location is None or not os.path.exists(self.location): self.blocks.clear() if self.location is None: fd = tempfile.TemporaryFile() else: fd = open(self.location, "wb+") fd.seek(self.size - 1) fd.write(b"1") fd.flush() else: fd = open(self.location, "r+b")
return mmap.mmap(fd.fileno(), self.size)
def _fetch(self, start: int | None, end: int | None) -> bytes: logger.debug(f"MMap cache fetching {start}-{end}") if start is None: start = 0 if end is None: end = self.size if start >= self.size or start >= end: return b"" start_block = start // self.blocksize end_block = end // self.blocksize block_range = range(start_block, end_block + 1) # Determine which blocks need to be fetched. This sequence is sorted by construction. need = (i for i in block_range if i not in self.blocks) # Count the number of blocks already cached self.hit_count += sum(1 for i in block_range if i in self.blocks)
ranges = [] block_groups = []
# Consolidate needed blocks. # Algorithm adapted from Python 2.x itertools documentation. # We are grouping an enumerated sequence of blocks. By comparing when the difference # between an ascending range (provided by enumerate) and the needed block numbers # we can detect when the block number skips values. The key computes this difference. # Whenever the difference changes, we know that we have previously cached block(s), # and a new group is started. In other words, this algorithm neatly groups # runs of consecutive block numbers so they can be fetched together. for _, _blocks in groupby(enumerate(need), key=lambda x: x[0] - x[1]): # Extract the blocks from the enumerated sequence _blocks = tuple(map(itemgetter(1), _blocks)) # Compute start of first block sstart = _blocks[0] * self.blocksize # Compute the end of the last block. Last block may not be full size. send = min(_blocks[-1] * self.blocksize + self.blocksize, self.size)
# Fetch bytes (could be multiple consecutive blocks) self.total_requested_bytes += send - sstart logger.debug( f"MMap get blocks {_blocks[0]}-{_blocks[-1]} ({sstart}-{send})" ) ranges.append((sstart, send)) block_groups.append(_blocks) # Update cache statistics with number of blocks we had to cache self.miss_count += len(_blocks)
if not ranges: return self.cache[start:end]
if self.multi_fetcher: logger.debug(f"MMap get blocks {ranges}") for idx, r in enumerate(self.multi_fetcher(ranges)): sstart, send = ranges[idx] logger.debug(f"MMap copy block ({sstart}-{send}") self.cache[sstart:send] = r self.blocks.update(block_groups[idx]) else: for idx, (sstart, send) in enumerate(ranges): logger.debug(f"MMap get block ({sstart}-{send}") self.cache[sstart:send] = self.fetcher(sstart, send) self.blocks.update(block_groups[idx])
return self.cache[start:end]
def close(self) -> None: if hasattr(self.cache, "close"): self.cache.close()
def __getstate__(self) -> dict[str, Any]: state = self.__dict__.copy() # Remove the unpicklable entries. del state["cache"] return state
def __setstate__(self, state: dict[str, Any]) -> None: # Restore instance attributes self.__dict__.update(state) self.cache = self._makefile()
class ReadAheadCache(BaseCache): """Cache which reads only when we get beyond a block of data
This is a much simpler version of BytesCache, and does not attempt to fill holes in the cache or keep fragments alive. It is best suited to many small reads in a sequential order (e.g., reading lines from a file). """
name = "readahead"
def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None: super().__init__(blocksize, fetcher, size) self.cache = b"" self.start = 0 self.end = 0
def _fetch(self, start: int | None, end: int | None) -> bytes: if start is None: start = 0 if end is None or end > self.size: end = self.size if start >= self.size or start >= end: return b"" l = end - start if start >= self.start and end <= self.end: # cache hit self.hit_count += 1 return self.cache[start - self.start : end - self.start] elif self.start <= start < self.end: # partial hit self.miss_count += 1 part = self.cache[start - self.start :] l -= len(part) start = self.end else: # miss self.miss_count += 1 part = b"" end = min(self.size, end + self.blocksize) self.total_requested_bytes += end - start self.cache = self.fetcher(start, end) # new block replaces old self.start = start self.end = self.start + len(self.cache) return part + self.cache[:l]
class AdaptiveReadaheadCache(BaseCache): """Cache with adaptive asynchronous prefetching.
Optimized for sequential and near-sequential reads by dynamically adjusting the amount of data prefetched in the background. The cache uses the generic prefetch engine when async loop support is available, and falls back to ``ReadAheadCache`` when it is not.
Parameters ---------- blocksize: int Nominal read size used by callers. fetcher: Fetcher Function of the form ``f(start, end)`` that returns bytes. size: int Total size of the file. concurrency: int Maximum number of concurrent background fetch tasks. max_prefetch_size: int | None Optional upper bound for adaptive prefetch size in bytes. """
name = "adaptive"
def __init__( self, blocksize: int, fetcher: Fetcher, size: int, concurrency: int = 4, max_prefetch_size: int | None = None, ) -> None: super().__init__(blocksize, fetcher, size) self._fallback = ReadAheadCache(blocksize, fetcher, size) self._prefetcher = None
async def _default_fetcher_async( start_offset: int, total_size: int, split_factor: int = 1, ) -> bytes: del split_factor return await asyncio.to_thread( self.fetcher, start_offset, start_offset + total_size )
try: from . import asyn as fsspec_asyn except ImportError as e: raise ImportError( "AdaptiveReadaheadCache requires fsspec.asyn to be available" ) from e
try: from .prefetcher import BackgroundPrefetcher
try: fs_loop = fetcher.__self__.fs.loop except AttributeError: fs_loop = None self._prefetcher = BackgroundPrefetcher( fetcher=_default_fetcher_async, size=size, concurrency=concurrency, max_prefetch_size=max_prefetch_size, loop=( fs_loop if isinstance(fs_loop, asyncio.AbstractEventLoop) else fsspec_asyn.get_loop() ), ) logger.info( "AdaptiveReadaheadCache enabled (blocksize=%d, size=%d, concurrency=%d, max_prefetch_size=%s)", blocksize, size, concurrency, max_prefetch_size, ) except Exception as e: logger.info( "AdaptiveReadaheadCache fallback to ReadAheadCache: %s", e, exc_info=True, ) self._prefetcher = None
def _fetch(self, start: int | None, end: int | None) -> bytes: if self._prefetcher is None: out = self._fallback._fetch(start, end) self.hit_count = self._fallback.hit_count self.miss_count = self._fallback.miss_count self.total_requested_bytes = self._fallback.total_requested_bytes return out
out = self._prefetcher.fetch(start, end) self.miss_count += 1 self.total_requested_bytes += len(out) return out
def close(self) -> None: if self._prefetcher is not None: self._prefetcher.close() self._prefetcher = None
def __getstate__(self) -> dict[str, Any]: # The prefetcher owns asyncio primitives that are not picklable. self.close() state = self.__dict__.copy() state["_prefetcher"] = None return state
def __setstate__(self, state: dict[str, Any]) -> None: self.__dict__.update(state) self._prefetcher = None
def __del__(self): try: self.close() except Exception: # Best-effort cleanup during GC. pass
class FirstChunkCache(BaseCache): """Caches the first block of a file only
This may be useful for file types where the metadata is stored in the header, but is randomly accessed. """
name = "first"
def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None: if blocksize > size: # this will buffer the whole thing blocksize = size super().__init__(blocksize, fetcher, size) self.cache: bytes | None = None
def _fetch(self, start: int | None, end: int | None) -> bytes: start = start or 0 if start > self.size: logger.debug("FirstChunkCache: requested start > file size") return b""
if end is None: end = self.size end = min(end, self.size)
if start < self.blocksize: if self.cache is None: self.miss_count += 1 if end > self.blocksize: self.total_requested_bytes += end data = self.fetcher(0, end) self.cache = data[: self.blocksize] return data[start:] self.cache = self.fetcher(0, self.blocksize) self.total_requested_bytes += self.blocksize part = self.cache[start:end] if end > self.blocksize: self.total_requested_bytes += end - self.blocksize part += self.fetcher(self.blocksize, end) self.hit_count += 1 return part else: self.miss_count += 1 self.total_requested_bytes += end - start return self.fetcher(start, end)
class BlockCache(BaseCache): """ Cache holding memory as a set of blocks.
Requests are only ever made ``blocksize`` at a time, and are stored in an LRU cache. The least recently accessed block is discarded when more than ``maxblocks`` are stored.
Parameters ---------- blocksize : int The number of bytes to store in each block. Requests are only ever made for ``blocksize``, so this should balance the overhead of making a request against the granularity of the blocks. fetcher : Callable size : int The total size of the file being cached. maxblocks : int The maximum number of blocks to cache for. The maximum memory use for this cache is then ``blocksize * maxblocks``. """
name = "blockcache"
def __init__( self, blocksize: int, fetcher: Fetcher, size: int, maxblocks: int = 32 ) -> None: super().__init__(blocksize, fetcher, size) self.nblocks = math.ceil(size / blocksize) self.maxblocks = maxblocks self._fetch_block_cached = functools.lru_cache(maxblocks)(self._fetch_block)
def cache_info(self): """ The statistics on the block cache.
Returns ------- NamedTuple Returned directly from the LRU Cache used internally. """ return self._fetch_block_cached.cache_info()
def __getstate__(self) -> dict[str, Any]: state = self.__dict__.copy() del state["_fetch_block_cached"] return state
def __setstate__(self, state: dict[str, Any]) -> None: self.__dict__.update(state) self._fetch_block_cached = functools.lru_cache(state["maxblocks"])( self._fetch_block )
def _fetch(self, start: int | None, end: int | None) -> bytes: if start is None: start = 0 if end is None or end > self.size: end = self.size if start >= self.size or start >= end: return b""
return self._read_cache( start, end, start // self.blocksize, (end - 1) // self.blocksize )
def _fetch_block(self, block_number: int) -> bytes: """ Fetch the block of data for `block_number`. """ if block_number > self.nblocks: raise ValueError( f"'block_number={block_number}' is greater than " f"the number of blocks ({self.nblocks})" )
start = block_number * self.blocksize if start >= self.size: return b"" end = min(start + self.blocksize, self.size) self.total_requested_bytes += end - start self.miss_count += 1 logger.info("BlockCache fetching block %d", block_number) block_contents = super()._fetch(start, end) return block_contents
def _read_cache( self, start: int, end: int, start_block_number: int, end_block_number: int ) -> bytes: """ Read from our block cache.
Parameters ---------- start, end : int The start and end byte positions. start_block_number, end_block_number : int The start and end block numbers. """ start_pos = start % self.blocksize end_pos = end % self.blocksize if end_pos == 0: end_pos = self.blocksize
self.hit_count += 1 if start_block_number == end_block_number: block: bytes = self._fetch_block_cached(start_block_number) return block[start_pos:end_pos]
else: # read from the initial out = [self._fetch_block_cached(start_block_number)[start_pos:]]
# intermediate blocks # Note: it'd be nice to combine these into one big request. However # that doesn't play nicely with our LRU cache. out.extend( map( self._fetch_block_cached, range(start_block_number + 1, end_block_number), ) )
# final block out.append(self._fetch_block_cached(end_block_number)[:end_pos])
return b"".join(out)
class BytesCache(BaseCache): """Cache which holds data in a in-memory bytes object
Implements read-ahead by the block size, for semi-random reads progressing through the file.
Parameters ---------- trim: bool As we read more data, whether to discard the start of the buffer when we are more than a blocksize ahead of it. """
name: ClassVar[str] = "bytes"
def __init__( self, blocksize: int, fetcher: Fetcher, size: int, trim: bool = True ) -> None: super().__init__(blocksize, fetcher, size) self.cache = b"" self.start: int | None = None self.end: int | None = None self.trim = trim
def _fetch(self, start: int | None, end: int | None) -> bytes: # TODO: only set start/end after fetch, in case it fails? # is this where retry logic might go? if start is None: start = 0 if end is None: end = self.size if start >= self.size or start >= end: return b"" if ( self.start is not None and start >= self.start and self.end is not None and end <= self.end ): # cache hit: we have all the required data offset = start - self.start self.hit_count += 1 return self.cache[offset : offset + end - start]
if self.blocksize: bend = min(self.size, end + self.blocksize) else: bend = end
if bend == start or start > self.size: return b""
if (self.start is None or start < self.start) and ( self.end is None or end > self.end ): # First read, or extending both before and after self.total_requested_bytes += bend - start self.miss_count += 1 self.cache = self.fetcher(start, bend) self.start = start else: assert self.start is not None assert self.end is not None self.miss_count += 1
if start < self.start: if self.end is None or self.end - end > self.blocksize: self.total_requested_bytes += bend - start self.cache = self.fetcher(start, bend) self.start = start else: self.total_requested_bytes += self.start - start new = self.fetcher(start, self.start) self.start = start self.cache = new + self.cache elif self.end is not None and bend > self.end: if self.end > self.size: pass elif end - self.end > self.blocksize: self.total_requested_bytes += bend - start self.cache = self.fetcher(start, bend) self.start = start else: self.total_requested_bytes += bend - self.end new = self.fetcher(self.end, bend) self.cache = self.cache + new
self.end = self.start + len(self.cache) offset = start - self.start out = self.cache[offset : offset + end - start] if self.trim: num = (self.end - self.start) // (self.blocksize + 1) if num > 1: self.start += self.blocksize * num self.cache = self.cache[self.blocksize * num :] return out
def __len__(self) -> int: return len(self.cache)
class AllBytes(BaseCache): """Cache entire contents of the file"""
name: ClassVar[str] = "all"
def __init__( self, blocksize: int | None = None, fetcher: Fetcher | None = None, size: int | None = None, data: bytes | None = None, ) -> None: super().__init__(blocksize, fetcher, size) # type: ignore[arg-type] if data is None: self.miss_count += 1 self.total_requested_bytes += self.size data = self.fetcher(0, self.size) self.data = data
def _fetch(self, start: int | None, stop: int | None) -> bytes: self.hit_count += 1 return self.data[start:stop]
class KnownPartsOfAFile(BaseCache): """ Cache holding known file parts.
Parameters ---------- blocksize: int How far to read ahead in numbers of bytes fetcher: func Function of the form f(start, end) which gets bytes from remote as specified size: int How big this file is data: dict A dictionary mapping explicit `(start, stop)` file-offset tuples with known bytes. strict: bool, default True Whether to fetch reads that go beyond a known byte-range boundary. If `False`, any read that ends outside a known part will be zero padded. Note that zero padding will not be used for reads that begin outside a known byte-range. """
name: ClassVar[str] = "parts"
def __init__( self, blocksize: int, fetcher: Fetcher, size: int, data: dict[tuple[int, int], bytes] | None = None, strict: bool = False, **_: Any, ): super().__init__(blocksize, fetcher, size) self.strict = strict
# simple consolidation of contiguous blocks if data: old_offsets = sorted(data.keys()) offsets = [old_offsets[0]] blocks = [data.pop(old_offsets[0])] for start, stop in old_offsets[1:]: start0, stop0 = offsets[-1] if start == stop0: offsets[-1] = (start0, stop) blocks[-1] += data.pop((start, stop)) else: offsets.append((start, stop)) blocks.append(data.pop((start, stop)))
self.data = dict(zip(offsets, blocks)) else: self.data = {}
@property def size(self): return sum(_[1] - _[0] for _ in self.data)
@size.setter def size(self, value): pass
@property def nblocks(self): return len(self.data)
@nblocks.setter def nblocks(self, value): pass
def _fetch(self, start: int | None, stop: int | None) -> bytes: logger.debug("Known parts request %s %s", start, stop) if start is None: start = 0 if stop is None: stop = self.size self.total_requested_bytes += stop - start out = b"" started = False loc_old = 0 for loc0, loc1 in sorted(self.data): if (loc0 <= start < loc1) and (loc0 <= stop <= loc1): # entirely within the block off = start - loc0 self.hit_count += 1 return self.data[(loc0, loc1)][off : off + stop - start] if stop <= loc0: break if started and loc0 > loc_old: # a gap where we need data self.miss_count += 1 if self.strict: raise ValueError out += b"\x00" * (loc0 - loc_old) if loc0 <= start < loc1: # found the start self.hit_count += 1 off = start - loc0 out = self.data[(loc0, loc1)][off : off + stop - start] started = True elif start < loc0 and stop > loc1: # the whole block self.hit_count += 1 out += self.data[(loc0, loc1)] elif started and loc0 <= stop <= loc1: # end block. The start of the request must have been found in # an earlier part, else these bytes come from the wrong offsets self.hit_count += 1 out = out + self.data[(loc0, loc1)][: stop - loc0] return out loc_old = loc1 self.miss_count += 1 if started and not self.strict: out = out + b"\x00" * (stop - loc_old) return out raise ValueError
class UpdatableLRU(Generic[P, T]): """ Custom implementation of LRU cache that allows updating keys
Used by BackgroundBlockCache """
class CacheInfo(NamedTuple): hits: int misses: int maxsize: int currsize: int
def __init__(self, func: Callable[P, T], max_size: int = 128) -> None: self._cache: OrderedDict[Any, T] = collections.OrderedDict() self._func = func self._max_size = max_size self._hits = 0 self._misses = 0 self._lock = threading.Lock()
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: if kwargs: raise TypeError(f"Got unexpected keyword argument {kwargs.keys()}") with self._lock: if args in self._cache: self._cache.move_to_end(args) self._hits += 1 return self._cache[args]
result = self._func(*args, **kwargs)
with self._lock: self._cache[args] = result self._misses += 1 if len(self._cache) > self._max_size: self._cache.popitem(last=False)
return result
def is_key_cached(self, *args: Any) -> bool: with self._lock: return args in self._cache
def add_key(self, result: T, *args: Any) -> None: with self._lock: self._cache[args] = result if len(self._cache) > self._max_size: self._cache.popitem(last=False)
def cache_info(self) -> UpdatableLRU.CacheInfo: with self._lock: return self.CacheInfo( maxsize=self._max_size, currsize=len(self._cache), hits=self._hits, misses=self._misses, )
class BackgroundBlockCache(BaseCache): """ Cache holding memory as a set of blocks with pre-loading of the next block in the background.
Requests are only ever made ``blocksize`` at a time, and are stored in an LRU cache. The least recently accessed block is discarded when more than ``maxblocks`` are stored. If the next block is not in cache, it is loaded in a separate thread in non-blocking way.
Parameters ---------- blocksize : int The number of bytes to store in each block. Requests are only ever made for ``blocksize``, so this should balance the overhead of making a request against the granularity of the blocks. fetcher : Callable size : int The total size of the file being cached. maxblocks : int The maximum number of blocks to cache for. The maximum memory use for this cache is then ``blocksize * maxblocks``. """
name: ClassVar[str] = "background"
def __init__( self, blocksize: int, fetcher: Fetcher, size: int, maxblocks: int = 32 ) -> None: super().__init__(blocksize, fetcher, size) self.nblocks = math.ceil(size / blocksize) self.maxblocks = maxblocks self._fetch_block_cached = UpdatableLRU(self._fetch_block, maxblocks)
self._thread_executor = ThreadPoolExecutor(max_workers=1) self._fetch_future_block_number: int | None = None self._fetch_future: Future[bytes] | None = None self._fetch_future_lock = threading.Lock() self._closed = False
def cache_info(self) -> UpdatableLRU.CacheInfo: """ The statistics on the block cache.
Returns ------- NamedTuple Returned directly from the LRU Cache used internally. """ return self._fetch_block_cached.cache_info()
def close(self) -> None: """Cancel pending work and shut down the background worker.""" with self._fetch_future_lock: if self._closed: return self._closed = True future = self._fetch_future self._fetch_future = None self._fetch_future_block_number = None
if future is not None: future.cancel() self._thread_executor.shutdown(wait=True, cancel_futures=True)
# UpdatableLRU stores a bound method and otherwise forms a reference cycle. del self._fetch_block_cached
def __getstate__(self) -> dict[str, Any]: state = self.__dict__.copy() del state["_fetch_block_cached"] del state["_thread_executor"] del state["_fetch_future_block_number"] del state["_fetch_future"] del state["_fetch_future_lock"] return state
def __setstate__(self, state) -> None: self.__dict__.update(state) self._fetch_block_cached = UpdatableLRU(self._fetch_block, state["maxblocks"]) self._thread_executor = ThreadPoolExecutor(max_workers=1) self._fetch_future_block_number = None self._fetch_future = None self._fetch_future_lock = threading.Lock() self._closed = False
def _fetch(self, start: int | None, end: int | None) -> bytes: if start is None: start = 0 if end is None or end > self.size: end = self.size if start >= self.size or start >= end: return b""
# byte position -> block numbers; ``end`` is exclusive start_block_number = start // self.blocksize end_block_number = (end - 1) // self.blocksize
fetch_future_block_number = None fetch_future = None with self._fetch_future_lock: # Background thread is running. Check we we can or must join it. if self._fetch_future is not None: assert self._fetch_future_block_number is not None if self._fetch_future.done(): logger.info("BlockCache joined background fetch without waiting.") self._fetch_block_cached.add_key( self._fetch_future.result(), self._fetch_future_block_number ) # Cleanup the fetch variables. Done with fetching the block. self._fetch_future_block_number = None self._fetch_future = None else: # Must join if we need the block for the current fetch must_join = bool( start_block_number <= self._fetch_future_block_number <= end_block_number ) if must_join: # Copy to the local variables to release lock # before waiting for result fetch_future_block_number = self._fetch_future_block_number fetch_future = self._fetch_future
# Cleanup the fetch variables. Have a local copy. self._fetch_future_block_number = None self._fetch_future = None
# Need to wait for the future for the current read if fetch_future is not None: logger.info("BlockCache waiting for background fetch.") # Wait until result and put it in cache self._fetch_block_cached.add_key( fetch_future.result(), fetch_future_block_number )
# fetch next block in the background if nothing is running in the background, # the block is within file and it is not already cached end_block_plus_1 = end_block_number + 1 with self._fetch_future_lock: if ( self._fetch_future is None and end_block_plus_1 <= self.nblocks and not self._fetch_block_cached.is_key_cached(end_block_plus_1) ): self._fetch_future_block_number = end_block_plus_1 self._fetch_future = self._thread_executor.submit( self._fetch_block, end_block_plus_1, "async" )
return self._read_cache( start, end, start_block_number=start_block_number, end_block_number=end_block_number, )
def _fetch_block(self, block_number: int, log_info: str = "sync") -> bytes: """ Fetch the block of data for `block_number`. """ if block_number > self.nblocks: raise ValueError( f"'block_number={block_number}' is greater than " f"the number of blocks ({self.nblocks})" )
start = block_number * self.blocksize if start >= self.size: return b"" end = min(start + self.blocksize, self.size) logger.info("BlockCache fetching block (%s) %d", log_info, block_number) self.total_requested_bytes += end - start self.miss_count += 1 block_contents = super()._fetch(start, end) return block_contents
def _read_cache( self, start: int, end: int, start_block_number: int, end_block_number: int ) -> bytes: """ Read from our block cache.
Parameters ---------- start, end : int The start and end byte positions. start_block_number, end_block_number : int The start and end block numbers. """ start_pos = start % self.blocksize end_pos = end % self.blocksize if end_pos == 0: end_pos = self.blocksize
# kind of pointless to count this as a hit, but it is self.hit_count += 1
if start_block_number == end_block_number: block = self._fetch_block_cached(start_block_number) return block[start_pos:end_pos]
else: # read from the initial out = [self._fetch_block_cached(start_block_number)[start_pos:]]
# intermediate blocks # Note: it'd be nice to combine these into one big request. However # that doesn't play nicely with our LRU cache. out.extend( map( self._fetch_block_cached, range(start_block_number + 1, end_block_number), ) )
# final block out.append(self._fetch_block_cached(end_block_number)[:end_pos])
return b"".join(out)
caches: dict[str | None, type[BaseCache]] = { # one custom case None: BaseCache,}
def register_cache(cls: type[BaseCache], clobber: bool = False) -> None: """'Register' cache implementation.
Parameters ---------- clobber: bool, optional If set to True (default is False) - allow to overwrite existing entry.
Raises ------ ValueError """ name = cls.name if not clobber and name in caches: raise ValueError(f"Cache with name {name!r} is already known: {caches[name]}") caches[name] = cls
for c in ( BaseCache, MMapCache, BytesCache, ReadAheadCache, AdaptiveReadaheadCache, BlockCache, FirstChunkCache, AllBytes, KnownPartsOfAFile, BackgroundBlockCache,): register_cache(c)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324from functools import wraps
class Callback: """ Base class and interface for callback mechanism
This class can be used directly for monitoring file transfers by providing ``callback=Callback(hooks=...)`` (see the ``hooks`` argument, below), or subclassed for more specialised behaviour.
Parameters ---------- size: int (optional) Nominal quantity for the value that corresponds to a complete transfer, e.g., total number of tiles or total number of bytes value: int (0) Starting internal counter value hooks: dict or None A dict of named functions to be called on each update. The signature of these must be ``f(size, value, **kwargs)`` """
def __init__(self, size=None, value=0, hooks=None, **kwargs): self.size = size self.value = value self.hooks = hooks or {} self.kw = kwargs
def __enter__(self): return self
def __exit__(self, *exc_args): self.close()
def close(self): """Close callback."""
def branched(self, path_1, path_2, **kwargs): """ Return callback for child transfers
If this callback is operating at a higher level, e.g., put, which may trigger transfers that can also be monitored. The function returns a callback that has to be passed to the child method, e.g., put_file, as `callback=` argument.
The implementation uses `callback.branch` for compatibility. When implementing callbacks, it is recommended to override this function instead of `branch` and avoid calling `super().branched(...)`.
Prefer using this function over `branch`.
Parameters ---------- path_1: str Child's source path path_2: str Child's destination path **kwargs: Arbitrary keyword arguments
Returns ------- callback: Callback A callback instance to be passed to the child method """ self.branch(path_1, path_2, kwargs) # mutate kwargs so that we can force the caller to pass "callback=" explicitly return kwargs.pop("callback", DEFAULT_CALLBACK)
def branch_coro(self, fn): """ Wraps a coroutine, and pass a new child callback to it. """
@wraps(fn) async def func(path1, path2: str, **kwargs): with self.branched(path1, path2, **kwargs) as child: return await fn(path1, path2, callback=child, **kwargs)
return func
def set_size(self, size): """ Set the internal maximum size attribute
Usually called if not initially set at instantiation. Note that this triggers a ``call()``.
Parameters ---------- size: int """ self.size = size self.call()
def absolute_update(self, value): """ Set the internal value state
Triggers ``call()``
Parameters ---------- value: int """ self.value = value self.call()
def relative_update(self, inc=1): """ Delta increment the internal counter
Triggers ``call()``
Parameters ---------- inc: int """ self.value += inc self.call()
def call(self, hook_name=None, **kwargs): """ Execute hook(s) with current state
Each function is passed the internal size and current value
Parameters ---------- hook_name: str or None If given, execute on this hook kwargs: passed on to (all) hook(s) """ if not self.hooks: return kw = self.kw.copy() kw.update(kwargs) if hook_name: if hook_name not in self.hooks: return return self.hooks[hook_name](self.size, self.value, **kw) for hook in self.hooks.values() or []: hook(self.size, self.value, **kw)
def wrap(self, iterable): """ Wrap an iterable to call ``relative_update`` on each iterations
Parameters ---------- iterable: Iterable The iterable that is being wrapped """ for item in iterable: self.relative_update() yield item
def branch(self, path_1, path_2, kwargs): """ Set callbacks for child transfers
If this callback is operating at a higher level, e.g., put, which may trigger transfers that can also be monitored. The passed kwargs are to be *mutated* to add ``callback=``, if this class supports branching to children.
Parameters ---------- path_1: str Child's source path path_2: str Child's destination path kwargs: dict arguments passed to child method, e.g., put_file.
Returns -------
""" return None
def no_op(self, *_, **__): pass
def __getattr__(self, item): """ If undefined methods are called on this class, nothing happens """ return self.no_op
@classmethod def as_callback(cls, maybe_callback=None): """Transform callback=... into Callback instance
For the special value of ``None``, return the global instance of ``NoOpCallback``. This is an alternative to including ``callback=DEFAULT_CALLBACK`` directly in a method signature. """ if maybe_callback is None: return DEFAULT_CALLBACK return maybe_callback
class NoOpCallback(Callback): """ This implementation of Callback does exactly nothing """
def call(self, *args, **kwargs): return None
class DotPrinterCallback(Callback): """ Simple example Callback implementation
Almost identical to Callback with a hook that prints a char; here we demonstrate how the outer layer may print "#" and the inner layer "." """
def __init__(self, chr_to_print="#", **kwargs): self.chr = chr_to_print super().__init__(**kwargs)
def branch(self, path_1, path_2, kwargs): """Mutate kwargs to add new instance with different print char""" kwargs["callback"] = DotPrinterCallback(".")
def call(self, **kwargs): """Just outputs a character""" print(self.chr, end="")
class TqdmCallback(Callback): """ A callback to display a progress bar using tqdm
Parameters ---------- tqdm_kwargs : dict, (optional) Any argument accepted by the tqdm constructor. See the `tqdm doc <https://tqdm.github.io/docs/tqdm/#__init__>`_. Will be forwarded to `tqdm_cls`. tqdm_cls: (optional) subclass of `tqdm.tqdm`. If not passed, it will default to `tqdm.tqdm`.
Examples -------- >>> import fsspec >>> from fsspec.callbacks import TqdmCallback >>> fs = fsspec.filesystem("memory") >>> path2distant_data = "/your-path" >>> fs.upload( ".", path2distant_data, recursive=True, callback=TqdmCallback(), )
You can forward args to tqdm using the ``tqdm_kwargs`` parameter.
>>> fs.upload( ".", path2distant_data, recursive=True, callback=TqdmCallback(tqdm_kwargs={"desc": "Your tqdm description"}), )
You can also customize the progress bar by passing a subclass of `tqdm`.
.. code-block:: python
class TqdmFormat(tqdm): '''Provides a `total_time` format parameter''' @property def format_dict(self): d = super().format_dict total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1) d.update(total_time=self.format_interval(total_time) + " in total") return d
>>> with TqdmCallback( tqdm_kwargs={ "desc": "desc", "bar_format": "{total_time}: {percentage:.0f}%|{bar}{r_bar}", }, tqdm_cls=TqdmFormat, ) as callback: fs.upload(".", path2distant_data, recursive=True, callback=callback) """
def __init__(self, tqdm_kwargs=None, *args, **kwargs): try: from tqdm import tqdm
except ImportError as exce: raise ImportError( "Using TqdmCallback requires tqdm to be installed" ) from exce
self._tqdm_cls = kwargs.pop("tqdm_cls", tqdm) self._tqdm_kwargs = tqdm_kwargs or {} self.tqdm = None super().__init__(*args, **kwargs)
def call(self, *args, **kwargs): if self.tqdm is None: self.tqdm = self._tqdm_cls(total=self.size, **self._tqdm_kwargs) self.tqdm.total = self.size self.tqdm.update(self.value - self.tqdm.n)
def close(self): if self.tqdm is not None: self.tqdm.close() self.tqdm = None
def __del__(self): return self.close()
DEFAULT_CALLBACK = _DEFAULT_CALLBACK = NoOpCallback()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185"""Helper functions for a standard streaming compression API"""
import sysfrom zipfile import ZipFile
import fsspec.utilsfrom fsspec.spec import AbstractBufferedFile
def noop_file(file, mode, **kwargs): return file
# TODO: files should also be available as contexts# should be functions of the form func(infile, mode=, **kwargs) -> file-likecompr = {None: noop_file}
def register_compression(name, callback, extensions, force=False): """Register an "inferable" file compression type.
Registers transparent file compression type for use with fsspec.open. Compression can be specified by name in open, or "infer"-ed for any files ending with the given extensions.
Args: name: (str) The compression type name. Eg. "gzip". callback: A callable of form (infile, mode, **kwargs) -> file-like. Accepts an input file-like object, the target mode and kwargs. Returns a wrapped file-like object. extensions: (str, Iterable[str]) A file extension, or list of file extensions for which to infer this compression scheme. Eg. "gz". force: (bool) Force re-registration of compression type or extensions.
Raises: ValueError: If name or extensions already registered, and not force.
""" if isinstance(extensions, str): extensions = [extensions]
# Validate registration if name in compr and not force: raise ValueError(f"Duplicate compression registration: {name}")
for ext in extensions: if ext in fsspec.utils.compressions and not force: raise ValueError(f"Duplicate compression file extension: {ext} ({name})")
compr[name] = callback
for ext in extensions: fsspec.utils.compressions[ext] = name
def unzip(infile, mode="rb", filename=None, **kwargs): if "r" not in mode: filename = filename or "file" z = ZipFile(infile, mode="w", **kwargs) fo = z.open(filename, mode="w") fo.close = lambda closer=fo.close: closer() or z.close() return fo z = ZipFile(infile) if filename is None: filename = z.namelist()[0] return z.open(filename, mode="r", **kwargs)
register_compression("zip", unzip, "zip")
try: from bz2 import BZ2Fileexcept ImportError: passelse: register_compression("bz2", BZ2File, "bz2")
try: # pragma: no cover from isal import igzip
def isal(infile, mode="rb", **kwargs): return igzip.IGzipFile(fileobj=infile, mode=mode, **kwargs)
register_compression("gzip", isal, "gz")except ImportError: from gzip import GzipFile
register_compression( "gzip", lambda f, **kwargs: GzipFile(fileobj=f, **kwargs), "gz" )
try: from lzma import LZMAFile
register_compression("lzma", LZMAFile, "lzma") register_compression("xz", LZMAFile, "xz")except ImportError: pass
try: import lzmaffi
register_compression("lzma", lzmaffi.LZMAFile, "lzma", force=True) register_compression("xz", lzmaffi.LZMAFile, "xz", force=True)except ImportError: pass
class SnappyFile(AbstractBufferedFile): def __init__(self, infile, mode, **kwargs): import snappy
super().__init__( fs=None, path="snappy", mode=mode.strip("b") + "b", size=999999999, **kwargs ) self.infile = infile if "r" in mode: self.codec = snappy.StreamDecompressor() else: self.codec = snappy.StreamCompressor()
def _upload_chunk(self, final=False): self.buffer.seek(0) out = self.codec.add_chunk(self.buffer.read()) self.infile.write(out) return True
def seek(self, loc, whence=0): raise NotImplementedError("SnappyFile is not seekable")
def seekable(self): return False
def _fetch_range(self, start, end): """Get the specified set of bytes from remote""" data = self.infile.read(end - start) return self.codec.decompress(data)
try: import snappy
snappy.compress(b"") # Snappy may use the .sz file extension, but this is not part of the # standard implementation. register_compression("snappy", SnappyFile, [])
except (ImportError, NameError, AttributeError): pass
try: import lz4.frame
register_compression("lz4", lz4.frame.open, "lz4")except ImportError: pass
try: if sys.version_info >= (3, 14): from compression import zstd else: from backports import zstd
register_compression("zstd", zstd.ZstdFile, ["zst", "zstd"])except ImportError: try: import zstandard as zstd
def zstandard_file(infile, mode="rb"): if "r" in mode: cctx = zstd.ZstdDecompressor() return cctx.stream_reader(infile) else: cctx = zstd.ZstdCompressor(level=10) return cctx.stream_writer(infile)
register_compression("zstd", zstandard_file, ["zst", "zstd"]) except ImportError: pass pass
def available_compressions(): """Return a list of the implemented compressions.""" return list(compr)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131from __future__ import annotations
import configparserimport jsonimport osimport warningsfrom typing import Any
conf: dict[str, dict[str, Any]] = {}default_conf_dir = os.path.join(os.path.expanduser("~"), ".config/fsspec")conf_dir = os.environ.get("FSSPEC_CONFIG_DIR", default_conf_dir)
def set_conf_env(conf_dict, envdict=os.environ): """Set config values from environment variables
Looks for variables of the form ``FSSPEC_<protocol>`` and ``FSSPEC_<protocol>_<kwarg>``. For ``FSSPEC_<protocol>`` the value is parsed as a json dictionary and used to ``update`` the config of the corresponding protocol. For ``FSSPEC_<protocol>_<kwarg>`` there is no attempt to convert the string value, but the kwarg keys will be lower-cased.
The ``FSSPEC_<protocol>_<kwarg>`` variables are applied after the ``FSSPEC_<protocol>`` ones.
Parameters ---------- conf_dict : dict(str, dict) This dict will be mutated envdict : dict-like(str, str) Source for the values - usually the real environment """ envdict = dict(envdict) kwarg_keys = [] for key in envdict: if key.startswith("FSSPEC_") and len(key) > 7 and key[7] != "_": try: value = json.loads(envdict[key]) envdict[key] = value except json.decoder.JSONDecodeError: value = envdict[key] if key.count("_") > 1: kwarg_keys.append(key) continue else: if isinstance(value, dict): _, proto = key.split("_", 1) conf_dict.setdefault(proto.lower(), {}).update(value) else: warnings.warn( f"Ignoring environment variable {key} due to not being a dict:" f" {type(value)}" ) elif key.startswith("FSSPEC"): warnings.warn( f"Ignoring environment variable {key} due to having an unexpected name" )
for key in kwarg_keys: _, proto, kwarg = key.split("_", 2) conf_dict.setdefault(proto.lower(), {})[kwarg.lower()] = envdict[key]
def set_conf_files(cdir, conf_dict): """Set config values from files
Scans for INI and JSON files in the given dictionary, and uses their contents to set the config. In case of repeated values, later values win.
In the case of INI files, all values are strings, and these will not be converted.
Parameters ---------- cdir : str Directory to search conf_dict : dict(str, dict) This dict will be mutated """ if not os.path.isdir(cdir): return allfiles = sorted(os.listdir(cdir)) for fn in allfiles: if fn.endswith(".ini"): ini = configparser.ConfigParser() ini.read(os.path.join(cdir, fn), encoding="utf-8") for key in ini: if key == "DEFAULT": continue conf_dict.setdefault(key, {}).update(dict(ini[key])) if fn.endswith(".json"): with open(os.path.join(cdir, fn), encoding="utf-8") as f: js = json.load(f) for key in js: conf_dict.setdefault(key, {}).update(dict(js[key]))
def apply_config(cls, kwargs, conf_dict=None): """Supply default values for kwargs when instantiating class
Augments the passed kwargs, by finding entries in the config dict which match the classes ``.protocol`` attribute (one or more str)
Parameters ---------- cls : file system implementation kwargs : dict conf_dict : dict of dict Typically this is the global configuration
Returns ------- dict : the modified set of kwargs """ if conf_dict is None: conf_dict = conf protos = cls.protocol if isinstance(cls.protocol, (tuple, list)) else [cls.protocol] kw = {} for proto in protos: # default kwargs from the current state of the config if proto in conf_dict: kw.update(conf_dict[proto]) # explicit kwargs always win kw.update(**kwargs) kwargs = kw return kwargs
set_conf_files(conf_dir, conf)set_conf_env(conf)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125import osimport shutilimport subprocessimport sysimport timefrom collections import dequefrom collections.abc import Generator, Sequence
import pytest
import fsspec
@pytest.fixture()def m(): """ Fixture providing a memory filesystem. """ m = fsspec.filesystem("memory") m.store.clear() m.pseudo_dirs.clear() m.pseudo_dirs.append("") try: yield m finally: m.store.clear() m.pseudo_dirs.clear() m.pseudo_dirs.append("")
class InstanceCacheInspector: """ Helper class to inspect instance caches of filesystem classes in tests. """
def clear(self) -> None: """ Clear instance caches of all currently imported filesystem classes. """ classes = deque([fsspec.spec.AbstractFileSystem]) while classes: cls = classes.popleft() cls.clear_instance_cache() classes.extend(cls.__subclasses__())
def gather_counts(self, *, omit_zero: bool = True) -> dict[str, int]: """ Gather counts of filesystem instances in the instance caches of all currently imported filesystem classes.
Parameters ---------- omit_zero: Whether to omit instance types with no cached instances. """ out: dict[str, int] = {} classes = deque([fsspec.spec.AbstractFileSystem]) while classes: cls = classes.popleft() count = len(cls._cache) # there is no public interface for the cache # note: skip intermediate AbstractFileSystem subclasses # if they proxy the protocol attribute via a property. if isinstance(cls.protocol, (Sequence, str)): key = cls.protocol if isinstance(cls.protocol, str) else cls.protocol[0] if count or not omit_zero: out[key] = count classes.extend(cls.__subclasses__()) return out
@pytest.fixture(scope="function", autouse=True)def instance_caches() -> Generator[InstanceCacheInspector, None, None]: """ Fixture to ensure empty filesystem instance caches before and after a test.
Used by default for all tests. Clears caches of all imported filesystem classes. Can be used to write test assertions about instance caches.
Usage:
def test_something(instance_caches): # Test code here fsspec.open("file://abc") fsspec.open("memory://foo/bar")
# Test assertion assert instance_caches.gather_counts() == {"file": 1, "memory": 1}
Returns ------- instance_caches: An instance cache inspector for clearing and inspecting caches. """ ic = InstanceCacheInspector()
ic.clear() try: yield ic finally: ic.clear()
@pytest.fixture(scope="function")def ftp_writable(tmpdir): """ Fixture providing a writable FTP filesystem. """ pytest.importorskip("pyftpdlib")
d = str(tmpdir) with open(os.path.join(d, "out"), "wb") as f: f.write(b"hello" * 10000) P = subprocess.Popen( [sys.executable, "-m", "pyftpdlib", "-d", d, "-u", "user", "-P", "pass", "-w"] ) try: time.sleep(1) yield "localhost", 2121, "user", "pass" finally: P.terminate() P.wait() try: shutil.rmtree(tmpdir) except Exception: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765from __future__ import annotations
import ioimport loggingimport posixpathimport refrom glob import has_magicfrom pathlib import Path
# for backwards compat, we export cache things from here toofrom fsspec.caching import ( # noqa: F401 BaseCache, BlockCache, BytesCache, MMapCache, ReadAheadCache, caches,)from fsspec.compression import comprfrom fsspec.config import conffrom fsspec.registry import available_protocols, filesystem, get_filesystem_classfrom fsspec.utils import ( _unstrip_protocol, build_name_function, infer_compression, stringify_path,)
logger = logging.getLogger("fsspec")
class OpenFile: """ File-like object to be used in a context
Can layer (buffered) text-mode and compression over any file-system, which are typically binary-only.
These instances are safe to serialize, as the low-level file object is not created until invoked using ``with``.
Parameters ---------- fs: FileSystem The file system to use for opening the file. Should be a subclass or duck-type with ``fsspec.spec.AbstractFileSystem`` path: str Location to open mode: str like 'rb', optional Mode of the opened file compression: str or None, optional Compression to apply encoding: str or None, optional The encoding to use if opened in text mode. errors: str or None, optional How to handle encoding errors if opened in text mode. newline: None or str Passed to TextIOWrapper in text mode, how to handle line endings. autoopen: bool If True, calls open() immediately. Mostly used by pickle pos: int If given and autoopen is True, seek to this location immediately """
def __init__( self, fs, path, mode="rb", compression=None, encoding=None, errors=None, newline=None, ): self.fs = fs self.path = path self.mode = mode self.compression = get_compression(path, compression) self.encoding = encoding self.errors = errors self.newline = newline self.fobjects = []
def __reduce__(self): return ( OpenFile, ( self.fs, self.path, self.mode, self.compression, self.encoding, self.errors, self.newline, ), )
def __repr__(self): return f"<OpenFile '{self.path}'>"
def __enter__(self): mode = self.mode.replace("t", "").replace("b", "") + "b"
try: f = self.fs.open(self.path, mode=mode) except FileNotFoundError as e: if has_magic(self.path): raise FileNotFoundError( f"{self.path} not found. " "The URL contains glob characters: you maybe needed\n" "to pass expand=True in fsspec.open() or the storage_options of \n" "your library. You can also set the config value 'open_expand'\n" "before import, or fsspec.core.DEFAULT_EXPAND at runtime, to True." ) from e raise
self.fobjects = [f]
if self.compression is not None: compress = compr[self.compression] f = compress(f, mode=mode[0]) self.fobjects.append(f)
if "b" not in self.mode: # assume, for example, that 'r' is equivalent to 'rt' as in builtin f = PickleableTextIOWrapper( f, encoding=self.encoding, errors=self.errors, newline=self.newline ) self.fobjects.append(f)
return self.fobjects[-1]
def __exit__(self, *args): self.close()
@property def full_name(self): return _unstrip_protocol(self.path, self.fs)
def open(self): """Materialise this as a real open file without context
The OpenFile object should be explicitly closed to avoid enclosed file instances persisting. You must, therefore, keep a reference to the OpenFile during the life of the file-like it generates. """ return self.__enter__()
def close(self): """Close all encapsulated file objects""" for f in reversed(self.fobjects): if "r" not in self.mode and not f.closed: f.flush() f.close() self.fobjects.clear()
class OpenFiles(list): """List of OpenFile instances
Can be used in a single context, which opens and closes all of the contained files. Normal list access to get the elements works as normal.
A special case is made for caching filesystems - the files will be down/uploaded together at the start or end of the context, and this may happen concurrently, if the target filesystem supports it. """
def __init__(self, *args, mode="rb", fs=None): self.mode = mode self.fs = fs self.files = [] super().__init__(*args)
def __enter__(self): if self.fs is None: raise ValueError("Context has already been used")
fs = self.fs while True: if hasattr(fs, "open_many"): # check for concurrent cache download; or set up for upload self.files = fs.open_many(self) return self.files if hasattr(fs, "fs") and fs.fs is not None: fs = fs.fs else: break return [s.__enter__() for s in self]
def __exit__(self, *args): fs = self.fs [s.__exit__(*args) for s in self] if "r" in self.mode: # open_many() returns files without populating the OpenFile objects. for f in self.files: f.close() else: while True: if hasattr(fs, "open_many"): # check for concurrent cache upload fs.commit_many(self.files) return if hasattr(fs, "fs") and fs.fs is not None: fs = fs.fs else: break
def __getitem__(self, item): out = super().__getitem__(item) if isinstance(item, slice): return OpenFiles(out, mode=self.mode, fs=self.fs) return out
def __repr__(self): return f"<List of {len(self)} OpenFile instances>"
def open_files( urlpath, mode="rb", compression=None, encoding="utf8", errors=None, name_function=None, num=1, protocol=None, newline=None, auto_mkdir=True, expand=True, **kwargs,): """Given a path or paths, return a list of ``OpenFile`` objects.
For writing, a str path must contain the "*" character, which will be filled in by increasing numbers, e.g., "part*" -> "part1", "part2" if num=2.
For either reading or writing, can instead provide explicit list of paths.
Parameters ---------- urlpath: string or list Absolute or relative filepath(s). Prefix with a protocol like ``s3://`` to read from alternative filesystems. To read from multiple files you can pass a globstring or a list of paths, with the caveat that they must all have the same protocol. mode: 'rb', 'wt', etc. compression: string or None If given, open file using compression codec. Can either be a compression name (a key in ``fsspec.compression.compr``) or "infer" to guess the compression from the filename suffix. encoding: str For text mode only errors: None or str Passed to TextIOWrapper in text mode name_function: function or None if opening a set of files for writing, those files do not yet exist, so we need to generate their names by formatting the urlpath for each sequence number num: int [1] if writing mode, number of files we expect to create (passed to name+function) protocol: str or None If given, overrides the protocol found in the URL. newline: bytes or None Used for line terminator in text mode. If None, uses system default; if blank, uses no translation. auto_mkdir: bool (True) If in write mode, this will ensure the target directory exists before writing, by calling ``fs.mkdirs(exist_ok=True)``. expand: bool **kwargs: dict Extra options that make sense to a particular storage connection, e.g. host, port, username, password, etc.
Examples -------- >>> files = open_files('2015-*-*.csv') # doctest: +SKIP >>> files = open_files( ... 's3://bucket/2015-*-*.csv.gz', compression='gzip' ... ) # doctest: +SKIP
Returns ------- An ``OpenFiles`` instance, which is a list of ``OpenFile`` objects that can be used as a single context
Notes ----- For a full list of the available protocols and the implementations that they map across to see the latest online documentation:
- For implementations built into ``fsspec`` see https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations - For implementations in separate packages see https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations """ fs, fs_token, paths = get_fs_token_paths( urlpath, mode, num=num, name_function=name_function, storage_options=kwargs, protocol=protocol, expand=expand, ) if fs.protocol == "file": fs.auto_mkdir = auto_mkdir elif "r" not in mode and auto_mkdir: parents = {fs._parent(path) for path in paths} for parent in parents: try: fs.makedirs(parent, exist_ok=True) except PermissionError: pass return OpenFiles( [ OpenFile( fs, path, mode=mode, compression=compression, encoding=encoding, errors=errors, newline=newline, ) for path in paths ], mode=mode, fs=fs, )
def _un_chain(path, kwargs): # Avoid a circular import from fsspec.implementations.chained import ChainedFileSystem
if "::" in path: x = re.compile(".*[^a-z]+.*") # test for non protocol-like single word known_protocols = set(available_protocols()) bits = []
# split on '::', then ensure each bit has a protocol for p in path.split("::"): if p in known_protocols: bits.append(p + "://") elif "://" in p or x.match(p): bits.append(p) else: bits.append(p + "://") else: bits = [path]
# [[url, protocol, kwargs], ...] out = [] previous_bit = None kwargs = kwargs.copy()
for bit in reversed(bits): protocol = kwargs.pop("protocol", None) or split_protocol(bit)[0] or "file" cls = get_filesystem_class(protocol) extra_kwargs = cls._get_kwargs_from_urls(bit) kws = kwargs.pop(protocol, {}).copy()
if bit is bits[0]: kws.update(kwargs)
kw = dict( **{k: v for k, v in extra_kwargs.items() if k not in kws or v != kws[k]}, **kws, ) bit = cls._strip_protocol(bit)
if ( "target_protocol" not in kw and issubclass(cls, ChainedFileSystem) and not bit ): # replace bit if we are chaining and no path given bit = previous_bit
out.append((bit, protocol, kw)) previous_bit = bit
out.reverse() return out
def url_to_fs(url, **kwargs): """ Turn fully-qualified and potentially chained URL into filesystem instance
Parameters ---------- url : str The fsspec-compatible URL **kwargs: dict Extra options that make sense to a particular storage connection, e.g. host, port, username, password, etc.
Returns ------- filesystem : FileSystem The new filesystem discovered from ``url`` and created with ``**kwargs``. urlpath : str The file-systems-specific URL for ``url``. """ url = stringify_path(url) # non-FS arguments that appear in fsspec.open() # inspect could keep this in sync with open()'s signature known_kwargs = { "compression", "encoding", "errors", "expand", "mode", "name_function", "newline", "num", } kwargs = {k: v for k, v in kwargs.items() if k not in known_kwargs} chain = _un_chain(url, kwargs) inkwargs = {} # Reverse iterate the chain, creating a nested target_* structure for i, ch in enumerate(reversed(chain)): urls, protocol, kw = ch if i == len(chain) - 1: inkwargs = dict(**kw, **inkwargs) continue inkwargs["target_options"] = dict(**kw, **inkwargs) inkwargs["target_protocol"] = protocol inkwargs["fo"] = urls urlpath, protocol, _ = chain[0] fs = filesystem(protocol, **inkwargs) return fs, urlpath
DEFAULT_EXPAND = conf.get("open_expand", False)
def open( urlpath, mode="rb", compression=None, encoding="utf8", errors=None, protocol=None, newline=None, expand=None, **kwargs,) -> OpenFile: """Given a path or paths, return one ``OpenFile`` object.
Parameters ---------- urlpath: string or list Absolute or relative filepath. Prefix with a protocol like ``s3://`` to read from alternative filesystems. Should not include glob character(s). mode: 'rb', 'wt', etc. compression: string or None If given, open file using compression codec. Can either be a compression name (a key in ``fsspec.compression.compr``) or "infer" to guess the compression from the filename suffix. encoding: str For text mode only errors: None or str Passed to TextIOWrapper in text mode protocol: str or None If given, overrides the protocol found in the URL. newline: bytes or None Used for line terminator in text mode. If None, uses system default; if blank, uses no translation. expand: bool or None Whether to regard file paths containing special glob characters as needing expansion (finding the first match) or absolute. Setting False allows using paths which do embed such characters. If None (default), this argument takes its value from the DEFAULT_EXPAND module variable, which takes its initial value from the "open_expand" config value at startup, which will be False if not set. **kwargs: dict Extra options that make sense to a particular storage connection, e.g. host, port, username, password, etc.
Examples -------- >>> openfile = open('2015-01-01.csv') # doctest: +SKIP >>> openfile = open( ... 's3://bucket/2015-01-01.csv.gz', compression='gzip' ... ) # doctest: +SKIP >>> with openfile as f: ... df = pd.read_csv(f) # doctest: +SKIP ...
Returns ------- ``OpenFile`` object.
Notes ----- For a full list of the available protocols and the implementations that they map across to see the latest online documentation:
- For implementations built into ``fsspec`` see https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations - For implementations in separate packages see https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations """ expand = DEFAULT_EXPAND if expand is None else expand out = open_files( urlpath=[urlpath], mode=mode, compression=compression, encoding=encoding, errors=errors, protocol=protocol, newline=newline, expand=expand, **kwargs, ) if not out: raise FileNotFoundError(urlpath) return out[0]
def open_local( url: str | list[str] | Path | list[Path], mode: str = "rb", **storage_options: dict,) -> str | list[str]: """Open file(s) which can be resolved to local
For files which either are local, or get downloaded upon open (e.g., by file caching)
Parameters ---------- url: str or list(str) mode: str Must be read mode storage_options: passed on to FS for or used by open_files (e.g., compression) """ if "r" not in mode: raise ValueError("Can only ensure local files when reading") of = open_files(url, mode=mode, **storage_options) if not getattr(of[0].fs, "local_file", False): raise ValueError( "open_local can only be used on a filesystem which" " has attribute local_file=True" ) with of as files: paths = [f.name for f in files] if (isinstance(url, str) and not has_magic(url)) or isinstance(url, Path): return paths[0] return paths
def get_compression(urlpath, compression): if compression == "infer": compression = infer_compression(urlpath) if compression is not None and compression not in compr: raise ValueError(f"Compression type {compression} not supported") return compression
def split_protocol(urlpath): """Return protocol, path pair""" urlpath = stringify_path(urlpath) if "://" in urlpath: protocol, path = urlpath.split("://", 1) if len(protocol) > 1: # excludes Windows paths return protocol, path if urlpath.startswith("data:"): return urlpath.split(":", 1) return None, urlpath
def strip_protocol(urlpath): """Return only path part of full URL, according to appropriate backend""" protocol, _ = split_protocol(urlpath) cls = get_filesystem_class(protocol) return cls._strip_protocol(urlpath)
def expand_paths_if_needed(paths, mode, num, fs, name_function): """Expand paths if they have a ``*`` in them (write mode) or any of ``*?[]`` in them (read mode).
:param paths: list of paths mode: str Mode in which to open files. num: int If opening in writing mode, number of files we expect to create. fs: filesystem object name_function: callable If opening in writing mode, this callable is used to generate path names. Names are generated for each partition by ``urlpath.replace('*', name_function(partition_index))``. :return: list of paths """ expanded_paths = [] paths = list(paths)
if "w" in mode or "x" in mode: # write mode if sum(1 for p in paths if "*" in p) > 1: raise ValueError( "When writing data, only one filename mask can be specified." ) num = max(num, len(paths))
for curr_path in paths: if "*" in curr_path: # expand using name_function expanded_paths.extend(_expand_paths(curr_path, name_function, num)) else: expanded_paths.append(curr_path) # if we generated more paths that asked for, trim the list if len(expanded_paths) > num: expanded_paths = expanded_paths[:num]
else: # read mode for curr_path in paths: if has_magic(curr_path): # expand using glob expanded_paths.extend(fs.glob(curr_path)) else: expanded_paths.append(curr_path)
return expanded_paths
def get_fs_token_paths( urlpath, mode="rb", num=1, name_function=None, storage_options=None, protocol=None, expand=True,): """Filesystem, deterministic token, and paths from a urlpath and options.
Parameters ---------- urlpath: string or iterable Absolute or relative filepath, URL (may include protocols like ``s3://``), or globstring pointing to data. mode: str, optional Mode in which to open files. num: int, optional If opening in writing mode, number of files we expect to create. name_function: callable, optional If opening in writing mode, this callable is used to generate path names. Names are generated for each partition by ``urlpath.replace('*', name_function(partition_index))``. storage_options: dict, optional Additional keywords to pass to the filesystem class. protocol: str or None To override the protocol specifier in the URL expand: bool Expand string paths for writing, assuming the path is a directory """ if isinstance(urlpath, (list, tuple, set)): if not urlpath: raise ValueError("empty urlpath sequence") urlpath0 = stringify_path(next(iter(urlpath))) else: urlpath0 = stringify_path(urlpath) storage_options = storage_options or {} if protocol: storage_options["protocol"] = protocol chain = _un_chain(urlpath0, storage_options or {}) inkwargs = {} # Reverse iterate the chain, creating a nested target_* structure for i, ch in enumerate(reversed(chain)): urls, nested_protocol, kw = ch if i == len(chain) - 1: inkwargs = dict(**kw, **inkwargs) continue inkwargs["target_options"] = dict(**kw, **inkwargs) inkwargs["target_protocol"] = nested_protocol inkwargs["fo"] = urls paths, protocol, _ = chain[0] fs = filesystem(protocol, **inkwargs) if isinstance(urlpath, (list, tuple, set)): pchains = [ _un_chain(stringify_path(u), storage_options or {})[0] for u in urlpath ] if len({pc[1] for pc in pchains}) > 1: raise ValueError(f"Protocol mismatch getting fs from {urlpath}") paths = [pc[0] for pc in pchains] else: paths = fs._strip_protocol(paths) if isinstance(paths, (list, tuple, set)): if expand: paths = expand_paths_if_needed(paths, mode, num, fs, name_function) elif not isinstance(paths, list): paths = list(paths) else: if ("w" in mode or "x" in mode) and expand: paths = _expand_paths(paths, name_function, num) elif "*" in paths: paths = [f for f in sorted(fs.glob(paths)) if not fs.isdir(f)] else: paths = [paths]
return fs, fs._fs_token, paths
def _expand_paths(path, name_function, num): if isinstance(path, str): if path.count("*") > 1: raise ValueError("Output path spec must contain exactly one '*'.") elif "*" not in path: # paths are "/"-separated on every filesystem, including local ones path = posixpath.join(path, "*.part")
if name_function is None: name_function = build_name_function(num - 1)
paths = [path.replace("*", name_function(i)) for i in range(num)] if paths != sorted(paths): logger.warning( "In order to preserve order between partitions" " paths created with ``name_function`` should " "sort to partition order" ) elif isinstance(path, (tuple, list)): assert len(path) == num paths = list(path) else: raise ValueError( "Path should be either\n" "1. A list of paths: ['foo.json', 'bar.json', ...]\n" "2. A directory: 'foo/\n" "3. A path with a '*' in it: 'foo.*.json'" ) return paths
class PickleableTextIOWrapper(io.TextIOWrapper): """TextIOWrapper cannot be pickled. This solves it.
Requires that ``buffer`` be pickleable, which all instances of AbstractBufferedFile are. """
def __init__( self, buffer, encoding=None, errors=None, newline=None, line_buffering=False, write_through=False, ): self.args = buffer, encoding, errors, newline, line_buffering, write_through super().__init__(*self.args)
def __reduce__(self): return PickleableTextIOWrapper, self.args123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125import timefrom collections import OrderedDictfrom collections.abc import MutableMapping
class DirCache(MutableMapping): """ Caching of directory listings, in a structure like::
{"path0": [ {"name": "path0/file0", "size": 123, "type": "file", ... }, {"name": "path0/file1", }, ... ], "path1": [...] }
Parameters to this class control listing expiry or indeed turn caching off. """
def __init__( self, use_listings_cache=True, listings_expiry_time=None, max_paths=None, **kwargs, ): """ Parameters ---------- use_listings_cache: bool If False, this cache never returns items, but always reports KeyError, and setting items has no effect. listings_expiry_time: int or float (optional) Time in seconds that a listing is considered valid. If None, listings do not expire. Time is measured from when the entry was set. max_paths: int (optional) The maximum number of directory listings to retain in the cache. When the cache exceeds this limit, the least recently used (set or accessed) listings are evicted. If None, 0, or negative, there is no limit. """ # max_paths is normalized to be either positive or None. self.max_paths = max_paths if max_paths and max_paths > 0 else None self._cache = OrderedDict() if self.max_paths else {} self._times = {} self.use_listings_cache = use_listings_cache self.listings_expiry_time = listings_expiry_time
def __getitem__(self, item): if not self.use_listings_cache: raise KeyError(item)
if self.listings_expiry_time is not None and item in self._cache: if time.time() - self._times.get(item, 0) > self.listings_expiry_time: del self[item] raise KeyError(item)
val = self._cache[item] if self.max_paths: self._cache.move_to_end(item) return val
def clear(self): self._cache.clear() self._times.clear()
def __len__(self): return len(self._cache)
def __contains__(self, item): if not self.use_listings_cache or item not in self._cache: return False
if self.listings_expiry_time is not None: if time.time() - self._times.get(item, 0) > self.listings_expiry_time: del self[item] return False
return True
def __setitem__(self, key, value): if not self.use_listings_cache: return
self._cache[key] = value if self.listings_expiry_time is not None: self._times[key] = time.time()
if self.max_paths: self._cache.move_to_end(key) if len(self._cache) > self.max_paths: oldest, _ = self._cache.popitem(last=False) self._times.pop(oldest, None)
def __delitem__(self, key): del self._cache[key] self._times.pop(key, None)
def __iter__(self): if not self.use_listings_cache: return
if self.listings_expiry_time is None: yield from self._cache return
now = time.time() for key in list(self._cache): if now - self._times.get(key, 0) > self.listings_expiry_time: del self[key] else: yield key
def __reduce__(self): return ( DirCache, (self.use_listings_cache, self.listings_expiry_time, self.max_paths), )123456789101112131415161718"""fsspec user-defined exception classes"""
import asyncio
class BlocksizeMismatchError(ValueError): """ Raised when a cached file is opened with a different blocksize than it was written with """
class FSTimeoutError(asyncio.TimeoutError): """ Raised when a fsspec function timed out occurs """123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324import argparseimport loggingimport osimport statimport threadingimport timefrom errno import EIO, ENOENT
from fuse import FUSE, FuseOSError, LoggingMixIn, Operations
from fsspec import __version__from fsspec.core import url_to_fs
logger = logging.getLogger("fsspec.fuse")
class FUSEr(Operations): def __init__(self, fs, path, ready_file=False): self.fs = fs self.cache = {} self.root = path.rstrip("/") + "/" self.counter = 0 logger.info("Starting FUSE at %s", path) self._ready_file = ready_file
def getattr(self, path, fh=None): logger.debug("getattr %s", path) if self._ready_file and path in ["/.fuse_ready", ".fuse_ready"]: return {"type": "file", "st_size": 5}
path = "".join([self.root, path.lstrip("/")]).rstrip("/") try: info = self.fs.info(path) except FileNotFoundError as exc: raise FuseOSError(ENOENT) from exc
data = {"st_uid": info.get("uid", 1000), "st_gid": info.get("gid", 1000)} perm = info.get("mode", 0o777)
if info["type"] != "file": data["st_mode"] = stat.S_IFDIR | perm data["st_size"] = 0 data["st_blksize"] = 0 else: data["st_mode"] = stat.S_IFREG | perm data["st_size"] = info["size"] data["st_blksize"] = 5 * 2**20 data["st_nlink"] = 1 data["st_atime"] = info["atime"] if "atime" in info else time.time() data["st_ctime"] = info["ctime"] if "ctime" in info else time.time() data["st_mtime"] = info["mtime"] if "mtime" in info else time.time() return data
def readdir(self, path, fh): logger.debug("readdir %s", path) path = "".join([self.root, path.lstrip("/")]) files = self.fs.ls(path, False) files = [os.path.basename(f.rstrip("/")) for f in files] return [".", ".."] + files
def mkdir(self, path, mode): path = "".join([self.root, path.lstrip("/")]) self.fs.mkdir(path) return 0
def rmdir(self, path): path = "".join([self.root, path.lstrip("/")]) self.fs.rmdir(path) return 0
def read(self, path, size, offset, fh): logger.debug("read %s", (path, size, offset)) if self._ready_file and path in ["/.fuse_ready", ".fuse_ready"]: # status indicator return b"ready"
f = self.cache[fh] f.seek(offset) out = f.read(size) return out
def write(self, path, data, offset, fh): logger.debug("write %s", (path, offset)) f = self.cache[fh] f.seek(offset) f.write(data) return len(data)
def create(self, path, flags, fi=None): logger.debug("create %s", (path, flags)) fn = "".join([self.root, path.lstrip("/")]) self.fs.touch(fn) # OS will want to get attributes immediately f = self.fs.open(fn, "wb") self.cache[self.counter] = f self.counter += 1 return self.counter - 1
def open(self, path, flags): logger.debug("open %s", (path, flags)) fn = "".join([self.root, path.lstrip("/")]) if flags % 2 == 0: # read mode = "rb" else: # write/create mode = "wb" self.cache[self.counter] = self.fs.open(fn, mode) self.counter += 1 return self.counter - 1
def truncate(self, path, length, fh=None): fn = "".join([self.root, path.lstrip("/")]) if length != 0: raise NotImplementedError # maybe should be no-op since open with write sets size to zero anyway self.fs.touch(fn)
def unlink(self, path): fn = "".join([self.root, path.lstrip("/")]) try: self.fs.rm(fn, False) except (OSError, FileNotFoundError) as exc: raise FuseOSError(EIO) from exc
def release(self, path, fh): try: if fh in self.cache: f = self.cache[fh] f.close() self.cache.pop(fh) except Exception as e: print(e) return 0
def chmod(self, path, mode): if hasattr(self.fs, "chmod"): path = "".join([self.root, path.lstrip("/")]) return self.fs.chmod(path, mode) raise NotImplementedError
def run( fs, path, mount_point, foreground=True, threads=False, ready_file=False, ops_class=FUSEr,): """Mount stuff in a local directory
This uses fusepy to make it appear as if a given path on an fsspec instance is in fact resident within the local file-system.
This requires that fusepy by installed, and that FUSE be available on the system (typically requiring a package to be installed with apt, yum, brew, etc.).
Parameters ---------- fs: file-system instance From one of the compatible implementations path: str Location on that file-system to regard as the root directory to mount. Note that you typically should include the terminating "/" character. mount_point: str An empty directory on the local file-system where the contents of the remote path will appear. foreground: bool Whether or not calling this function will block. Operation will typically be more stable if True. threads: bool Whether or not to create threads when responding to file operations within the mounter directory. Operation will typically be more stable if False. ready_file: bool Whether the FUSE process is ready. The ``.fuse_ready`` file will exist in the ``mount_point`` directory if True. Debugging purpose. ops_class: FUSEr or Subclass of FUSEr To override the default behavior of FUSEr. For Example, logging to file.
""" func = lambda: FUSE( ops_class(fs, path, ready_file=ready_file), mount_point, nothreads=not threads, foreground=foreground, ) if not foreground: th = threading.Thread(target=func) th.daemon = True th.start() return th else: # pragma: no cover try: func() except KeyboardInterrupt: pass
def main(args): """Mount filesystem from chained URL to MOUNT_POINT.
Examples:
python3 -m fsspec.fuse memory /usr/share /tmp/mem
python3 -m fsspec.fuse local /tmp/source /tmp/local \\ -l /tmp/fsspecfuse.log
You can also mount chained-URLs and use special settings:
python3 -m fsspec.fuse 'filecache::zip::file://data.zip' \\ / /tmp/zip \\ -o 'filecache-cache_storage=/tmp/simplecache'
You can specify the type of the setting by using `[int]` or `[bool]`, (`true`, `yes`, `1` represents the Boolean value `True`):
python3 -m fsspec.fuse 'simplecache::ftp://ftp1.at.proftpd.org' \\ /historic/packages/RPMS /tmp/ftp \\ -o 'simplecache-cache_storage=/tmp/simplecache' \\ -o 'simplecache-check_files=false[bool]' \\ -o 'ftp-listings_expiry_time=60[int]' \\ -o 'ftp-username=anonymous' \\ -o 'ftp-password=xieyanbo' """
class RawDescriptionArgumentParser(argparse.ArgumentParser): def format_help(self): usage = super().format_help() parts = usage.split("\n\n") parts[1] = self.description.rstrip() return "\n\n".join(parts)
parser = RawDescriptionArgumentParser(prog="fsspec.fuse", description=main.__doc__) parser.add_argument("--version", action="version", version=__version__) parser.add_argument("url", type=str, help="fs url") parser.add_argument("source_path", type=str, help="source directory in fs") parser.add_argument("mount_point", type=str, help="local directory") parser.add_argument( "-o", "--option", action="append", help="Any options of protocol included in the chained URL", ) parser.add_argument( "-l", "--log-file", type=str, help="Logging FUSE debug info (Default: '')" ) parser.add_argument( "-f", "--foreground", action="store_true", help="Running in foreground or not (Default: False)", ) parser.add_argument( "-t", "--threads", action="store_false", help="Running with threads support (Default: False)", ) parser.add_argument( "-r", "--ready-file", action="store_false", help="The `.fuse_ready` file will exist after FUSE is ready. " "(Debugging purpose, Default: False)", ) args = parser.parse_args(args)
kwargs = {} for item in args.option or []: key, sep, value = item.partition("=") if not sep: parser.error(message=f"Wrong option: {item!r}") val = value.lower() if val.endswith("[int]"): value = int(value[: -len("[int]")]) elif val.endswith("[bool]"): value = val[: -len("[bool]")] in ["1", "yes", "true"]
if "-" in key: fs_name, setting_name = key.split("-", 1) if fs_name in kwargs: kwargs[fs_name][setting_name] = value else: kwargs[fs_name] = {setting_name: value} else: kwargs[key] = value
if args.log_file: logging.basicConfig( level=logging.DEBUG, filename=args.log_file, format="%(asctime)s %(message)s", )
class LoggingFUSEr(FUSEr, LoggingMixIn): pass
fuser = LoggingFUSEr else: fuser = FUSEr
fs, url_path = url_to_fs(args.url, **kwargs) logger.debug("Mounting %s to %s", url_path, str(args.mount_point)) run( fs, args.source_path, args.mount_point, foreground=args.foreground, threads=args.threads, ready_file=args.ready_file, ops_class=fuser, )
if __name__ == "__main__": import sys
main(sys.argv[1:])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409from __future__ import annotations
import inspectimport loggingimport osimport uuid
from .asyn import AsyncFileSystem, _run_coros_in_chunks, sync_wrapperfrom .callbacks import DEFAULT_CALLBACKfrom .core import filesystem, get_filesystem_class, split_protocol, url_to_fsfrom .utils import check_contained
_generic_fs = {}logger = logging.getLogger("fsspec.generic")
def set_generic_fs(protocol, **storage_options): """Populate the dict used for method=="generic" lookups""" _generic_fs[protocol] = filesystem(protocol, **storage_options)
def _resolve_fs(url, method, protocol=None, storage_options=None): """Pick instance of backend FS""" url = url[0] if isinstance(url, (list, tuple)) else url protocol = protocol or split_protocol(url)[0] storage_options = storage_options or {} if method == "default": return filesystem(protocol) if method == "generic": return _generic_fs[protocol] if method == "current": cls = get_filesystem_class(protocol) return cls.current() if method == "options": fs, _ = url_to_fs(url, **storage_options.get(protocol, {})) return fs raise ValueError(f"Unknown FS resolution method: {method}")
def rsync( source, destination, delete_missing=False, source_field="size", dest_field="size", update_cond="different", inst_kwargs=None, fs=None, **kwargs,): """Sync files between two directory trees
(experimental)
Parameters ---------- source: str Root of the directory tree to take files from. This must be a directory, but do not include any terminating "/" character destination: str Root path to copy into. The contents of this location should be identical to the contents of ``source`` when done. This will be made a directory, and the terminal "/" should not be included. delete_missing: bool If there are paths in the destination that don't exist in the source and this is True, delete them. Otherwise, leave them alone. source_field: str | callable If ``update_field`` is "different", this is the key in the info of source files to consider for difference. Maybe a function of the info dict. dest_field: str | callable If ``update_field`` is "different", this is the key in the info of destination files to consider for difference. May be a function of the info dict. update_cond: "different"|"always"|"never" If "always", every file is copied, regardless of whether it exists in the destination. If "never", files that exist in the destination are not copied again. If "different" (default), only copy if the info fields given by ``source_field`` and ``dest_field`` (usually "size") are different. Other comparisons may be added in the future. inst_kwargs: dict|None If ``fs`` is None, use this set of keyword arguments to make a GenericFileSystem instance fs: GenericFileSystem|None Instance to use if explicitly given. The instance defines how to to make downstream file system instances from paths.
Returns ------- dict of the copy operations that were performed, {source: destination} """ fs = fs or GenericFileSystem(**(inst_kwargs or {})) source = fs._strip_protocol(source) destination = fs._strip_protocol(destination) allfiles = fs.find(source, withdirs=True, detail=True) if not fs.isdir(source): raise ValueError("Can only rsync on a directory") # The names came from the source listing; ".." in one of them would # otherwise place the copy above the destination. check_contained(destination, [a.replace(source, destination, 1) for a in allfiles]) otherfiles = fs.find(destination, withdirs=True, detail=True) dirs = [ a for a, v in allfiles.items() if v["type"] == "directory" and a.replace(source, destination, 1) not in otherfiles ] logger.debug(f"{len(dirs)} directories to create") if dirs: fs.make_many_dirs( [dirn.replace(source, destination, 1) for dirn in dirs], exist_ok=True ) allfiles = {a: v for a, v in allfiles.items() if v["type"] == "file"} logger.debug(f"{len(allfiles)} files to consider for copy") to_delete = [ o for o, v in otherfiles.items() if o.replace(destination, source, 1) not in allfiles and v["type"] == "file" ] for k, v in allfiles.copy().items(): otherfile = k.replace(source, destination, 1) if otherfile in otherfiles: if update_cond == "always": allfiles[k] = otherfile elif update_cond == "never": allfiles.pop(k) elif update_cond == "different": inf1 = source_field(v) if callable(source_field) else v[source_field] v2 = otherfiles[otherfile] inf2 = dest_field(v2) if callable(dest_field) else v2[dest_field] if inf1 != inf2: # details mismatch, make copy allfiles[k] = otherfile else: # details match, don't copy allfiles.pop(k) else: # file not in target yet allfiles[k] = otherfile logger.debug(f"{len(allfiles)} files to copy") if allfiles: source_files, target_files = zip(*allfiles.items()) fs.cp(source_files, target_files, **kwargs) logger.debug(f"{len(to_delete)} files to delete") if delete_missing and to_delete: fs.rm(to_delete) return allfiles
class GenericFileSystem(AsyncFileSystem): """Wrapper over all other FS types
<experimental!>
This implementation is a single unified interface to be able to run FS operations over generic URLs, and dispatch to the specific implementations using the URL protocol prefix.
Note: instances of this FS are always async, even if you never use it with any async backend. """
protocol = "generic" # there is no real reason to ever use a protocol with this FS
def __init__(self, default_method="default", storage_options=None, **kwargs): """
Parameters ---------- default_method: str (optional) Defines how to configure backend FS instances. Options are: - "default": instantiate like FSClass(), with no extra arguments; this is the default instance of that FS, and can be configured via the config system - "generic": takes instances from the `_generic_fs` dict in this module, which you must populate before use. Keys are by protocol - "options": expects storage_options, a dict mapping protocol to kwargs to use when constructing the filesystem - "current": takes the most recently instantiated version of each FS """ self.method = default_method self.st_opts = storage_options super().__init__(**kwargs)
def _parent(self, path): fs = _resolve_fs(path, self.method, storage_options=self.st_opts) return fs.unstrip_protocol(fs._parent(path))
def _strip_protocol(self, path): # normalization only fs = _resolve_fs(path, self.method, storage_options=self.st_opts) return fs.unstrip_protocol(fs._strip_protocol(path))
async def _find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): fs = _resolve_fs(path, self.method, storage_options=self.st_opts) if fs.async_impl: out = await fs._find( path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs ) else: out = fs.find( path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs ) result = {} for k, v in out.items(): v = v.copy() # don't corrupt target FS dircache name = fs.unstrip_protocol(k) v["name"] = name result[name] = v if detail: return result return list(result)
async def _info(self, url, **kwargs): fs = _resolve_fs(url, self.method, storage_options=self.st_opts) if fs.async_impl: out = await fs._info(url, **kwargs) else: out = fs.info(url, **kwargs) out = out.copy() # don't edit originals out["name"] = fs.unstrip_protocol(out["name"]) return out
async def _ls( self, url, detail=True, **kwargs, ): fs = _resolve_fs(url, self.method, storage_options=self.st_opts) if fs.async_impl: out = await fs._ls(url, detail=True, **kwargs) else: out = fs.ls(url, detail=True, **kwargs) out = [o.copy() for o in out] # don't edit originals for o in out: o["name"] = fs.unstrip_protocol(o["name"]) if detail: return out else: return [o["name"] for o in out]
async def _cat_file( self, url, **kwargs, ): fs = _resolve_fs(url, self.method, storage_options=self.st_opts) if fs.async_impl: return await fs._cat_file(url, **kwargs) else: return fs.cat_file(url, **kwargs)
async def _pipe_file( self, path, value, **kwargs, ): fs = _resolve_fs(path, self.method, storage_options=self.st_opts) if fs.async_impl: return await fs._pipe_file(path, value, **kwargs) else: return fs.pipe_file(path, value, **kwargs)
async def _rm(self, url, **kwargs): urls = url if isinstance(urls, str): urls = [urls] fs = _resolve_fs(urls[0], self.method, storage_options=self.st_opts) if fs.async_impl: await fs._rm(urls, **kwargs) else: fs.rm(url, **kwargs)
async def _makedirs(self, path, exist_ok=False): logger.debug("Make dir %s", path) fs = _resolve_fs(path, self.method, storage_options=self.st_opts) if fs.async_impl: await fs._makedirs(path, exist_ok=exist_ok) else: fs.makedirs(path, exist_ok=exist_ok)
def rsync(self, source, destination, **kwargs): """Sync files between two directory trees
See `func:rsync` for more details. """ rsync(source, destination, fs=self, **kwargs)
async def _cp_file( self, url, url2, blocksize=2**20, callback=DEFAULT_CALLBACK, tempdir: str | None = None, **kwargs, ): fs = _resolve_fs(url, self.method, storage_options=self.st_opts) fs2 = _resolve_fs(url2, self.method, storage_options=self.st_opts) if fs is fs2: # pure remote if fs.async_impl: return await fs._copy(url, url2, **kwargs) else: return fs.copy(url, url2, **kwargs) await copy_file_op(fs, [url], fs2, [url2], tempdir, 1, on_error="raise")
async def _make_many_dirs(self, urls, exist_ok=True): fs = _resolve_fs(urls[0], self.method, storage_options=self.st_opts) if fs.async_impl: coros = [fs._makedirs(u, exist_ok=exist_ok) for u in urls] await _run_coros_in_chunks(coros) else: for u in urls: fs.makedirs(u, exist_ok=exist_ok)
make_many_dirs = sync_wrapper(_make_many_dirs)
async def _copy( self, path1: list[str], path2: list[str], recursive: bool = False, on_error: str = "ignore", maxdepth: int | None = None, batch_size: int | None = None, tempdir: str | None = None, **kwargs, ): # TODO: special case for one FS being local, which can use get/put # TODO: special case for one being memFS, which can use cat/pipe if recursive: raise NotImplementedError("Please use fsspec.generic.rsync") path1 = [path1] if isinstance(path1, str) else path1 path2 = [path2] if isinstance(path2, str) else path2
fs = _resolve_fs(path1, self.method, storage_options=self.st_opts) fs2 = _resolve_fs(path2, self.method, storage_options=self.st_opts)
# Validate both entire batches before copying any files. for paths, backend, side in ( (path1, fs, "source"), (path2, fs2, "destination"), ): if any( _resolve_fs(path, self.method, storage_options=self.st_opts) is not backend for path in paths ): raise ValueError(f"Multiple {side} backends are not supported")
if fs is fs2: if fs.async_impl: return await fs._copy(path1, path2, **kwargs) else: return fs.copy(path1, path2, **kwargs)
await copy_file_op( fs, path1, fs2, path2, tempdir, batch_size, on_error=on_error )
async def copy_file_op( fs1, url1, fs2, url2, tempdir=None, batch_size=20, on_error="ignore"): import tempfile
with tempfile.TemporaryDirectory(dir=tempdir) as tempdir: coros = [ _copy_file_op( fs1, u1, fs2, u2, os.path.join(tempdir, uuid.uuid4().hex), ) for u1, u2 in zip(url1, url2) ] out = await _run_coros_in_chunks( coros, batch_size=batch_size, return_exceptions=True ) if on_error == "return": return out elif on_error == "raise": for o in out: if isinstance(o, Exception): raise o
async def _copy_file_op(fs1, url1, fs2, url2, local, on_error="ignore"): if fs1.async_impl: await fs1._get_file(url1, local) else: fs1.get_file(url1, local) if fs2.async_impl: await fs2._put_file(local, url2) else: fs2.put_file(local, url2) os.unlink(local) logger.debug("Copy %s -> %s; done", url1, url2)
async def maybe_await(cor): if inspect.iscoroutine(cor): return await cor else: return cor123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417import astimport contextlibimport loggingimport osimport refrom collections.abc import Sequencefrom typing import ClassVar
import panel as pn
from .core import OpenFile, get_filesystem_class, split_protocolfrom .registry import known_implementations
pn.extension()logger = logging.getLogger("fsspec.gui")
class SigSlot: """Signal-slot mixin, for Panel event passing
Include this class in a widget manager's superclasses to be able to register events and callbacks on Panel widgets managed by that class.
The method ``_register`` should be called as widgets are added, and external code should call ``connect`` to associate callbacks.
By default, all signals emit a DEBUG logging statement. """
# names of signals that this class may emit each of which must be # set by _register for any new instance signals: ClassVar[Sequence[str]] = [] # names of actions that this class may respond to slots: ClassVar[Sequence[str]] = []
# each of which must be a method name
def __init__(self): self._ignoring_events = False self._sigs = {} self._map = {} self._setup()
def _setup(self): """Create GUI elements and register signals""" self.panel = pn.pane.PaneBase() # no signals to set up in the base class
def _register( self, widget, name, thing="value", log_level=logging.DEBUG, auto=False ): """Watch the given attribute of a widget and assign it a named event
This is normally called at the time a widget is instantiated, in the class which owns it.
Parameters ---------- widget : pn.layout.Panel or None Widget to watch. If None, an anonymous signal not associated with any widget. name : str Name of this event thing : str Attribute of the given widget to watch log_level : int When the signal is triggered, a logging event of the given level will be fired in the dfviz logger. auto : bool If True, automatically connects with a method in this class of the same name. """ if name not in self.signals: raise ValueError(f"Attempt to assign an undeclared signal: {name}") self._sigs[name] = { "widget": widget, "callbacks": [], "thing": thing, "log": log_level, } wn = "-".join( [ getattr(widget, "name", str(widget)) if widget is not None else "none", thing, ] ) self._map[wn] = name if widget is not None: widget.param.watch(self._signal, thing, onlychanged=True) if auto and hasattr(self, name): self.connect(name, getattr(self, name))
def _repr_mimebundle_(self, *args, **kwargs): """Display in a notebook or a server""" try: return self.panel._repr_mimebundle_(*args, **kwargs) except (ValueError, AttributeError) as exc: raise NotImplementedError( "Panel does not seem to be set up properly" ) from exc
def connect(self, signal, slot): """Associate call back with given event
The callback must be a function which takes the "new" value of the watched attribute as the only parameter. If the callback return False, this cancels any further processing of the given event.
Alternatively, the callback can be a string, in which case it means emitting the correspondingly-named event (i.e., connect to self) """ self._sigs[signal]["callbacks"].append(slot)
def _signal(self, event): """This is called by a an action on a widget
Within an self.ignore_events context, nothing happens.
Tests can execute this method by directly changing the values of widget components. """ if not self._ignoring_events: wn = "-".join([event.obj.name, event.name]) if wn in self._map and self._map[wn] in self._sigs: self._emit(self._map[wn], event.new)
@contextlib.contextmanager def ignore_events(self): """Temporarily turn off events processing in this instance
(does not propagate to children) """ self._ignoring_events = True try: yield finally: self._ignoring_events = False
def _emit(self, sig, value=None): """An event happened, call its callbacks
This method can be used in tests to simulate message passing without directly changing visual elements.
Calling of callbacks will halt whenever one returns False. """ logger.log(self._sigs[sig]["log"], f"{sig}: {value}") for callback in self._sigs[sig]["callbacks"]: if isinstance(callback, str): self._emit(callback) else: try: # running callbacks should not break the interface ret = callback(value) if ret is False: break except Exception as e: logger.exception( "Exception (%s) while executing callback for signal: %s", e, sig, )
def show(self, threads=False): """Open a new browser tab and display this instance's interface""" self.panel.show(threads=threads, verbose=False) return self
class SingleSelect(SigSlot): """A multiselect which only allows you to select one item for an event"""
signals = ["_selected", "selected"] # the first is internal slots = ["set_options", "set_selection", "add", "clear", "select"]
def __init__(self, **kwargs): self.kwargs = kwargs super().__init__()
def _setup(self): self.panel = pn.widgets.MultiSelect(**self.kwargs) self._register(self.panel, "_selected", "value") self._register(None, "selected") self.connect("_selected", self.select_one)
def _signal(self, *args, **kwargs): super()._signal(*args, **kwargs)
def select_one(self, *_): with self.ignore_events(): val = [self.panel.value[-1]] if self.panel.value else [] self.panel.value = val self._emit("selected", self.panel.value)
def set_options(self, options): self.panel.options = options
def clear(self): self.panel.options = []
@property def value(self): return self.panel.value
def set_selection(self, selection): self.panel.value = [selection]
class FileSelector(SigSlot): """Panel-based graphical file selector widget
Instances of this widget are interactive and can be displayed in jupyter by having them as the output of a cell, or in a separate browser tab using ``.show()``. """
signals = [ "protocol_changed", "selection_changed", "directory_entered", "home_clicked", "up_clicked", "go_clicked", "filters_changed", ] slots = ["set_filters", "go_home"]
def __init__(self, url=None, filters=None, ignore=None, kwargs=None): """
Parameters ---------- url : str (optional) Initial value of the URL to populate the dialog; should include protocol filters : list(str) (optional) File endings to include in the listings. If not included, all files are allowed. Does not affect directories. If given, the endings will appear as checkboxes in the interface ignore : list(str) (optional) Regex(s) of file basename patterns to ignore, e.g., "\\." for typical hidden files on posix kwargs : dict (optional) To pass to file system instance """ if url: self.init_protocol, url = split_protocol(url) else: self.init_protocol, url = "file", os.getcwd() self.init_url = url self.init_kwargs = (kwargs if isinstance(kwargs, str) else str(kwargs)) or "{}" self.filters = filters self.ignore = [re.compile(i) for i in ignore or []] self._fs = None super().__init__()
def _setup(self): self.url = pn.widgets.TextInput( name="url", value=self.init_url, align="end", sizing_mode="stretch_width", width_policy="max", ) self.protocol = pn.widgets.Select( options=sorted(known_implementations), value=self.init_protocol, name="protocol", align="center", ) self.kwargs = pn.widgets.TextInput( name="kwargs", value=self.init_kwargs, align="center" ) self.go = pn.widgets.Button(name="⇨", align="end", width=45) self.main = SingleSelect(size=10) self.home = pn.widgets.Button(name="🏠", width=40, height=30, align="end") self.up = pn.widgets.Button(name="‹", width=30, height=30, align="end")
self._register(self.protocol, "protocol_changed", auto=True) self._register(self.go, "go_clicked", "clicks", auto=True) self._register(self.up, "up_clicked", "clicks", auto=True) self._register(self.home, "home_clicked", "clicks", auto=True) self._register(None, "selection_changed") self.main.connect("selected", self.selection_changed) self._register(None, "directory_entered") self.prev_protocol = self.protocol.value self.prev_kwargs = self.storage_options
self.filter_sel = pn.widgets.CheckBoxGroup( value=[], options=[], inline=False, align="end", width_policy="min" ) self._register(self.filter_sel, "filters_changed", auto=True)
self.panel = pn.Column( pn.Row(self.protocol, self.kwargs), pn.Row(self.home, self.up, self.url, self.go, self.filter_sel), self.main.panel, ) self.set_filters(self.filters) self.go_clicked()
def set_filters(self, filters=None): self.filters = filters if filters: self.filter_sel.options = filters self.filter_sel.value = filters else: self.filter_sel.options = [] self.filter_sel.value = []
@property def storage_options(self): """Value of the kwargs box as a dictionary""" return ast.literal_eval(self.kwargs.value) or {}
@property def fs(self): """Current filesystem instance""" if self._fs is None: cls = get_filesystem_class(self.protocol.value) self._fs = cls(**self.storage_options) return self._fs
@property def urlpath(self): """URL of currently selected item""" return ( (f"{self.protocol.value}://{self.main.value[0]}") if self.main.value else None )
def open_file(self, mode="rb", compression=None, encoding=None): """Create OpenFile instance for the currently selected item
For example, in a notebook you might do something like
.. code-block::
[ ]: sel = FileSelector(); sel
# user selects their file
[ ]: with sel.open_file('rb') as f: ... out = f.read()
Parameters ---------- mode: str (optional) Open mode for the file. compression: str (optional) The interact with the file as compressed. Set to 'infer' to guess compression from the file ending encoding: str (optional) If using text mode, use this encoding; defaults to UTF8. """ if self.urlpath is None: raise ValueError("No file selected") return OpenFile(self.fs, self.urlpath, mode, compression, encoding)
def filters_changed(self, values): self.filters = values self.go_clicked()
def selection_changed(self, *_): if self.urlpath is None: return if self.fs.isdir(self.urlpath): self.url.value = self.fs._strip_protocol(self.urlpath) self.go_clicked()
def go_clicked(self, *_): if ( self.prev_protocol != self.protocol.value or self.prev_kwargs != self.storage_options ): self._fs = None # causes fs to be recreated self.prev_protocol = self.protocol.value self.prev_kwargs = self.storage_options listing = sorted( self.fs.ls(self.url.value, detail=True), key=lambda x: x["name"] ) listing = [ l for l in listing if not any(i.match(l["name"].rsplit("/", 1)[-1]) for i in self.ignore) ] folders = { "📁 " + o["name"].rsplit("/", 1)[-1]: o["name"] for o in listing if o["type"] == "directory" } files = { "📄 " + o["name"].rsplit("/", 1)[-1]: o["name"] for o in listing if o["type"] == "file" } if self.filters: files = { k: v for k, v in files.items() if any(v.endswith(ext) for ext in self.filters) } self.main.set_options(dict(**folders, **files))
def protocol_changed(self, *_): self._fs = None self.main.options = [] self.url.value = ""
def home_clicked(self, *_): self.protocol.value = self.init_protocol self.kwargs.value = self.init_kwargs self.url.value = self.init_url self.go_clicked()
def up_clicked(self, *_): self.url.value = self.fs._parent(self.url.value) self.go_clicked()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333import errnoimport ioimport osimport secretsimport shutilfrom contextlib import suppressfrom functools import cached_property, wrapsfrom urllib.parse import parse_qs
from fsspec.spec import AbstractFileSystemfrom fsspec.utils import ( get_package_version_without_import, infer_storage_options, mirror_from, tokenize,)
def wrap_exceptions(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except OSError as exception: if not exception.args: raise
message, *args = exception.args if isinstance(message, str) and "does not exist" in message: raise FileNotFoundError(errno.ENOENT, message) from exception else: raise
return wrapper
PYARROW_VERSION = None_EMPTY_ROOT_MARKER_FILESYSTEMS = {"gcs", "s3"}
class ArrowFSWrapper(AbstractFileSystem): """FSSpec-compatible wrapper of pyarrow.fs.FileSystem.
Parameters ---------- fs : pyarrow.fs.FileSystem
"""
root_marker = "/"
def __init__(self, fs, **kwargs): global PYARROW_VERSION PYARROW_VERSION = get_package_version_without_import("pyarrow") self.fs = fs if fs.type_name in _EMPTY_ROOT_MARKER_FILESYSTEMS: self.root_marker = "" super().__init__(**kwargs)
@property def protocol(self): return self.fs.type_name
@cached_property def fsid(self): return "hdfs_" + tokenize(self.fs.host, self.fs.port)
def _parent(self, path): if self.root_marker: return super()._parent(path)
path = self._strip_protocol(path).lstrip("/") return path.rsplit("/", 1)[0] if "/" in path else ""
@classmethod def _strip_protocol(cls, path): ops = infer_storage_options(path) path = ops["path"] if path.startswith("//"): # special case for "hdfs://path" (without the triple slash) path = path[1:] return path
def ls(self, path, detail=False, **kwargs): path = self._strip_protocol(path) from pyarrow.fs import FileSelector
try: entries = [ self._make_entry(entry) for entry in self.fs.get_file_info(FileSelector(path)) ] except (FileNotFoundError, NotADirectoryError): entries = [self.info(path, **kwargs)] if detail: return entries else: return [entry["name"] for entry in entries]
def info(self, path, **kwargs): path = self._strip_protocol(path) [info] = self.fs.get_file_info([path]) return self._make_entry(info)
def exists(self, path): path = self._strip_protocol(path) try: self.info(path) except FileNotFoundError: return False else: return True
def _make_entry(self, info): from pyarrow.fs import FileType
if info.type is FileType.Directory: kind = "directory" elif info.type is FileType.File: kind = "file" elif info.type is FileType.NotFound: raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), info.path) else: kind = "other"
return { "name": info.path, "size": info.size, "type": kind, "mtime": info.mtime, }
@wrap_exceptions def cp_file(self, path1, path2, **kwargs): path1 = self._strip_protocol(path1).rstrip("/") path2 = self._strip_protocol(path2).rstrip("/")
with self._open(path1, "rb") as lstream: tmp_fname = f"{path2}.tmp.{secrets.token_hex(6)}" try: with self.open(tmp_fname, "wb") as rstream: shutil.copyfileobj(lstream, rstream) self.fs.move(tmp_fname, path2) except BaseException: with suppress(FileNotFoundError): self.fs.delete_file(tmp_fname) raise
@wrap_exceptions def mv(self, path1, path2, **kwargs): path1 = self._strip_protocol(path1).rstrip("/") path2 = self._strip_protocol(path2).rstrip("/") self.fs.move(path1, path2)
@wrap_exceptions def rm_file(self, path): path = self._strip_protocol(path) self.fs.delete_file(path)
@wrap_exceptions def rm(self, path, recursive=False, maxdepth=None): path = self._strip_protocol(path).rstrip("/") if self.isdir(path): if recursive: self.fs.delete_dir(path) else: raise ValueError("Can't delete directories without recursive=False") else: self.fs.delete_file(path)
@wrap_exceptions def _open(self, path, mode="rb", block_size=None, seekable=True, **kwargs): if mode == "rb": if seekable: method = self.fs.open_input_file else: method = self.fs.open_input_stream elif mode == "wb": method = self.fs.open_output_stream elif mode == "ab": method = self.fs.open_append_stream else: raise ValueError(f"unsupported mode for Arrow filesystem: {mode!r}")
_kwargs = {} if mode != "rb" or not seekable: if int(PYARROW_VERSION.split(".")[0]) >= 4: # disable compression auto-detection _kwargs["compression"] = None stream = method(path, **_kwargs)
return ArrowFile(self, stream, path, mode, block_size, **kwargs)
@wrap_exceptions def mkdir(self, path, create_parents=True, **kwargs): path = self._strip_protocol(path) if create_parents: self.makedirs(path, exist_ok=True) else: self.fs.create_dir(path, recursive=False)
@wrap_exceptions def makedirs(self, path, exist_ok=False): path = self._strip_protocol(path) self.fs.create_dir(path, recursive=True)
@wrap_exceptions def rmdir(self, path): path = self._strip_protocol(path) self.fs.delete_dir(path)
@wrap_exceptions def modified(self, path): path = self._strip_protocol(path) return self.fs.get_file_info(path).mtime
def cat_file(self, path, start=None, end=None, **kwargs): kwargs.setdefault("seekable", start not in [None, 0]) return super().cat_file(path, start, end, **kwargs)
def get_file(self, rpath, lpath, **kwargs): kwargs.setdefault("seekable", False) super().get_file(rpath, lpath, **kwargs)
@mirror_from( "stream", [ "read", "readinto", "seek", "tell", "write", "flush", "readable", "writable", "close", "seekable", ],)class ArrowFile(io.IOBase): def __init__(self, fs, stream, path, mode, block_size=None, **kwargs): self.path = path self.mode = mode
self.fs = fs self.stream = stream
self.blocksize = self.block_size = block_size self.kwargs = kwargs
def __enter__(self): return self
@property def closed(self): return self.stream.closed
@property def size(self): if self.stream.seekable(): return self.stream.size() return None
def __exit__(self, *args): return self.close()
class HadoopFileSystem(ArrowFSWrapper): """A wrapper on top of the pyarrow.fs.HadoopFileSystem to connect it's interface with fsspec"""
protocol = "hdfs"
def __init__( self, host="default", port=0, user=None, kerb_ticket=None, replication=3, extra_conf=None, **kwargs, ): """
Parameters ---------- host: str Hostname, IP or "default" to try to read from Hadoop config port: int Port to connect on, or default from Hadoop config if 0 user: str or None If given, connect as this username kerb_ticket: str or None If given, use this ticket for authentication replication: int set replication factor of file for write operations. default value is 3. extra_conf: None or dict Passed on to HadoopFileSystem """ from pyarrow.fs import HadoopFileSystem
fs = HadoopFileSystem( host=host, port=port, user=user, kerb_ticket=kerb_ticket, replication=replication, extra_conf=extra_conf, ) super().__init__(fs=fs, **kwargs) self._fsid = "hdfs_" + tokenize(host, port)
@property def fsid(self): return self._fsid
@staticmethod def _get_kwargs_from_urls(path): ops = infer_storage_options(path) out = {} if ops.get("host", None): out["host"] = ops["host"] if ops.get("username", None): out["user"] = ops["username"] if ops.get("port", None): out["port"] = ops["port"] if ops.get("url_query", None): queries = parse_qs(ops["url_query"]) if queries.get("replication", None): out["replication"] = int(queries["replication"][0]) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135import asyncioimport functoolsimport inspect
import fsspecfrom fsspec.asyn import AsyncFileSystem, running_async
from .chained import ChainedFileSystem
def async_wrapper(func, obj=None, semaphore=None): """ Wraps a synchronous function to make it awaitable.
Parameters ---------- func : callable The synchronous function to wrap. obj : object, optional The instance to bind the function to, if applicable. semaphore : asyncio.Semaphore, optional A semaphore to limit concurrent calls.
Returns ------- coroutine An awaitable version of the function. """
@functools.wraps(func) async def wrapper(*args, **kwargs): if semaphore: async with semaphore: return await asyncio.to_thread(func, *args, **kwargs) return await asyncio.to_thread(func, *args, **kwargs)
return wrapper
class AsyncFileSystemWrapper(AsyncFileSystem, ChainedFileSystem): """ A wrapper class to convert a synchronous filesystem into an asynchronous one.
This class takes an existing synchronous filesystem implementation and wraps all its methods to provide an asynchronous interface.
Parameters ---------- sync_fs : AbstractFileSystem The synchronous filesystem instance to wrap. """
protocol = "asyncwrapper", "async_wrapper" cachable = False
def __init__( self, fs=None, asynchronous=None, target_protocol=None, target_options=None, semaphore=None, max_concurrent_tasks=None, **kwargs, ): if asynchronous is None: asynchronous = running_async() super().__init__(asynchronous=asynchronous, **kwargs) if fs is not None: self.sync_fs = fs else: self.sync_fs = fsspec.filesystem(target_protocol, **target_options) self.protocol = self.sync_fs.protocol # paths must be normalized the way the wrapped filesystem does it self.root_marker = self.sync_fs.root_marker self._strip_protocol = self.sync_fs._strip_protocol self._parent = self.sync_fs._parent self.semaphore = semaphore self._wrap_all_sync_methods()
@property def fsid(self): return f"async_{self.sync_fs.fsid}"
def _wrap_all_sync_methods(self): """ Wrap all synchronous methods of the underlying filesystem with asynchronous versions. """ excluded_methods = {"open"} for method_name in dir(self.sync_fs): if method_name.startswith("_") or method_name in excluded_methods: continue
attr = inspect.getattr_static(self.sync_fs, method_name) if isinstance(attr, property): continue
method = getattr(self.sync_fs, method_name) # generators such as ``walk`` cannot become coroutines: the async API # expects async generators, which AsyncFileSystem already builds on # top of the wrapped methods (``_walk`` uses ``_ls``) if ( callable(method) and not inspect.iscoroutinefunction(method) and not inspect.isgeneratorfunction(method) ): async_method = async_wrapper(method, obj=self, semaphore=self.semaphore) setattr(self, f"_{method_name}", async_method)
@classmethod def wrap_class(cls, sync_fs_class): """ Create a new class that can be used to instantiate an AsyncFileSystemWrapper with lazy instantiation of the underlying synchronous filesystem.
Parameters ---------- sync_fs_class : type The class of the synchronous filesystem to wrap.
Returns ------- type A new class that wraps the provided synchronous filesystem class. """
class GeneratedAsyncFileSystemWrapper(cls): def __init__(self, *args, **kwargs): sync_fs = sync_fs_class(*args, **kwargs) super().__init__(sync_fs)
GeneratedAsyncFileSystemWrapper.__name__ = ( f"Async{sync_fs_class.__name__}Wrapper" ) return GeneratedAsyncFileSystemWrapper123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475from __future__ import annotations
import abcimport hashlib
from fsspec.implementations.local import make_path_posix
class AbstractCacheMapper(abc.ABC): """Abstract super-class for mappers from remote URLs to local cached basenames. """
@abc.abstractmethod def __call__(self, path: str) -> str: ...
def __eq__(self, other: object) -> bool: # Identity only depends on class. When derived classes have attributes # they will need to be included. return isinstance(other, type(self))
def __hash__(self) -> int: # Identity only depends on class. When derived classes have attributes # they will need to be included. return hash(type(self))
class BasenameCacheMapper(AbstractCacheMapper): """Cache mapper that uses the basename of the remote URL and a fixed number of directory levels above this.
The default is zero directory levels, meaning different paths with the same basename will have the same cached basename. """
def __init__(self, directory_levels: int = 0): if directory_levels < 0: raise ValueError( "BasenameCacheMapper requires zero or positive directory_levels" ) self.directory_levels = directory_levels
# Separator for directories when encoded as strings. self._separator = "_@_"
def __call__(self, path: str) -> str: path = make_path_posix(path) prefix, *bits = path.rsplit("/", self.directory_levels + 1) if bits: return self._separator.join(bits) else: return prefix # No separator found, simple filename
def __eq__(self, other: object) -> bool: return super().__eq__(other) and self.directory_levels == other.directory_levels
def __hash__(self) -> int: return super().__hash__() ^ hash(self.directory_levels)
class HashCacheMapper(AbstractCacheMapper): """Cache mapper that uses a hash of the remote URL."""
def __call__(self, path: str) -> str: return hashlib.sha256(path.encode()).hexdigest()
def create_cache_mapper(same_names: bool) -> AbstractCacheMapper: """Factory method to create cache mapper for backward compatibility with ``CachingFileSystem`` constructor using ``same_names`` kwarg. """ if same_names: return BasenameCacheMapper() else: return HashCacheMapper()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217from __future__ import annotations
import osimport timefrom typing import TYPE_CHECKING
from fsspec.utils import atomic_write
try: import ujson as jsonexcept ImportError: if not TYPE_CHECKING: import json
if TYPE_CHECKING: from collections.abc import Iterator from typing import Any, Literal, TypeAlias
from .cached import CachingFileSystem
Detail: TypeAlias = dict[str, Any]
class CacheMetadata: """Cache metadata.
All reading and writing of cache metadata is performed by this class, accessing the cached files and blocks is not.
Metadata is stored in a single file per storage directory in JSON format. For backward compatibility. No longer supports pickle. """
def __init__(self, storage: list[str]): """
Parameters ---------- storage: list[str] Directories containing cached files, must be at least one. Metadata is stored in the last of these directories by convention. """ if not storage: raise ValueError("CacheMetadata expects at least one storage location")
self._storage = storage self.cached_files: list[Detail] = [{}]
def _load(self, fn: str) -> Detail: """Low-level function to load metadata from specific file""" with open(fn, "r") as f: loaded = json.load(f) for c in loaded.values(): if isinstance(c.get("blocks"), list): c["blocks"] = set(c["blocks"]) return loaded
def _save(self, metadata_to_save: Detail, fn: str) -> None: """Low-level function to save metadata to specific file""" with atomic_write(fn, mode="w") as f: json.dump(metadata_to_save, f)
def _scan_locations( self, writable_only: bool = False ) -> Iterator[tuple[str, str, bool]]: """Yield locations (filenames) where metadata is stored, and whether writable or not.
Parameters ---------- writable: bool Set to True to only yield writable locations.
Returns ------- Yields (str, str, bool) """ n = len(self._storage) for i, storage in enumerate(self._storage): writable = i == n - 1 if writable_only and not writable: continue yield os.path.join(storage, "cache"), storage, writable
def check_file( self, path: str, cfs: CachingFileSystem | None ) -> Literal[False] | tuple[Detail, str]: """If path is in cache return its details, otherwise return ``False``.
If the optional CachingFileSystem is specified then it is used to perform extra checks to reject possible matches, such as if they are too old. """ for (fn, base, _), cache in zip(self._scan_locations(), self.cached_files): if path not in cache: continue detail = cache[path].copy()
if cfs is not None: if cfs.check_files and detail["uid"] != cfs.fs.ukey(path): # Wrong file as determined by hash of file properties continue if cfs.expiry and time.time() - detail["time"] > cfs.expiry: # Cached file has expired continue
fn = os.path.join(base, detail["fn"]) if os.path.exists(fn): return detail, fn return False
def clear_expired(self, expiry_time: int) -> tuple[list[str], bool]: """Remove expired metadata from the cache.
Returns names of files corresponding to expired metadata and a boolean flag indicating whether the writable cache is empty. Caller is responsible for deleting the expired files. """ expired_files = [] for path, detail in self.cached_files[-1].copy().items(): if time.time() - detail["time"] > expiry_time: fn = detail.get("fn", "") if not fn: raise RuntimeError( f"Cache metadata does not contain 'fn' for {path}" ) fn = os.path.join(self._storage[-1], fn) expired_files.append(fn) self.cached_files[-1].pop(path)
if self.cached_files[-1]: cache_path = os.path.join(self._storage[-1], "cache") self._save(self.cached_files[-1], cache_path)
writable_cache_empty = not self.cached_files[-1] return expired_files, writable_cache_empty
def load(self) -> None: """Load all metadata from disk and store in ``self.cached_files``""" cached_files = [] for fn, _, _ in self._scan_locations(): if os.path.exists(fn): # TODO: consolidate blocks here cached_files.append(self._load(fn)) else: cached_files.append({}) self.cached_files = cached_files or [{}]
def on_close_cached_file(self, f: Any, path: str) -> None: """Perform side-effect actions on closing a cached file.
The actual closing of the file is the responsibility of the caller. """ # File must be writable, so in self.cached_files[-1] c = self.cached_files[-1][path] if c["blocks"] is not True and len(c["blocks"]) * f.blocksize >= f.size: c["blocks"] = True
def pop_file(self, path: str) -> str | None: """Remove metadata of cached file.
If path is in the cache, return the filename of the cached file, otherwise return ``None``. Caller is responsible for deleting the cached file. """ details = self.check_file(path, None) if not details: return None _, fn = details if fn.startswith(self._storage[-1]): self.cached_files[-1].pop(path) self.save() else: raise PermissionError( "Can only delete cached file in last, writable cache location" ) return fn
def save(self) -> None: """Save metadata to disk""" for (fn, _, writable), cache in zip(self._scan_locations(), self.cached_files): if not writable: continue
if os.path.exists(fn): cached_files = self._load(fn) for k, c in cached_files.items(): if k in cache: if c["blocks"] is True or cache[k]["blocks"] is True: c["blocks"] = True else: # self.cached_files[*][*]["blocks"] must continue to # point to the same set object so that updates # performed by MMapCache are propagated back to # self.cached_files. blocks = cache[k]["blocks"] blocks.update(c["blocks"]) c["blocks"] = blocks c["time"] = max(c["time"], cache[k]["time"]) c["uid"] = cache[k]["uid"]
# Files can be added to cache after it was written once for k, c in cache.items(): if k not in cached_files: cached_files[k] = c else: cached_files = cache cache = {k: v.copy() for k, v in cached_files.items()} for c in cache.values(): if isinstance(c["blocks"], set): c["blocks"] = list(c["blocks"]) self._save(cache, fn) self.cached_files[-1] = cached_files
def update_file(self, path: str, detail: Detail) -> None: """Update metadata for specific file in memory, do not save""" self.cached_files[-1][path] = detail123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224from __future__ import annotations
import asyncioimport inspectimport loggingimport osimport secretsimport tempfileimport timeimport weakreffrom collections.abc import Callablefrom contextlib import ExitStack, contextmanager, suppressfrom hashlib import sha256from shutil import rmtreefrom typing import TYPE_CHECKING, Any, ClassVar
from fsspec import filesystemfrom fsspec.asyn import _run_coros_in_chunksfrom fsspec.callbacks import DEFAULT_CALLBACKfrom fsspec.compression import comprfrom fsspec.core import BaseCache, MMapCachefrom fsspec.exceptions import BlocksizeMismatchErrorfrom fsspec.implementations.cache_mapper import create_cache_mapperfrom fsspec.implementations.cache_metadata import CacheMetadatafrom fsspec.implementations.chained import ChainedFileSystemfrom fsspec.implementations.local import LocalFileSystemfrom fsspec.spec import AbstractBufferedFile, AbstractFileSystemfrom fsspec.transaction import Transactionfrom fsspec.utils import infer_compression
if TYPE_CHECKING: from fsspec.implementations.cache_mapper import AbstractCacheMapper
logger = logging.getLogger("fsspec.cached")
@contextmanagerdef _tempfile(lpath): # download to a temporary file, renamed into place once complete, so that # a partial download is never visible under its final cache name (#639) tmp = os.path.join(os.path.dirname(lpath), f"{secrets.token_hex(8)}.part") try: # stamp the start from the filesystem's clock: windows mtimes can lag time.time() open(tmp, "wb").close() start = os.path.getmtime(tmp) os.remove(tmp) yield tmp try: os.replace(tmp, lpath) except PermissionError: # windows: destination open elsewhere. A same-size file written # since we started is a concurrent copy of the same download. if not ( os.path.isfile(lpath) and os.path.getsize(lpath) == os.path.getsize(tmp) and os.path.getmtime(lpath) >= start ): raise finally: with suppress(OSError): os.remove(tmp)
def _atomic_get(fs, rpaths, lpaths, callback=DEFAULT_CALLBACK): with ExitStack() as stack: fs.get( rpaths, [stack.enter_context(_tempfile(fn)) for fn in lpaths], callback=callback, )
class WriteCachedTransaction(Transaction): def complete(self, commit=True): if not commit: return super().complete(commit=False) rpaths = [f.path for f in self.files] lpaths = [f.fn for f in self.files] if commit: self.fs.put(lpaths, rpaths) self.files.clear() self.fs._intrans = False self.fs._transaction = None self.fs = None # break cycle
class CachingFileSystem(ChainedFileSystem): """Locally caching filesystem, layer over any other FS
This class implements chunk-wise local storage of remote files, for quick access after the initial download. The files are stored in a given directory with hashes of URLs for the filenames. If no directory is given, a temporary one is used, which should be cleaned up by the OS after the process ends. The files themselves are sparse (as implemented in :class:`~fsspec.caching.MMapCache`), so only the data which is accessed takes up space.
Restrictions:
- the block-size must be the same for each access of a given file, unless all blocks of the file have already been read - caching can only be applied to file-systems which produce files derived from fsspec.spec.AbstractBufferedFile. """
protocol: ClassVar[str | tuple[str, ...]] = ("blockcache", "cached") _strip_tokenize_options = ("fo",)
def __init__( self, target_protocol=None, cache_storage="TMP", cache_check=10, check_files=False, expiry_time=604800, target_options=None, fs=None, same_names: bool | None = None, compression=None, cache_mapper: AbstractCacheMapper | None = None, cache_storage_mode=None, callback=DEFAULT_CALLBACK, **kwargs, ): """
Parameters ---------- target_protocol: str (optional) Target filesystem protocol. Provide either this or ``fs``. cache_storage: str or list(str) Location to store files. If "TMP", this is a temporary directory, and will be cleaned up by the OS when this process ends (or later). If a list, each location will be tried in the order given, but only the last will be considered writable. cache_check: int Number of seconds between reload of cache metadata check_files: bool Whether to explicitly see if the UID of the remote file matches the stored one before using. Warning: some file systems such as HTTP cannot reliably give a unique hash of the contents of some path, so be sure to set this option to False. expiry_time: int The time in seconds after which a local copy is considered useless. Set to falsy to prevent expiry. The default is equivalent to one week. target_options: dict or None Passed to the instantiation of the FS, if fs is None. fs: filesystem instance The target filesystem to run against. Provide this or ``protocol``. same_names: bool (optional) By default, target URLs are hashed using a ``HashCacheMapper`` so that files from different backends with the same basename do not conflict. If this argument is ``true``, a ``BasenameCacheMapper`` is used instead. Other cache mapper options are available by using the ``cache_mapper`` keyword argument. Only one of this and ``cache_mapper`` should be specified. compression: str (optional) To decompress on download. Can be 'infer' (guess from the URL name), one of the entries in ``fsspec.compression.compr``, or None for no decompression. cache_mapper: AbstractCacheMapper (optional) The object use to map from original filenames to cached filenames. Only one of this and ``same_names`` should be specified. cache_storage_mode: int (optional) Permission mode used when creating the cache storage directory, e.g. ``0o700``. The default of ``None`` leaves the directory at the system default (governed by the umask), which is the existing behaviour. Pass an octal mode such as ``0o700`` to keep the cache directory, and so the cached data files within it, readable by the owner only. callback: fsspec.callbacks.Callback (optional) Receives the progress of the downloads made into the cache on a cache miss, i.e. the ``get`` operations on the target filesystem when ``filecache`` or ``simplecache`` first open, ``cat`` or ``cat_ranges`` a file. The block-wise ``blockcache`` fetches ranges on demand and does not use it. """ super().__init__(**kwargs) if fs is None and target_protocol is None: raise ValueError( "Please provide filesystem instance(fs) or target_protocol" ) if not (fs is None) ^ (target_protocol is None): raise ValueError( "Both filesystems (fs) and target_protocol may not be both given." ) if cache_storage == "TMP": tempdir = tempfile.mkdtemp() storage = [tempdir] weakref.finalize(self, self._remove_tempdir, tempdir) else: if isinstance(cache_storage, str): storage = [cache_storage] else: storage = cache_storage self.cache_storage_mode = cache_storage_mode self._makedirs(storage[-1]) self.storage = storage self.kwargs = target_options or {} self.cache_check = cache_check self.check_files = check_files self.expiry = expiry_time self.compression = compression self.callback = callback
# Size of cache in bytes. If None then the size is unknown and will be # recalculated the next time cache_size() is called. On writes to the # cache this is reset to None. self._cache_size = None
if same_names is not None and cache_mapper is not None: raise ValueError( "Cannot specify both same_names and cache_mapper in " "CachingFileSystem.__init__" ) if cache_mapper is not None: self._mapper = cache_mapper else: self._mapper = create_cache_mapper( same_names if same_names is not None else False )
self.target_protocol = ( target_protocol if isinstance(target_protocol, str) else (fs.protocol if isinstance(fs.protocol, str) else fs.protocol[0]) ) self._metadata = CacheMetadata(self.storage) self.load_cache() self.fs = fs if fs is not None else filesystem(target_protocol, **self.kwargs)
def _strip_protocol(path): # acts as a method, since each instance has a difference target return self.fs._strip_protocol(type(self)._strip_protocol(path))
self._strip_protocol: Callable = _strip_protocol
@staticmethod def _remove_tempdir(tempdir): try: rmtree(tempdir) except Exception: pass
def _makedirs(self, path): if self.cache_storage_mode is None: os.makedirs(path, exist_ok=True) else: os.makedirs(path, exist_ok=True, mode=self.cache_storage_mode)
def _mkcache(self): self._makedirs(self.storage[-1])
def cache_size(self): """Return size of cache in bytes.
If more than one cache directory is in use, only the size of the last one (the writable cache directory) is returned. """ if self._cache_size is None: cache_dir = self.storage[-1] self._cache_size = filesystem("file").du(cache_dir, withdirs=True) return self._cache_size
def load_cache(self): """Read set of stored blocks from file""" self._metadata.load() self._mkcache() self.last_cache = time.time()
def save_cache(self): """Save set of stored blocks from file""" self._mkcache() self._metadata.save() self.last_cache = time.time() self._cache_size = None
def _check_cache(self): """Reload caches if time elapsed or any disappeared""" self._mkcache() if not self.cache_check: # explicitly told not to bother checking return timecond = time.time() - self.last_cache > self.cache_check existcond = all(os.path.exists(storage) for storage in self.storage) if timecond or not existcond: self.load_cache()
def _check_file(self, path): """Is path in cache and still valid""" path = self._strip_protocol(path) self._check_cache() return self._metadata.check_file(path, self)
def clear_cache(self): """Remove all files and metadata from the cache
In the case of multiple cache locations, this clears only the last one, which is assumed to be the read/write one. """ rmtree(self.storage[-1]) self.load_cache() self._cache_size = None
def clear_expired_cache(self, expiry_time=None): """Remove all expired files and metadata from the cache
In the case of multiple cache locations, this clears only the last one, which is assumed to be the read/write one.
Parameters ---------- expiry_time: int The time in seconds after which a local copy is considered useless. If not defined the default is equivalent to the attribute from the file caching instantiation. """
if expiry_time is None: if not self.expiry: # "Set to falsy to prevent expiry" (see __init__): nothing # ever goes stale, so there is nothing to clear. return expiry_time = self.expiry
self._check_cache()
expired_files, writable_cache_empty = self._metadata.clear_expired(expiry_time) for fn in expired_files: if os.path.exists(fn): os.remove(fn)
if writable_cache_empty: rmtree(self.storage[-1]) self.load_cache()
self._cache_size = None
def pop_from_cache(self, path): """Remove cached version of given file
Deletes local copy of the given (remote) path. If it is found in a cache location which is not the last, it is assumed to be read-only, and raises PermissionError """ path = self._strip_protocol(path) fn = self._metadata.pop_file(path) if fn is not None: os.remove(fn) self._cache_size = None
def _open( self, path, mode="rb", block_size=None, autocommit=True, cache_options=None, **kwargs, ): """Wrap the target _open
If the whole file exists in the cache, just open it locally and return that.
Otherwise, open the file on the target FS, and make it have a mmap cache pointing to the location which we determine, in our cache. The ``blocks`` instance is shared, so as the mmap cache instance updates, so does the entry in our ``cached_files`` attribute. We monkey-patch this file, so that when it closes, we call ``close_and_update`` to save the state of the blocks. """ path = self._strip_protocol(path)
path = self.fs._strip_protocol(path) if "r" not in mode: return self.fs._open( path, mode=mode, block_size=block_size, autocommit=autocommit, cache_options=cache_options, **kwargs, ) detail = self._check_file(path) if detail: # file is in cache detail, fn = detail hash, blocks = detail["fn"], detail["blocks"] if blocks is True: # stored file is complete logger.debug("Opening local copy of %s", path) return open(fn, mode) # TODO: action where partial file exists in read-only cache logger.debug("Opening partially cached copy of %s", path) else: hash = self._mapper(path) fn = os.path.join(self.storage[-1], hash) blocks = set() detail = { "original": path, "fn": hash, "blocks": blocks, "time": time.time(), "uid": self.fs.ukey(path), } self._metadata.update_file(path, detail) logger.debug("Creating local sparse file for %s", path)
# explicitly submitting the size to the open call will avoid extra # operations when opening. This is particularly relevant # for any file that is read over a network, e.g. S3. size = detail.get("size")
# call target filesystems open self._mkcache() f = self.fs._open( path, mode=mode, block_size=block_size, autocommit=autocommit, cache_options=cache_options, cache_type="none", size=size, **kwargs, )
# set size if not already set if size is None: detail["size"] = f.size self._metadata.update_file(path, detail)
if self.compression: comp = ( infer_compression(path) if self.compression == "infer" else self.compression ) f = compr[comp](f, mode="rb") if "blocksize" in detail: if detail["blocksize"] != f.blocksize: raise BlocksizeMismatchError( f"Cached file must be reopened with same block" f" size as original (old: {detail['blocksize']}," f" new {f.blocksize})" ) else: detail["blocksize"] = f.blocksize
def _fetch_ranges(ranges): return self.fs.cat_ranges( [path] * len(ranges), [r[0] for r in ranges], [r[1] for r in ranges], **kwargs, )
multi_fetcher = None if self.compression else _fetch_ranges f.cache = MMapCache( f.blocksize, f._fetch_range, f.size, fn, blocks, multi_fetcher=multi_fetcher ) close = f.close f.close = lambda: self.close_and_update(f, close) self.save_cache() return f
def _parent(self, path): return self.fs._parent(path)
def hash_name(self, path: str, *args: Any) -> str: # Kept for backward compatibility with downstream libraries. # Ignores extra arguments, previously same_name boolean. return self._mapper(path)
def close_and_update(self, f, close): """Called when a file is closing, so store the set of blocks""" if f.closed: return path = self._strip_protocol(f.path) self._metadata.on_close_cached_file(f, path) try: logger.debug("going to save") self.save_cache() logger.debug("saved") except OSError: logger.debug("Cache saving failed while closing file") except NameError: logger.debug("Cache save failed due to interpreter shutdown") close() f.closed = True
def ls(self, path, detail=True, **kwargs): return self.fs.ls(path, detail, **kwargs)
def __getattribute__(self, item): if item in { "load_cache", "_get_cached_file_before_open", "_open", "save_cache", "close_and_update", "__init__", "__getattribute__", "__reduce__", "_make_local_details", "_ukey_async", "_check_file_async", "_download_async", "open", "cat", "cat_file", "_cat_file", "cat_ranges", "_cat_ranges", "_local_paths_for_ranges", "get", "read_block", "tail", "head", "info", "ls", "exists", "isfile", "isdir", "_check_file", "_check_cache", "_makedirs", "_mkcache", "clear_cache", "clear_expired_cache", "pop_from_cache", "local_file", "_paths_from_path", "get_mapper", "open_many", "commit_many", "hash_name", "__hash__", "__eq__", "to_json", "to_dict", "cache_size", "pipe_file", "pipe", "start_transaction", "end_transaction", }: # all the methods defined in this class. Note `open` here, since # it calls `_open`, but is actually in superclass if hasattr(type(self), item): return lambda *args, **kw: getattr(type(self), item).__get__(self)( *args, **kw ) # method is in the whitelist but not defined on this subclass; # fall through to delegate to the wrapped filesystem below if item in ["__reduce_ex__"]: raise AttributeError if item in ["transaction"]: # property return type(self).transaction.__get__(self) if item in {"_cache", "transaction_type", "protocol"}: # class attributes return getattr(type(self), item) if item == "__class__": return type(self) d = object.__getattribute__(self, "__dict__") fs = d.get("fs", None) # fs is not immediately defined if item in d: return d[item] elif fs is not None: if item in fs.__dict__: # attribute of instance return fs.__dict__[item] # attributed belonging to the target filesystem cls = type(fs) m = getattr(cls, item) if (inspect.isfunction(m) or inspect.isdatadescriptor(m)) and ( not hasattr(m, "__self__") or m.__self__ is None ): # instance method return m.__get__(fs, cls) return m # class method or attribute else: # attributes of the superclass, while target is being set up return super().__getattribute__(item)
def __eq__(self, other): """Test for equality.""" if self is other: return True if not isinstance(other, type(self)): return False return ( self.storage == other.storage and self.kwargs == other.kwargs and self.cache_check == other.cache_check and self.check_files == other.check_files and self.expiry == other.expiry and self.compression == other.compression and self._mapper == other._mapper and self.target_protocol == other.target_protocol )
def __hash__(self): """Calculate hash.""" return ( hash(tuple(self.storage)) ^ hash(str(self.kwargs)) ^ hash(self.cache_check) ^ hash(self.check_files) ^ hash(self.expiry) ^ hash(self.compression) ^ hash(self._mapper) ^ hash(self.target_protocol) )
class WholeFileCacheFileSystem(CachingFileSystem): """Caches whole remote files on first access
This class is intended as a layer over any other file system, and will make a local copy of each file accessed, so that all subsequent reads are local. This is similar to ``CachingFileSystem``, but without the block-wise functionality and so can work even when sparse files are not allowed. See its docstring for definition of the init arguments.
The class still needs access to the remote store for listing files, and may refresh cached files. """
protocol = "filecache" local_file = True
def open_many(self, open_files, **kwargs): paths = [of.path for of in open_files] if "r" in open_files.mode: self._mkcache() else: return [ LocalTempFile( self.fs, path, mode=open_files.mode, fn=os.path.join(self.storage[-1], self._mapper(path)), **kwargs, ) for path in paths ]
if self.compression: raise NotImplementedError details = [self._check_file(sp) for sp in paths] downpath = [p for p, d in zip(paths, details) if not d] downfn0 = [ os.path.join(self.storage[-1], self._mapper(p)) for p, d in zip(paths, details) ] # keep these path names for opening later downfn = [fn for fn, d in zip(downfn0, details) if not d] if downpath: # skip if all files are already cached and up to date _atomic_get(self.fs, downpath, downfn, callback=self.callback)
# update metadata - only happens when downloads are successful newdetail = [ { "original": path, "fn": self._mapper(path), "blocks": True, "time": time.time(), "uid": self.fs.ukey(path), } for path in downpath ] for path, detail in zip(downpath, newdetail): self._metadata.update_file(path, detail) self.save_cache()
def firstpart(fn): # helper to adapt both whole-file and simple-cache return fn[1] if isinstance(fn, tuple) else fn
return [ open(firstpart(fn0) if fn0 else fn1, mode=open_files.mode) for fn0, fn1 in zip(details, downfn0) ]
def commit_many(self, open_files): self.fs.put([f.fn for f in open_files], [f.path for f in open_files]) [f.close() for f in open_files] for f in open_files: # in case autocommit is off, and so close did not already delete try: os.remove(f.name) except FileNotFoundError: pass self._cache_size = None
def _make_local_details(self, path, uid=None): hash = self._mapper(path) fn = os.path.join(self.storage[-1], hash) detail = { "original": path, "fn": hash, "blocks": True, "time": time.time(), "uid": self.fs.ukey(path) if uid is None else uid, } self._metadata.update_file(path, detail) logger.debug("Copying %s to local cache", path) return fn
async def _ukey_async(self, path): # the default ukey calls sync info(), which fails in a running loop; # an override may too (s3fs's does), so run it off the loop if type(self.fs).ukey is AbstractFileSystem.ukey: return sha256(str(await self.fs._info(path)).encode()).hexdigest() return await asyncio.to_thread(self.fs.ukey, path)
async def _check_file_async(self, path): # _check_file, with the async-safe ukey for check_files self._check_cache() detail = self._metadata.check_file(path, None) if not detail: return False detail, fn = detail if self.check_files and detail["uid"] != await self._ukey_async(path): return False if self.expiry and time.time() - detail["time"] > self.expiry: return False if detail["blocks"] is not True: return False # a partial blockcache entry sharing this directory return fn
async def _download_async(self, path, fn, **kwargs): kwargs.setdefault("callback", self.callback) with _tempfile(fn) as tmp: await self.fs._get_file(path, tmp, **kwargs) if not self.compression: # a compressed download is left unrecorded, for open() to redo self._make_local_details(path, uid=await self._ukey_async(path))
def cat( self, path, recursive=False, on_error="raise", callback=DEFAULT_CALLBACK, **kwargs, ): paths = self.expand_path( path, recursive=recursive, maxdepth=kwargs.get("maxdepth") ) getpaths = [] storepaths = [] fns = [] out = {} for p in paths.copy(): try: detail = self._check_file(p) if not detail: if self.compression: self._get_cached_file_before_open(p) fn = os.path.join(self.storage[-1], self._mapper(p)) else: fn = self._make_local_details(p) getpaths.append(p) storepaths.append(fn) else: detail, fn = detail if isinstance(detail, tuple) else (None, detail) fns.append(fn) except Exception as e: if on_error == "raise": raise if on_error == "return": out[p] = e paths.remove(p)
if getpaths: _atomic_get(self.fs, getpaths, storepaths, callback=self.callback) self.save_cache()
callback.set_size(len(paths)) for p, fn in zip(paths, fns): with open(fn, "rb") as f: out[p] = f.read() callback.relative_update(1) if isinstance(path, str) and len(paths) == 1 and recursive is False: out = out[paths[0]] return out
def _get_cached_file_before_open(self, path, **kwargs): fn = self._make_local_details(path) # call target filesystems open self._mkcache() if self.compression: with ( _tempfile(fn) as tmp, self.fs._open(path, mode="rb", **kwargs) as f, open(tmp, "wb") as f2, ): if isinstance(f, AbstractBufferedFile): # want no type of caching if just downloading whole thing f.cache = BaseCache(0, f.cache.fetcher, f.size) comp = ( infer_compression(path) if self.compression == "infer" else self.compression ) f = compr[comp](f, mode="rb") data = True while data: block = getattr(f, "blocksize", 5 * 2**20) data = f.read(block) f2.write(data) else: with _tempfile(fn) as tmp: self.fs.get_file(path, tmp, callback=self.callback) self.save_cache() return self._metadata.cached_files[-1][path].copy(), fn
def _open(self, path, mode="rb", **kwargs): path = self._strip_protocol(path) # For read (or append), (try) download from remote if "r" in mode or "a" in mode: cached = self._check_file(path) if not cached: if self.fs.exists(path): cached = self._get_cached_file_before_open(path, **kwargs) elif "r" in mode: raise FileNotFoundError(path)
# Use this open's selected file, even if it expired during download. if cached: detail, fn = cached _, blocks = detail["fn"], detail["blocks"] if blocks is True: logger.debug("Opening local copy of %s", path) else: raise ValueError( f"Attempt to open partially cached file {path}" f" as a wholly cached file" )
# Just reading does not need special file handling if "r" in mode and "+" not in mode: # In order to support downstream filesystems to be able to # infer the compression from the original filename, like # the `TarFileSystem`, let's extend the `io.BufferedReader` # fileobject protocol by adding a dedicated attribute # `original`. f = open(fn, mode) f.original = detail.get("original") return f
hash = self._mapper(path) fn = os.path.join(self.storage[-1], hash) user_specified_kwargs = { k: v for k, v in kwargs.items() # those kwargs were added by open(), we don't want them if k not in ["autocommit", "block_size", "cache_options"] } return LocalTempFile(self, path, mode=mode, fn=fn, **user_specified_kwargs)
async def _cat_file(self, path, start=None, end=None, **kwargs): logger.debug("async cat_file %s", path) path = self._strip_protocol(path) sha = self._mapper(path) fn = await self._check_file_async(path)
if not fn: fn = os.path.join(self.storage[-1], sha) await self._download_async(path, fn, **kwargs) self.save_cache()
with open(fn, "rb") as f: # noqa ASYNC230 if start: f.seek(start) size = -1 if end is None else end - f.tell() return f.read(size)
def _local_paths_for_ranges(self, paths): """Cache file for each of paths, and which remote files to download
A path given more than once is downloaded once, and every occurrence reads from the same cache file. """ lpaths = [] local = {} download = [] rpaths = [] for p in paths: if p not in local: detail = self._check_file(p) if not detail: fn = os.path.join(self.storage[-1], self._mapper(p)) download.append(fn) rpaths.append(p) else: # filecache returns (detail, fn), simplecache just fn fn = detail[1] if isinstance(detail, tuple) else detail local[p] = fn lpaths.append(local[p]) return lpaths, rpaths, download
async def _cat_ranges( self, paths, starts, ends, max_gap=None, on_error="return", **kwargs ): logger.debug("async cat ranges %s", paths) # _local_paths_for_ranges, but the validity check is a coroutine here paths = [self._strip_protocol(p) for p in paths] lpaths = [] local = {} need = {} for p in paths: if p not in local: local[p] = await self._check_file_async(p) or need.setdefault( p, os.path.join(self.storage[-1], self._mapper(p)) ) lpaths.append(local[p]) errors = {} if need: # not self.fs._get: each download needs its own temp file results = await _run_coros_in_chunks( [self._download_async(p, fn, **kwargs) for p, fn in need.items()], batch_size=self.fs.batch_size, return_exceptions=True, ) errors = {p: e for p, e in zip(need, results) if isinstance(e, Exception)} self.save_cache() if errors and on_error == "raise": raise next(iter(errors.values()))
out = LocalFileSystem().cat_ranges( lpaths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs ) if on_error == "return": # report the download error, not the missing local copy out = [errors.get(p, o) for p, o in zip(paths, out)] return out
class SimpleCacheFileSystem(WholeFileCacheFileSystem): """Caches whole remote files on first access
This class is intended as a layer over any other file system, and will make a local copy of each file accessed, so that all subsequent reads are local. This implementation only copies whole files, and does not keep any metadata about the download time or file details. It is therefore safer to use in multi-threaded/concurrent situations.
This is the only of the caching filesystems that supports write: you will be given a real local open file, and upon close and commit, it will be uploaded to the target filesystem; the writability or the target URL is not checked until that time.
"""
protocol = "simplecache" local_file = True transaction_type = WriteCachedTransaction
def __init__(self, **kwargs): kw = kwargs.copy() for key in ["cache_check", "expiry_time", "check_files"]: kw[key] = False super().__init__(**kw) for storage in self.storage: if not os.path.exists(storage): self._makedirs(storage)
def _check_file(self, path): self._check_cache() sha = self._mapper(path) for storage in self.storage: fn = os.path.join(storage, sha) if os.path.exists(fn): return fn
def save_cache(self): pass
def load_cache(self): pass
def clear_expired_cache(self, expiry_time=None): """Remove cached files older than ``expiry_time`` seconds.
SimpleCache does not store metadata, so cached file modification times are used instead. Only the last (writable) cache location is changed.
Parameters ---------- expiry_time: int or float Maximum age of a cached file in seconds. This must be supplied explicitly because SimpleCache has no configured expiry time. """ if expiry_time is None: raise ValueError("expiry_time must be provided for simplecache") if expiry_time < 0: raise ValueError("expiry_time must be non-negative")
self._mkcache() cutoff = time.time() - expiry_time with os.scandir(self.storage[-1]) as entries: for entry in entries: try: if ( entry.is_file(follow_symlinks=False) and entry.stat(follow_symlinks=False).st_mtime < cutoff ): os.remove(entry.path) except FileNotFoundError: # Another process may be using the same simple cache. pass self._cache_size = None
async def _check_file_async(self, path): return self._check_file(path) # existence-based, no remote I/O
async def _download_async(self, path, fn, **kwargs): # no metadata to record (and no ukey lookup needed) kwargs.setdefault("callback", self.callback) with _tempfile(fn) as tmp: await self.fs._get_file(path, tmp, **kwargs)
def pipe_file(self, path, value=None, **kwargs): if self._intrans: with self.open(path, "wb") as f: f.write(value) else: super().pipe_file(path, value)
def ls(self, path, detail=True, **kwargs): path = self._strip_protocol(path) details = [] try: details = self.fs.ls( path, detail=True, **kwargs ).copy() # don't edit original! except FileNotFoundError as e: ex = e else: ex = None if self._intrans: path1 = path.rstrip("/") + "/" for f in self.transaction.files: if f.path == path: details.append( {"name": path, "size": f.size or f.tell(), "type": "file"} ) elif f.path.startswith(path1): if f.path.count("/") == path1.count("/"): details.append( {"name": f.path, "size": f.size or f.tell(), "type": "file"} ) else: dname = "/".join(f.path.split("/")[: path1.count("/") + 1]) details.append({"name": dname, "size": 0, "type": "directory"}) if ex is not None and not details: raise ex if detail: return details return sorted(_["name"] for _ in details)
def info(self, path, **kwargs): path = self._strip_protocol(path) if self._intrans: f = [_ for _ in self.transaction.files if _.path == path] if f: size = os.path.getsize(f[0].fn) if f[0].closed else f[0].tell() return {"name": path, "size": size, "type": "file"} f = any(_.path.startswith(path + "/") for _ in self.transaction.files) if f: return {"name": path, "size": 0, "type": "directory"} return self.fs.info(path, **kwargs)
def pipe(self, path, value=None, **kwargs): if isinstance(path, str): self.pipe_file(self._strip_protocol(path), value, **kwargs) elif isinstance(path, dict): for k, v in path.items(): self.pipe_file(self._strip_protocol(k), v, **kwargs) else: raise ValueError("path must be str or dict")
def cat_ranges( self, paths, starts, ends, max_gap=None, on_error="return", **kwargs ): logger.debug("cat ranges %s", paths) lpaths, rpaths, download = self._local_paths_for_ranges(paths) if download: _atomic_get(self.fs, rpaths, download, callback=self.callback) return LocalFileSystem().cat_ranges( lpaths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs )
def _get_cached_file_before_open(self, path, **kwargs): sha = self._mapper(path) fn = os.path.join(self.storage[-1], sha) logger.debug("Copying %s to local cache", path)
self._mkcache() self._cache_size = None
if self.compression: with ( _tempfile(fn) as tmp, self.fs._open(path, mode="rb", **kwargs) as f, open(tmp, "wb") as f2, ): if isinstance(f, AbstractBufferedFile): # want no type of caching if just downloading whole thing f.cache = BaseCache(0, f.cache.fetcher, f.size) comp = ( infer_compression(path) if self.compression == "infer" else self.compression ) f = compr[comp](f, mode="rb") data = True while data: block = getattr(f, "blocksize", 5 * 2**20) data = f.read(block) f2.write(data) else: with _tempfile(fn) as tmp: self.fs.get_file(path, tmp, callback=self.callback)
def _open(self, path, mode="rb", **kwargs): path = self._strip_protocol(path) sha = self._mapper(path)
# For read (or append), (try) download from remote if "r" in mode or "a" in mode: if not self._check_file(path): # append does not require an existing file but read does if self.fs.exists(path): self._get_cached_file_before_open(path, **kwargs) elif "r" in mode: raise FileNotFoundError(path)
fn = self._check_file(path) # Just reading does not need special file handling if "r" in mode and "+" not in mode: return open(fn, mode)
fn = os.path.join(self.storage[-1], sha) user_specified_kwargs = { k: v for k, v in kwargs.items() if k not in ["autocommit", "block_size", "cache_options"] } # those were added by open() return LocalTempFile( self, path, mode=mode, autocommit=not self._intrans, fn=fn, **user_specified_kwargs, )
class LocalTempFile: """A temporary local file, which will be uploaded on commit"""
def __init__(self, fs, path, fn, mode="wb", autocommit=True, seek=0, **kwargs): self.fn = fn self.fh = open(fn, mode) self.mode = mode if seek: self.fh.seek(seek) self.path = path self.size = None self.fs = fs self.closed = False self.autocommit = autocommit self.kwargs = kwargs
def __reduce__(self): # always open in r+b to allow continuing writing at a location return ( LocalTempFile, (self.fs, self.path, self.fn, "r+b", self.autocommit, self.tell()), )
def __enter__(self): return self.fh
def __exit__(self, exc_type, exc_val, exc_tb): self.close()
def close(self): # self.size = self.fh.tell() if self.closed: return self.fh.close() self.closed = True if self.autocommit: self.commit()
def discard(self): self.fh.close() # Repeated writes in one transaction can share a cache filename. with suppress(FileNotFoundError): os.remove(self.fn)
def commit(self): # calling put() with list arguments avoids path expansion and additional operations # like isdir() self.fs.put([self.fn], [self.path], **self.kwargs) # we do not delete the local copy, it's still in the cache.
@property def name(self): return self.fn
def __repr__(self) -> str: return f"LocalTempFile: {self.path}"
def __getattr__(self, item): return getattr(self.fh, item)1234567891011121314151617181920212223from typing import ClassVar
from fsspec import AbstractFileSystem
__all__ = ("ChainedFileSystem",)
class ChainedFileSystem(AbstractFileSystem): """Chained filesystem base class.
A chained filesystem is designed to be layered over another FS. This is useful to implement things like caching.
This base class does very little on its own, but is used as a marker that the class is designed for chaining.
Right now this is only used in `url_to_fs` to provide the path argument (`fo`) to the chained filesystem from the underlying filesystem.
Additional functionality may be added in the future. """
protocol: ClassVar[str] = "chained"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152import daskfrom distributed.client import Client, _get_global_clientfrom distributed.worker import Worker
from fsspec import filesystemfrom fsspec.spec import AbstractBufferedFile, AbstractFileSystemfrom fsspec.utils import infer_storage_options
def _get_client(client): if client is None: return _get_global_client() elif isinstance(client, Client): return client else: # e.g., connection string return Client(client)
def _in_worker(): return bool(Worker._instances)
class DaskWorkerFileSystem(AbstractFileSystem): """View files accessible to a worker as any other remote file-system
When instances are run on the worker, uses the real filesystem. When run on the client, they call the worker to provide information or data.
**Warning** this implementation is experimental, and read-only for now. """
def __init__( self, target_protocol=None, target_options=None, fs=None, client=None, **kwargs ): super().__init__(**kwargs) if not (fs is None) ^ (target_protocol is None): raise ValueError( "Please provide one of filesystem instance (fs) or" " target_protocol, not both" ) self.target_protocol = target_protocol self.target_options = target_options self.worker = None self.client = client self.fs = fs self._determine_worker()
@staticmethod def _get_kwargs_from_urls(path): so = infer_storage_options(path) if "host" in so and "port" in so: return {"client": f"{so['host']}:{so['port']}"} else: return {}
def _determine_worker(self): if _in_worker(): self.worker = True if self.fs is None: self.fs = filesystem( self.target_protocol, **(self.target_options or {}) ) else: self.worker = False self.client = _get_client(self.client) self.rfs = dask.delayed(self)
def mkdir(self, *args, **kwargs): if self.worker: self.fs.mkdir(*args, **kwargs) else: self.rfs.mkdir(*args, **kwargs).compute()
def rm(self, *args, **kwargs): if self.worker: self.fs.rm(*args, **kwargs) else: self.rfs.rm(*args, **kwargs).compute()
def copy(self, *args, **kwargs): if self.worker: self.fs.copy(*args, **kwargs) else: self.rfs.copy(*args, **kwargs).compute()
def mv(self, *args, **kwargs): if self.worker: self.fs.mv(*args, **kwargs) else: self.rfs.mv(*args, **kwargs).compute()
def ls(self, *args, **kwargs): if self.worker: return self.fs.ls(*args, **kwargs) else: return self.rfs.ls(*args, **kwargs).compute()
def _open( self, path, mode="rb", block_size=None, autocommit=True, cache_options=None, **kwargs, ): if self.worker: return self.fs._open( path, mode=mode, block_size=block_size, autocommit=autocommit, cache_options=cache_options, **kwargs, ) else: return DaskFile( fs=self, path=path, mode=mode, block_size=block_size, autocommit=autocommit, cache_options=cache_options, **kwargs, )
def fetch_range(self, path, mode, start, end): if self.worker: with self._open(path, mode) as f: f.seek(start) return f.read(end - start) else: return self.rfs.fetch_range(path, mode, start, end).compute()
class DaskFile(AbstractBufferedFile): def __init__(self, mode="rb", **kwargs): if mode != "rb": raise ValueError('Remote dask files can only be opened in "rb" mode') super().__init__(**kwargs)
def _upload_chunk(self, final=False): pass
def _initiate_upload(self): """Create remote file/upload""" pass
def _fetch_range(self, start, end): """Get the specified set of bytes from remote""" return self.fs.fetch_range(self.path, self.mode, start, end)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import base64import iofrom urllib.parse import unquote_to_bytes
from fsspec import AbstractFileSystemfrom fsspec.utils import stringify_path
class DataFileSystem(AbstractFileSystem): """A handy decoder for data-URLs
Example ------- >>> with fsspec.open("data:,Hello%2C%20World%21") as f: ... print(f.read()) b"Hello, World!"
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs """
protocol = "data"
def __init__(self, **kwargs): """No parameters for this filesystem""" super().__init__(**kwargs)
@classmethod def _strip_protocol(cls, path): if isinstance(path, list): return [cls._strip_protocol(p) for p in path] path = stringify_path(path) if path.startswith("data://"): path = path[7:] elif path.startswith("data:"): path = path[5:] # Do NOT strip trailing slashes, as they may be meaningful base64 characters # or percent-encoded data content return path
def cat_file(self, path, start=None, end=None, **kwargs): # Strip the fragment before decoding so an encoded %23 remains data. pref, data = path.split("#", 1)[0].split(",", 1) if pref.endswith(";base64"): return base64.b64decode(unquote_to_bytes(data))[start:end] return unquote_to_bytes(data)[start:end]
def info(self, path, **kwargs): path = self._strip_protocol(path) pref, name = path.split(",", 1) data = self.cat_file(path) mime = pref.split(";", 1)[0] return {"name": name, "size": len(data), "type": "file", "mimetype": mime}
def _open( self, path, mode="rb", block_size=None, autocommit=True, cache_options=None, **kwargs, ): if "r" not in mode: raise ValueError("Read only filesystem") return io.BytesIO(self.cat_file(path))
@staticmethod def encode(data: bytes, mime: str | None = None): """Format the given data into data-URL syntax
This version always base64 encodes, even when the data is ascii/url-safe. """ return f"data:{mime or ''};base64,{base64.b64encode(data).decode()}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498from __future__ import annotations
import base64import urllib
import requestsfrom requests.adapters import HTTPAdapter, Retryfrom typing_extensions import override
from fsspec import AbstractFileSystemfrom fsspec.spec import AbstractBufferedFile
class DatabricksException(Exception): """ Helper class for exceptions raised in this module. """
def __init__(self, error_code, message, details=None): """Create a new DatabricksException""" super().__init__(message)
self.error_code = error_code self.message = message self.details = details
class DatabricksFileSystem(AbstractFileSystem): """ Get access to the Databricks filesystem implementation over HTTP. Can be used inside and outside of a databricks cluster. """
def __init__(self, instance, token, **kwargs): """ Create a new DatabricksFileSystem.
Parameters ---------- instance: str The instance URL of the databricks cluster. For example for an Azure databricks cluster, this has the form adb-<some-number>.<two digits>.azuredatabricks.net. token: str Your personal token. Find out more here: https://docs.databricks.com/dev-tools/api/latest/authentication.html """ self.instance = instance self.token = token self.session = requests.Session() self.retries = Retry( total=10, backoff_factor=0.05, status_forcelist=[408, 429, 500, 502, 503, 504], )
self.session.mount("https://", HTTPAdapter(max_retries=self.retries)) self.session.headers.update({"Authorization": f"Bearer {self.token}"})
super().__init__(**kwargs)
@override def _ls_from_cache(self, path) -> list[dict[str, str | int]] | None: """Check cache for listing
Returns listing, if found (may be empty list for a directory that exists but contains nothing), None if not in cache. """ self.dircache.pop(path.rstrip("/"), None)
parent = self._parent(path) if parent in self.dircache: for entry in self.dircache[parent]: if entry["name"] == path.rstrip("/"): if entry["type"] != "directory": return [entry] return [] raise FileNotFoundError(path)
def ls(self, path, detail=True, **kwargs): """ List the contents of the given path.
Parameters ---------- path: str Absolute path detail: bool Return not only the list of filenames, but also additional information on file sizes and types. """ try: out = self._ls_from_cache(path) except FileNotFoundError: # This happens if the `path`'s parent was cached, but `path` is not # there. This suggests that `path` is new since the parent was # cached. Attempt to invalidate parent's cache before continuing. self.dircache.pop(self._parent(path), None) out = None
if not out: try: r = self._send_to_api( method="get", endpoint="list", json={"path": path} ) except DatabricksException as e: if e.error_code == "RESOURCE_DOES_NOT_EXIST": raise FileNotFoundError(e.message) from e
raise files = r.get("files", []) out = [ { "name": o["path"], "type": "directory" if o["is_dir"] else "file", "size": o["file_size"], } for o in files ] self.dircache[path] = out
if detail: return out return [o["name"] for o in out]
def makedirs(self, path, exist_ok=True): """ Create a given absolute path and all of its parents.
Parameters ---------- path: str Absolute path to create exist_ok: bool If false, checks if the folder exists before creating it (and raises an Exception if this is the case) """ if not exist_ok: try: # If the following succeeds, the path is already present self._send_to_api( method="get", endpoint="get-status", json={"path": path} ) raise FileExistsError(f"Path {path} already exists") except DatabricksException as e: if e.error_code == "RESOURCE_DOES_NOT_EXIST": pass
try: self._send_to_api(method="post", endpoint="mkdirs", json={"path": path}) except DatabricksException as e: if e.error_code == "RESOURCE_ALREADY_EXISTS": raise FileExistsError(e.message) from e
raise self.invalidate_cache(self._parent(path))
def mkdir(self, path, create_parents=True, **kwargs): """ Create a given absolute path and all of its parents.
Parameters ---------- path: str Absolute path to create create_parents: bool Whether to create all parents or not. "False" is not implemented so far. """ if not create_parents: raise NotImplementedError
self.mkdirs(path, **kwargs)
def rm(self, path, recursive=False, **kwargs): """ Remove the file or folder at the given absolute path.
Parameters ---------- path: str Absolute path what to remove recursive: bool Recursively delete all files in a folder. """ while True: try: self._send_to_api( method="post", endpoint="delete", json={"path": path, "recursive": recursive}, ) except DatabricksException as e: # Not everything was deleted so far; retry without recursion. if e.error_code == "PARTIAL_DELETE": continue elif e.error_code == "IO_ERROR": # Using the same exception as the os module would use here raise OSError(e.message) from e
raise break self.invalidate_cache(self._parent(path))
def mv( self, source_path, destination_path, recursive=False, maxdepth=None, **kwargs ): """ Move a source to a destination path.
A note from the original [databricks API manual] (https://docs.databricks.com/dev-tools/api/latest/dbfs.html#move).
When moving a large number of files the API call will time out after approximately 60s, potentially resulting in partially moved data. Therefore, for operations that move more than 10k files, we strongly discourage using the DBFS REST API.
Parameters ---------- source_path: str From where to move (absolute path) destination_path: str To where to move (absolute path) recursive: bool Not implemented to far. maxdepth: Not implemented to far. """ if recursive: raise NotImplementedError if maxdepth: raise NotImplementedError
try: self._send_to_api( method="post", endpoint="move", json={"source_path": source_path, "destination_path": destination_path}, ) except DatabricksException as e: if e.error_code == "RESOURCE_DOES_NOT_EXIST": raise FileNotFoundError(e.message) from e elif e.error_code == "RESOURCE_ALREADY_EXISTS": raise FileExistsError(e.message) from e
raise self.invalidate_cache(self._parent(source_path)) self.invalidate_cache(self._parent(destination_path))
def _open(self, path, mode="rb", block_size="default", **kwargs): """ Overwrite the base class method to make sure to create a DBFile. All arguments are copied from the base method.
Only the default blocksize is allowed. """ return DatabricksFile(self, path, mode=mode, block_size=block_size, **kwargs)
def _send_to_api(self, method, endpoint, json): """ Send the given json to the DBFS API using a get or post request (specified by the argument `method`).
Parameters ---------- method: str Which http method to use for communication; "get" or "post". endpoint: str Where to send the request to (last part of the API URL) json: dict Dictionary of information to send """ if method == "post": session_call = self.session.post elif method == "get": session_call = self.session.get else: raise ValueError(f"Do not understand method {method}")
url = urllib.parse.urljoin(f"https://{self.instance}/api/2.0/dbfs/", endpoint)
r = session_call(url, json=json)
# The DBFS API will return a json, also in case of an exception. # We want to preserve this information as good as possible. try: r.raise_for_status() except requests.HTTPError as e: # try to extract json error message # if that fails, fall back to the original exception try: exception_json = e.response.json() except Exception: raise e from None
raise DatabricksException(**exception_json) from e
return r.json()
def _create_handle(self, path, overwrite=True): """ Internal function to create a handle, which can be used to write blocks of a file to DBFS. A handle has a unique identifier which needs to be passed whenever written during this transaction. The handle is active for 10 minutes - after that a new write transaction needs to be created. Make sure to close the handle after you are finished.
Parameters ---------- path: str Absolute path for this file. overwrite: bool If a file already exist at this location, either overwrite it or raise an exception. """ try: r = self._send_to_api( method="post", endpoint="create", json={"path": path, "overwrite": overwrite}, ) return r["handle"] except DatabricksException as e: if e.error_code == "RESOURCE_ALREADY_EXISTS": raise FileExistsError(e.message) from e
raise
def _close_handle(self, handle): """ Close a handle, which was opened by :func:`_create_handle`.
Parameters ---------- handle: str Which handle to close. """ try: self._send_to_api(method="post", endpoint="close", json={"handle": handle}) except DatabricksException as e: if e.error_code == "RESOURCE_DOES_NOT_EXIST": raise FileNotFoundError(e.message) from e
raise
def _add_data(self, handle, data): """ Upload data to an already opened file handle (opened by :func:`_create_handle`). The maximal allowed data size is 1MB after conversion to base64. Remember to close the handle when you are finished.
Parameters ---------- handle: str Which handle to upload data to. data: bytes Block of data to add to the handle. """ data = base64.b64encode(data).decode() try: self._send_to_api( method="post", endpoint="add-block", json={"handle": handle, "data": data}, ) except DatabricksException as e: if e.error_code == "RESOURCE_DOES_NOT_EXIST": raise FileNotFoundError(e.message) from e elif e.error_code == "MAX_BLOCK_SIZE_EXCEEDED": raise ValueError(e.message) from e
raise
def _get_data(self, path, start, end): """ Download data in bytes from a given absolute path in a block from [start, start+length]. The maximum number of allowed bytes to read is 1MB.
Parameters ---------- path: str Absolute path to download data from start: int Start position of the block end: int End position of the block """ try: r = self._send_to_api( method="get", endpoint="read", json={"path": path, "offset": start, "length": end - start}, ) return base64.b64decode(r["data"]) except DatabricksException as e: if e.error_code == "RESOURCE_DOES_NOT_EXIST": raise FileNotFoundError(e.message) from e elif e.error_code in ["INVALID_PARAMETER_VALUE", "MAX_READ_SIZE_EXCEEDED"]: raise ValueError(e.message) from e
raise
def invalidate_cache(self, path=None): if path is None: self.dircache.clear() else: self.dircache.pop(path, None) super().invalidate_cache(path)
class DatabricksFile(AbstractBufferedFile): """ Helper class for files referenced in the DatabricksFileSystem. """
DEFAULT_BLOCK_SIZE = 1 * 2**20 # only allowed block size
def __init__( self, fs, path, mode="rb", block_size="default", autocommit=True, cache_type="readahead", cache_options=None, **kwargs, ): """ Create a new instance of the DatabricksFile.
The blocksize needs to be the default one. """ if block_size is None or block_size == "default": block_size = self.DEFAULT_BLOCK_SIZE
if block_size != self.DEFAULT_BLOCK_SIZE: raise ValueError( f"Only the default block size is allowed, not {block_size}" )
super().__init__( fs, path, mode=mode, block_size=block_size, autocommit=autocommit, cache_type=cache_type, cache_options=cache_options or {}, **kwargs, )
def _initiate_upload(self): """Internal function to start a file upload""" self.handle = self.fs._create_handle(self.path, overwrite="x" not in self.mode)
def _upload_chunk(self, final=False): """Internal function to add a chunk of data to a started upload""" self.buffer.seek(0) data = self.buffer.getvalue()
data_chunks = [ data[start:end] for start, end in self._to_sized_blocks(len(data)) ]
for data_chunk in data_chunks: self.fs._add_data(handle=self.handle, data=data_chunk)
if final: self.fs._close_handle(handle=self.handle) return True
def _fetch_range(self, start, end): """Internal function to download a block of data""" return_buffer = b"" length = end - start for chunk_start, chunk_end in self._to_sized_blocks(length, start): return_buffer += self.fs._get_data( path=self.path, start=chunk_start, end=chunk_end )
return return_buffer
def _to_sized_blocks(self, length, start=0): """Helper function to split a range from 0 to total_length into blocksizes""" end = start + length for data_chunk in range(start, end, self.blocksize): data_start = data_chunk data_end = min(end, data_chunk + self.blocksize) yield data_start, data_end123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492from .. import filesystemfrom ..asyn import AsyncFileSystemfrom ..utils import stringify_pathfrom .chained import ChainedFileSystemfrom .local import LocalFileSystem
def _escapes_root(path): """Whether a relative path would resolve above its root via ".." segments.""" depth = 0 for part in path.split("/"): if part == "..": depth -= 1 if depth < 0: return True elif part and part != ".": depth += 1 return False
class DirFileSystem(AsyncFileSystem, ChainedFileSystem): """Directory prefix filesystem
The DirFileSystem is a filesystem-wrapper. It assumes every path it is dealing with is relative to the `path`. After performing the necessary paths operation it delegates everything to the wrapped filesystem. """
protocol = "dir"
def __init__( self, path=None, fs=None, fo=None, target_protocol=None, target_options=None, **storage_options, ): """ Parameters ---------- path: str Path to the directory. fs: AbstractFileSystem An instantiated filesystem to wrap. target_protocol, target_options: if fs is none, construct it from these fo: str Alternate for path; do not provide both """ super().__init__(**storage_options) if fs is None: fs = filesystem(protocol=target_protocol, **(target_options or {})) path = path or fo
if self.asynchronous and not fs.async_impl: raise ValueError("can't use asynchronous with non-async fs")
if fs.async_impl and self.asynchronous != fs.asynchronous: raise ValueError("both dirfs and fs should be in the same sync/async mode")
self.path = fs._strip_protocol(path) self.fs = fs self.async_impl = fs.async_impl
def _join(self, path): path = stringify_path(path) if isinstance(path, str): if not self.path: return path if not path: return self.path # a trailing slash requests "copy the contents" in bulk # operations (docs/source/copying.rst), so preserve it across the # join even though _strip_protocol removes it suffix = "/" if path.endswith("/") else "" path = self._strip_protocol(path) # ".." only navigates above the root on filesystems that resolve it # against a real directory tree; on object stores it is a literal # path part, so only guard the local case here. if isinstance(self.fs, LocalFileSystem) and _escapes_root(path): raise ValueError( f"path {path!r} escapes the {self.path!r} root of the filesystem" ) joined = self.fs.sep.join((self.path, path)) if suffix and not joined.endswith("/"): joined += "/" return joined if isinstance(path, dict): return {self._join(_path): value for _path, value in path.items()} return [self._join(_path) for _path in path]
def _relpath(self, path): if isinstance(path, str): if not self.path: return path # We need to account for S3FileSystem returning paths that do not # start with a '/' if path == self.path or ( self.path.startswith(self.fs.sep) and path == self.path[1:] ): return "" prefix = self.path + self.fs.sep if self.path.startswith(self.fs.sep) and not path.startswith(self.fs.sep): prefix = prefix[1:] assert path.startswith(prefix) return path[len(prefix) :] return [self._relpath(_path) for _path in path]
def _relpath_detail(self, paths): out = {} for path, info in paths.items(): path = self._relpath(path) info = info.copy() info["name"] = path out[path] = info return out
# Wrappers below
@property def sep(self): return self.fs.sep
@property def local_file(self): return getattr(self.fs, "local_file", False)
async def set_session(self, *args, **kwargs): return await self.fs.set_session(*args, **kwargs)
async def _rm_file(self, path, **kwargs): return await self.fs._rm_file(self._join(path), **kwargs)
def rm_file(self, path, **kwargs): return self.fs.rm_file(self._join(path), **kwargs)
async def _rm(self, path, *args, **kwargs): return await self.fs._rm(self._join(path), *args, **kwargs)
def rm(self, path, *args, **kwargs): return self.fs.rm(self._join(path), *args, **kwargs)
def delete(self, path, recursive=False, maxdepth=None): return self.fs.delete(self._join(path), recursive=recursive, maxdepth=maxdepth)
async def _cp_file(self, path1, path2, **kwargs): return await self.fs._cp_file(self._join(path1), self._join(path2), **kwargs)
def cp_file(self, path1, path2, **kwargs): return self.fs.cp_file(self._join(path1), self._join(path2), **kwargs)
async def _copy( self, path1, path2, *args, **kwargs, ): return await self.fs._copy( self._join(path1), self._join(path2), *args, **kwargs, )
def copy(self, path1, path2, *args, **kwargs): return self.fs.copy( self._join(path1), self._join(path2), *args, **kwargs, )
async def _pipe(self, path, *args, **kwargs): return await self.fs._pipe(self._join(path), *args, **kwargs)
def pipe(self, path, *args, **kwargs): return self.fs.pipe(self._join(path), *args, **kwargs)
async def _pipe_file(self, path, *args, **kwargs): return await self.fs._pipe_file(self._join(path), *args, **kwargs)
def pipe_file(self, path, *args, **kwargs): return self.fs.pipe_file(self._join(path), *args, **kwargs)
def write_text( self, path, value, encoding=None, errors=None, newline=None, **kwargs ): return self.fs.write_text( self._join(path), value, encoding=encoding, errors=errors, newline=newline, **kwargs, )
async def _cat_file(self, path, *args, **kwargs): return await self.fs._cat_file(self._join(path), *args, **kwargs)
def cat_file(self, path, *args, **kwargs): return self.fs.cat_file(self._join(path), *args, **kwargs)
async def _cat(self, path, *args, **kwargs): ret = await self.fs._cat( self._join(path), *args, **kwargs, )
if isinstance(ret, dict): return {self._relpath(key): value for key, value in ret.items()}
return ret
def cat(self, path, *args, **kwargs): ret = self.fs.cat( self._join(path), *args, **kwargs, )
if isinstance(ret, dict): return {self._relpath(key): value for key, value in ret.items()}
return ret
async def _cat_ranges(self, paths, starts, ends, *args, **kwargs): return await self.fs._cat_ranges( self._join(paths), starts, ends, *args, **kwargs )
def cat_ranges(self, paths, starts, ends, *args, **kwargs): return self.fs.cat_ranges(self._join(paths), starts, ends, *args, **kwargs)
async def _put_file(self, lpath, rpath, **kwargs): return await self.fs._put_file(lpath, self._join(rpath), **kwargs)
def put_file(self, lpath, rpath, **kwargs): return self.fs.put_file(lpath, self._join(rpath), **kwargs)
async def _put( self, lpath, rpath, *args, **kwargs, ): return await self.fs._put( lpath, self._join(rpath), *args, **kwargs, )
def put(self, lpath, rpath, *args, **kwargs): return self.fs.put( lpath, self._join(rpath), *args, **kwargs, )
async def _get_file(self, rpath, lpath, **kwargs): return await self.fs._get_file(self._join(rpath), lpath, **kwargs)
def get_file(self, rpath, lpath, **kwargs): return self.fs.get_file(self._join(rpath), lpath, **kwargs)
async def _get(self, rpath, *args, **kwargs): return await self.fs._get(self._join(rpath), *args, **kwargs)
def get(self, rpath, *args, **kwargs): return self.fs.get(self._join(rpath), *args, **kwargs)
async def _isfile(self, path): return await self.fs._isfile(self._join(path))
def isfile(self, path): return self.fs.isfile(self._join(path))
async def _isdir(self, path): return await self.fs._isdir(self._join(path))
def isdir(self, path): return self.fs.isdir(self._join(path))
async def _size(self, path): return await self.fs._size(self._join(path))
def size(self, path): return self.fs.size(self._join(path))
async def _sizes(self, paths): return await self.fs._sizes(self._join(paths))
def sizes(self, paths): return self.fs.sizes(self._join(paths))
def invalidate_cache(self, path=None): # With no path, clear only what is cached under this directory. An # unrooted dirfs joins to "", which means everything on the wrapped fs. self.fs.invalidate_cache(self._join(path or "") or None)
def ukey(self, path): return self.fs.ukey(self._join(path))
def checksum(self, path): return self.fs.checksum(self._join(path))
async def _exists(self, path): return await self.fs._exists(self._join(path))
def exists(self, path): return self.fs.exists(self._join(path))
async def _info(self, path, **kwargs): info = await self.fs._info(self._join(path), **kwargs) info = info.copy() info["name"] = self._relpath(info["name"]) return info
def info(self, path, **kwargs): info = self.fs.info(self._join(path), **kwargs) info = info.copy() info["name"] = self._relpath(info["name"]) return info
async def _ls(self, path, detail=True, **kwargs): ret = (await self.fs._ls(self._join(path), detail=detail, **kwargs)).copy() if detail: out = [] for entry in ret: entry = entry.copy() entry["name"] = self._relpath(entry["name"]) out.append(entry) return out
return self._relpath(ret)
def ls(self, path, detail=True, **kwargs): ret = self.fs.ls(self._join(path), detail=detail, **kwargs).copy() if detail: out = [] for entry in ret: entry = entry.copy() entry["name"] = self._relpath(entry["name"]) out.append(entry) return out
return self._relpath(ret)
def _relpath_walk_entries(self, entries): # with detail=True, walk gives dicts keyed by basename whose infos # still carry the full name in the wrapped filesystem if not isinstance(entries, dict): return entries # Keep the mapping so callers can prune the wrapped walk in place. for name, info in entries.items(): entries[name] = {**info, "name": self._relpath(info["name"])} return entries
async def _walk(self, path, *args, **kwargs): async for root, dirs, files in self.fs._walk(self._join(path), *args, **kwargs): yield ( self._relpath(root), self._relpath_walk_entries(dirs), self._relpath_walk_entries(files), )
def walk(self, path, *args, **kwargs): for root, dirs, files in self.fs.walk(self._join(path), *args, **kwargs): yield ( self._relpath(root), self._relpath_walk_entries(dirs), self._relpath_walk_entries(files), )
async def _glob(self, path, **kwargs): detail = kwargs.get("detail", False) ret = await self.fs._glob(self._join(path), **kwargs) if detail: return self._relpath_detail(ret) return self._relpath(ret)
def glob(self, path, **kwargs): detail = kwargs.get("detail", False) ret = self.fs.glob(self._join(path), **kwargs) if detail: return self._relpath_detail(ret) return self._relpath(ret)
async def _du(self, path, *args, **kwargs): total = kwargs.get("total", True) ret = await self.fs._du(self._join(path), *args, **kwargs) if total: return ret
return {self._relpath(path): size for path, size in ret.items()}
def du(self, path, *args, **kwargs): total = kwargs.get("total", True) ret = self.fs.du(self._join(path), *args, **kwargs) if total: return ret
return {self._relpath(path): size for path, size in ret.items()}
async def _find(self, path, *args, **kwargs): detail = kwargs.get("detail", False) ret = await self.fs._find(self._join(path), *args, **kwargs) if detail: return self._relpath_detail(ret) return self._relpath(ret)
def find(self, path, *args, **kwargs): detail = kwargs.get("detail", False) ret = self.fs.find(self._join(path), *args, **kwargs) if detail: return self._relpath_detail(ret) return self._relpath(ret)
async def _expand_path(self, path, *args, **kwargs): return self._relpath( await self.fs._expand_path(self._join(path), *args, **kwargs) )
def expand_path(self, path, *args, **kwargs): return self._relpath(self.fs.expand_path(self._join(path), *args, **kwargs))
async def _mkdir(self, path, *args, **kwargs): return await self.fs._mkdir(self._join(path), *args, **kwargs)
def mkdir(self, path, *args, **kwargs): return self.fs.mkdir(self._join(path), *args, **kwargs)
async def _makedirs(self, path, *args, **kwargs): return await self.fs._makedirs(self._join(path), *args, **kwargs)
def makedirs(self, path, *args, **kwargs): return self.fs.makedirs(self._join(path), *args, **kwargs)
def rmdir(self, path): return self.fs.rmdir(self._join(path))
def mv(self, path1, path2, **kwargs): return self.fs.mv( self._join(path1), self._join(path2), **kwargs, )
def touch(self, path, **kwargs): return self.fs.touch(self._join(path), **kwargs)
def created(self, path): return self.fs.created(self._join(path))
def modified(self, path): return self.fs.modified(self._join(path))
def sign(self, path, *args, **kwargs): return self.fs.sign(self._join(path), *args, **kwargs)
def __repr__(self): return f"{self.__class__.__qualname__}(path='{self.path}', fs={self.fs})"
def open( self, path, *args, **kwargs, ): return self.fs.open( self._join(path), *args, **kwargs, )
async def open_async( self, path, *args, **kwargs, ): return await self.fs.open_async( self._join(path), *args, **kwargs, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445import osimport sslimport uuidfrom ftplib import FTP, FTP_TLS, Error, error_permfrom typing import Any
from ..spec import AbstractBufferedFile, AbstractFileSystemfrom ..utils import infer_storage_options, isfilelike
SECURITY_PROTOCOL_MAP = { "tls": ssl.PROTOCOL_TLS, "sslv23": ssl.PROTOCOL_SSLv23,}for protocol in ["TLSv1", "TLSv1_1", "TLSv1_2"]: if hasattr(ssl, f"PROTOCOL_{protocol}"): SECURITY_PROTOCOL_MAP[protocol.lower()] = getattr(ssl, f"PROTOCOL_{protocol}")
class ImplicitFTPTLS(FTP_TLS): """ FTP_TLS subclass that automatically wraps sockets in SSL to support implicit FTPS. """
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._sock = None
@property def sock(self): """Return the socket.""" return self._sock
@sock.setter def sock(self, value): """When modifying the socket, ensure that it is ssl wrapped.""" if value is not None and not isinstance(value, ssl.SSLSocket): value = self.context.wrap_socket(value) self._sock = value
class FTPFileSystem(AbstractFileSystem): """A filesystem over classic FTP"""
root_marker = "/" cachable = False protocol = "ftp"
def __init__( self, host, port=21, username=None, password=None, acct=None, block_size=None, tempdir=None, timeout=30, encoding="utf-8", tls=False, **kwargs, ): """ You can use _get_kwargs_from_urls to get some kwargs from a reasonable FTP url.
Authentication will be anonymous if username/password are not given.
Parameters ---------- host: str The remote server name/ip to connect to port: int Port to connect with username: str or None If authenticating, the user's identifier password: str of None User's password on the server, if using acct: str or None Some servers also need an "account" string for auth block_size: int or None If given, the read-ahead or write buffer size. tempdir: str Directory on remote to put temporary files when in a transaction timeout: int Timeout of the ftp connection in seconds encoding: str Encoding to use for directories and filenames in FTP connection tls: bool or str Enable FTP-TLS for secure connections: - False: Plain FTP (default) - True: Explicit TLS (FTPS with AUTH TLS command) - "tls": Auto-negotiate highest protocol - "tlsv1": TLS v1.0 - "tlsv1_1": TLS v1.1 - "tlsv1_2": TLS v1.2 """ super().__init__(**kwargs) self.host = host self.port = port self.tempdir = tempdir or "/tmp" self.cred = username or "", password or "", acct or "" self.timeout = timeout self.encoding = encoding if block_size is not None: self.blocksize = block_size else: self.blocksize = 2**16 self.tls = tls self._connect()
def _connect(self): security = None if self.tls: if isinstance(self.tls, str): ftp_cls = ImplicitFTPTLS security = SECURITY_PROTOCOL_MAP.get( self.tls, f"Not supported {self.tls} protocol", ) if isinstance(security, str): raise ValueError(security) else: ftp_cls = FTP_TLS else: ftp_cls = FTP self.ftp = ftp_cls(timeout=self.timeout, encoding=self.encoding) if security: self.ftp.ssl_version = security self.ftp.connect(self.host, self.port) self.ftp.login(*self.cred) if isinstance(self.tls, bool) and self.tls: # also on a reconnect, which would otherwise send data in clear self.ftp.prot_p()
@classmethod def _strip_protocol(cls, path): return "/" + infer_storage_options(path)["path"].lstrip("/").rstrip("/")
@staticmethod def _get_kwargs_from_urls(urlpath): out = infer_storage_options(urlpath) out.pop("path", None) out.pop("protocol", None) return out
def ls(self, path, detail=True, **kwargs): path = self._strip_protocol(path) out = [] if path not in self.dircache: try: try: out = [ (fn, details) for (fn, details) in self.ftp.mlsd(path) if fn not in [".", ".."] and details["type"] not in ["pdir", "cdir"] ] except error_perm: out = _mlsd2(self.ftp, path) # Not platform independent for fn, details in out: details["name"] = "/".join( ["" if path == "/" else path, fn.lstrip("/")] ) if details["type"] == "file": details["size"] = int(details["size"]) else: details["size"] = 0 if details["type"] == "dir": details["type"] = "directory" self.dircache[path] = out except Error: try: info = self.info(path) if info["type"] == "file": out = [(path, info)] except (Error, IndexError) as exc: raise FileNotFoundError(path) from exc files = self.dircache.get(path, out) if not detail: return sorted([fn for fn, details in files]) return [details for fn, details in files]
def info(self, path, **kwargs): # implement with direct method path = self._strip_protocol(path) if path == "/": # special case, since this dir has no real entry return {"name": "/", "size": 0, "type": "directory"} files = self.ls(self._parent(path).lstrip("/"), True) try: out = next(f for f in files if f["name"] == path) except StopIteration as exc: raise FileNotFoundError(path) from exc return out
def get_file(self, rpath, lpath, **kwargs): rpath = self._strip_protocol(rpath) if self.isdir(rpath): if not os.path.exists(lpath): os.mkdir(lpath) return if isfilelike(lpath): outfile = lpath else: outfile = open(lpath, "wb")
def cb(x): outfile.write(x)
self.ftp.retrbinary( f"RETR {rpath}", blocksize=self.blocksize, callback=cb, ) if not isfilelike(lpath): outfile.close()
def cat_file(self, path, start=None, end=None, **kwargs): path = self._strip_protocol(path) if end is not None or (start is not None and start < 0): return super().cat_file(path, start, end, **kwargs) out = []
def cb(x): out.append(x)
try: self.ftp.retrbinary( f"RETR {path}", blocksize=self.blocksize, rest=start, callback=cb, ) except (Error, error_perm) as orig_exc: raise FileNotFoundError(path) from orig_exc return b"".join(out)
def _open( self, path, mode="rb", block_size=None, cache_options=None, autocommit=True, **kwargs, ): path = self._strip_protocol(path) block_size = block_size or self.blocksize return FTPFile( self, path, mode=mode, block_size=block_size, tempdir=self.tempdir, autocommit=autocommit, cache_options=cache_options, )
def _rm(self, path): path = self._strip_protocol(path) self.ftp.delete(path) self.invalidate_cache(self._parent(path))
def rm(self, path, recursive=False, maxdepth=None): paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) for p in reversed(paths): if self.isfile(p): self.rm_file(p) else: self.rmdir(p)
def mkdir(self, path: str, create_parents: bool = True, **kwargs: Any) -> None: path = self._strip_protocol(path) parent = self._parent(path) if parent != self.root_marker and not self.exists(parent) and create_parents: self.mkdir(parent, create_parents=create_parents)
self.ftp.mkd(path) self.invalidate_cache(self._parent(path))
def makedirs(self, path: str, exist_ok: bool = False) -> None: path = self._strip_protocol(path) if self.exists(path): # NB: "/" does not "exist" as it has no directory entry if not exist_ok: raise FileExistsError(f"{path} exists without `exist_ok`") # exists_ok=True -> no-op else: self.mkdir(path, create_parents=True)
def rmdir(self, path): path = self._strip_protocol(path) self.ftp.rmd(path) self.invalidate_cache(self._parent(path))
def mv(self, path1, path2, **kwargs): path1 = self._strip_protocol(path1) path2 = self._strip_protocol(path2) self.ftp.rename(path1, path2) self.invalidate_cache(self._parent(path1)) self.invalidate_cache(self._parent(path2))
def __del__(self): self.ftp.close()
def invalidate_cache(self, path=None): if path is None: self.dircache.clear() else: self.dircache.pop(path, None) super().invalidate_cache(path)
class TransferDone(Exception): """Internal exception to break out of transfer"""
pass
class FTPFile(AbstractBufferedFile): """Interact with a remote FTP file with read/write buffering"""
def __init__( self, fs, path, mode="rb", block_size="default", autocommit=True, cache_type="readahead", cache_options=None, **kwargs, ): super().__init__( fs, path, mode=mode, block_size=block_size, autocommit=autocommit, cache_type=cache_type, cache_options=cache_options, **kwargs, ) if not autocommit: self.target = self.path self.path = "/".join([kwargs["tempdir"], str(uuid.uuid4())])
def commit(self): self.fs.mv(self.path, self.target)
def discard(self): self.fs.rm(self.path)
def _fetch_range(self, start, end): """Get bytes between given byte limits
Implemented by raising an exception in the fetch callback when the number of bytes received reaches the requested amount.
Will fail if the server does not respect the REST command on retrieve requests. """ out = [] total = [0]
def callback(x): total[0] += len(x) if total[0] > end - start: out.append(x[: (end - start) - total[0]]) if end < self.size: raise TransferDone else: out.append(x)
if total[0] == end - start and end < self.size: raise TransferDone
try: self.fs.ftp.retrbinary( f"RETR {self.path}", blocksize=self.blocksize, rest=start, callback=callback, ) except TransferDone: try: # stop transfer, we got enough bytes for this block self.fs.ftp.abort() self.fs.ftp.getmultiline() except Error: self.fs._connect()
return b"".join(out)
def _upload_chunk(self, final=False): self.buffer.seek(0) self.fs.ftp.storbinary( f"STOR {self.path}", self.buffer, blocksize=self.blocksize, rest=self.offset ) return True
def _mlsd2(ftp, path="."): """ Fall back to using `dir` instead of `mlsd` if not supported.
This parses a Linux style `ls -l` response to `dir`, but the response may be platform dependent.
Parameters ---------- ftp: ftplib.FTP path: str Expects to be given path, but defaults to ".". """ lines = [] minfo = [] ftp.dir(path, lines.append) for line in lines: split_line = line.split(maxsplit=8) if len(split_line) < 9: continue name = split_line[8] unix_mode = split_line[0] if unix_mode[0] == "l" and " -> " in name: # Symbolic link: "<name> -> <target>"; keep only the link name. name = name.split(" -> ", 1)[0] this = ( name, { "modify": " ".join(split_line[5:8]), "unix.owner": split_line[2], "unix.group": split_line[3], "unix.mode": unix_mode, "size": split_line[4], }, ) if this[1]["unix.mode"][0] == "d": this[1]["type"] = "dir" else: this[1]["type"] = "file" minfo.append(this) return minfo123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241import requests
from ..spec import AbstractFileSystemfrom ..utils import infer_storage_optionsfrom .memory import MemoryFile
class GistFileSystem(AbstractFileSystem): """ Interface to files in a single GitHub Gist.
Provides read-only access to a gist's files. Gists do not contain subdirectories, so file listing is straightforward.
Parameters ---------- gist_id: str The ID of the gist you want to access (the long hex value from the URL). filenames: list[str] (optional) If provided, only make a file system representing these files, and do not fetch the list of all files for this gist. sha: str (optional) If provided, fetch a particular revision of the gist. If omitted, the latest revision is used. username: str (optional) GitHub username for authentication. token: str (optional) GitHub personal access token (required if username is given), or. timeout: (float, float) or float, optional Connect and read timeouts for requests (default 60s each). kwargs: dict Stored on `self.request_kw` and passed to `requests.get` when fetching Gist metadata or reading ("opening") a file. """
protocol = "gist" gist_url = "https://api.github.com/gists/{gist_id}" gist_rev_url = "https://api.github.com/gists/{gist_id}/{sha}"
def __init__( self, gist_id, filenames=None, sha=None, username=None, token=None, timeout=None, **kwargs, ): super().__init__() self.gist_id = gist_id self.filenames = filenames self.sha = sha # revision of the gist (optional) if username is not None and token is None: raise ValueError("User auth requires a token") self.username = username self.token = token self.request_kw = kwargs # Default timeouts to 60s connect/read if none provided self.timeout = timeout if timeout is not None else (60, 60)
# We use a single-level "directory" cache, because a gist is essentially flat self.dircache[""] = self._fetch_file_list()
@property def kw(self): """Auth parameters passed to 'requests' if we have username/token.""" kw = { "headers": { "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", } } kw.update(self.request_kw) if self.username and self.token: kw["auth"] = (self.username, self.token) elif self.token: kw["headers"]["Authorization"] = f"Bearer {self.token}" return kw
def _fetch_gist_metadata(self): """ Fetch the JSON metadata for this gist (possibly for a specific revision). """ if self.sha: url = self.gist_rev_url.format(gist_id=self.gist_id, sha=self.sha) else: url = self.gist_url.format(gist_id=self.gist_id)
r = requests.get(url, timeout=self.timeout, **self.kw) if r.status_code == 404: raise FileNotFoundError( f"Gist not found: {self.gist_id}@{self.sha or 'latest'}" ) r.raise_for_status() return r.json()
def _fetch_file_list(self): """ Returns a list of dicts describing each file in the gist. These get stored in self.dircache[""]. """ meta = self._fetch_gist_metadata() if self.filenames: available_files = meta.get("files", {}) files = {} for fn in self.filenames: if fn not in available_files: raise FileNotFoundError(fn) files[fn] = available_files[fn] else: files = meta.get("files", {})
out = [] for fname, finfo in files.items(): if finfo is None: # Occasionally GitHub returns a file entry with null if it was deleted continue # Build a directory entry out.append( { "name": fname, # file's name "type": "file", # gists have no subdirectories "size": finfo.get("size", 0), # file size in bytes "raw_url": finfo.get("raw_url"), } ) return out
@classmethod def _strip_protocol(cls, path): """ Remove 'gist://' from the path, if present. """ # The default infer_storage_options can handle gist://username:token@id/file # or gist://id/file, but let's ensure we handle a normal usage too. # We'll just strip the protocol prefix if it exists. path = infer_storage_options(path).get("path", path) return path.lstrip("/")
@staticmethod def _get_kwargs_from_urls(path): """ Parse 'gist://' style URLs into GistFileSystem constructor kwargs. For example: gist://:TOKEN@<gist_id>/file.txt gist://username:TOKEN@<gist_id>/file.txt """ so = infer_storage_options(path) out = {} if "username" in so and so["username"]: out["username"] = so["username"] if "password" in so and so["password"]: out["token"] = so["password"] if "host" in so and so["host"]: # We interpret 'host' as the gist ID out["gist_id"] = so["host"]
# Extract SHA and filename from path if "path" in so and so["path"]: path_parts = so["path"].rsplit("/", 2)[-2:] if len(path_parts) == 2: if path_parts[0]: # SHA present out["sha"] = path_parts[0] if path_parts[1]: # filename also present out["filenames"] = [path_parts[1]]
return out
def ls(self, path="", detail=False, **kwargs): """ List files in the gist. Gists are single-level, so any 'path' is basically the filename, or empty for all files.
Parameters ---------- path : str, optional The filename to list. If empty, returns all files in the gist. detail : bool, default False If True, return a list of dicts; if False, return a list of filenames. """ path = self._strip_protocol(path or "") # If path is empty, return all if path == "": results = self.dircache[""] else: # We want just the single file with this name all_files = self.dircache[""] results = [f for f in all_files if f["name"] == path] if not results: raise FileNotFoundError(path) if detail: return results else: return sorted(f["name"] for f in results)
def _open(self, path, mode="rb", block_size=None, **kwargs): """ Read a single file from the gist. """ if mode != "rb": raise NotImplementedError("GitHub Gist FS is read-only (no write).")
path = self._strip_protocol(path) # Find the file entry in our dircache matches = [f for f in self.dircache[""] if f["name"] == path] if not matches: raise FileNotFoundError(path) finfo = matches[0]
raw_url = finfo.get("raw_url") if not raw_url: raise FileNotFoundError(f"No raw_url for file: {path}")
r = requests.get(raw_url, timeout=self.timeout, **self.kw) if r.status_code == 404: raise FileNotFoundError(path) r.raise_for_status() return MemoryFile(path, None, r.content)
def cat(self, path, recursive=False, on_error="raise", **kwargs): """ Return {path: contents} for the given file or files. If 'recursive' is True, and path is empty, returns all files in the gist. """ paths = self.expand_path(path, recursive=recursive) out = {} for p in paths: try: with self.open(p, "rb") as f: out[p] = f.read() except FileNotFoundError as e: if on_error == "raise": raise e elif on_error == "omit": pass # skip else: out[p] = e if len(paths) == 1 and paths[0] == path: return out[path] return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123import os
import pygit2
from fsspec.spec import AbstractFileSystem
from .memory import MemoryFile
class GitFileSystem(AbstractFileSystem): """Browse the files of a local git repo at any hash/tag/branch
(experimental backend) """
root_marker = "" cachable = True
def __init__(self, path=None, fo=None, ref=None, **kwargs): """
Parameters ---------- path: str (optional) Local location of the repo (uses current directory if not given). May be deprecated in favour of ``fo``. When used with a higher level function such as fsspec.open(), may be of the form "git://[path-to-repo[:]][ref@]path/to/file" (but the actual file path should not contain "@" or ":"). For example, "git://C:/repo:master@file" selects a branch in a Windows repository, and "git://C:/repo:file" uses the default ref. fo: str (optional) Same as ``path``, but passed as part of a chained URL. This one takes precedence if both are given. ref: str (optional) Reference to work with, could be a hash, tag or branch name. Defaults to current working tree. Note that ``ls`` and ``open`` also take hash, so this becomes the default for those operations kwargs """ super().__init__(**kwargs) self.repo = pygit2.Repository(fo or path or os.getcwd()) self.ref = ref or "master"
@classmethod def _strip_protocol(cls, path): path = super()._strip_protocol(path).lstrip("/") if ":" in path: path = path.rsplit(":", 1)[1] if "@" in path: path = path.split("@", 1)[1] return path.lstrip("/")
def _path_to_object(self, path, ref): comm, ref = self.repo.resolve_refish(ref or self.ref) parts = path.split("/") tree = comm.tree for part in parts: if not part: continue if not isinstance(tree, pygit2.Tree) or part not in tree: raise FileNotFoundError(path) tree = tree[part] return tree
@staticmethod def _get_kwargs_from_urls(path): path = path.removeprefix("git://") out = {} if ":" in path: out["path"], path = path.rsplit(":", 1) if "@" in path: out["ref"], path = path.split("@", 1) return out
@staticmethod def _object_to_info(obj, path=None): # obj.name and obj.filemode are None for the root tree! is_dir = isinstance(obj, pygit2.Tree) return { "type": "directory" if is_dir else "file", "name": ( "/".join([path, obj.name or ""]).lstrip("/") if path else obj.name ), "hex": str(obj.id), "mode": "100644" if obj.filemode is None else f"{obj.filemode:o}", "size": 0 if is_dir else obj.size, }
def ls(self, path, detail=True, ref=None, **kwargs): path = self._strip_protocol(path).rstrip("/") tree = self._path_to_object(path, ref) if not isinstance(tree, pygit2.Tree): return [self.info(path, ref=ref)] if detail else [path] return [ GitFileSystem._object_to_info(obj, path) if detail else GitFileSystem._object_to_info(obj, path)["name"] for obj in tree ]
def info(self, path, ref=None, **kwargs): path = self._strip_protocol(path).rstrip("/") tree = self._path_to_object(path, ref) info = GitFileSystem._object_to_info(tree) info["name"] = path return info
def ukey(self, path, ref=None): return self.info(path, ref=ref)["hex"]
def _open( self, path, mode="rb", block_size=None, autocommit=True, cache_options=None, ref=None, **kwargs, ): obj = self._path_to_object(path, ref or self.ref) return MemoryFile(data=obj.data)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348import base64import refrom urllib.parse import quote
import requests
from ..spec import AbstractFileSystemfrom ..utils import infer_storage_optionsfrom .memory import MemoryFile
def _github_names(url, timeout, **kwargs): names = [] while url: response = requests.get(url, timeout=timeout, **kwargs) response.raise_for_status() names.extend(item["name"] for item in response.json()) url = response.links.get("next", {}).get("url") return names
class GithubFileSystem(AbstractFileSystem): """Interface to files in github
An instance of this class provides the files residing within a remote github repository. You may specify a point in the repos history, by SHA, branch or tag (default is current master).
For files less than 1 MB in size, file content is returned directly in a MemoryFile. For larger files, or for files tracked by git-lfs, file content is returned as an HTTPFile wrapping the ``download_url`` provided by the GitHub API.
When using fsspec.open, allows URIs of the form:
- "github://path/file", in which case you must specify org, repo and may specify sha in the extra args - 'github://org:repo@/precip/catalog.yml', where the org and repo are part of the URI - 'github://org:repo@sha/precip/catalog.yml', where the sha is also included
``sha`` can be the full or abbreviated hex of the commit you want to fetch from, or a branch or tag name. Pass the unencoded name in the ``sha`` option; it is percent-encoded when constructing GitHub API URLs.
For authorised access, you must provide username and token, which can be made at https://github.com/settings/tokens """
url = "https://api.github.com/repos/{org}/{repo}/git/trees/{sha}" content_url = "https://api.github.com/repos/{org}/{repo}/contents/{path}?ref={sha}" protocol = "github" timeout = (60, 60) # connect, read timeouts
def __init__( self, org, repo, sha=None, username=None, token=None, timeout=None, **kwargs ): super().__init__(**kwargs) self.org = org self.repo = repo if (username is None) ^ (token is None): raise ValueError("Auth required both username and token") self.username = username self.token = token if timeout is not None: self.timeout = timeout if sha is None: # look up default branch (not necessarily "master") u = "https://api.github.com/repos/{org}/{repo}" r = requests.get( u.format(org=org, repo=repo), timeout=self.timeout, **self.kw ) r.raise_for_status() sha = r.json()["default_branch"]
self.root = sha self.ls("") try: from .http import HTTPFileSystem
self.http_fs = HTTPFileSystem(**kwargs) except ImportError: self.http_fs = None
@property def kw(self): if self.username: return {"auth": (self.username, self.token)} return {}
@classmethod def repos(cls, org_or_user, is_org=True): """List repo names for given org or user
This may become the top level of the FS
Parameters ---------- org_or_user: str Name of the github org or user to query is_org: bool (default True) Whether the name is an organisation (True) or user (False)
Returns ------- List of string """ return _github_names( f"https://api.github.com/{['users', 'orgs'][is_org]}/{org_or_user}/repos", timeout=cls.timeout, )
@property def tags(self): """Names of tags in the repo""" return _github_names( f"https://api.github.com/repos/{self.org}/{self.repo}/tags", timeout=self.timeout, **self.kw, )
@property def branches(self): """Names of branches in the repo""" return _github_names( f"https://api.github.com/repos/{self.org}/{self.repo}/branches", timeout=self.timeout, **self.kw, )
@property def refs(self): """Named references, tags and branches""" return {"tags": self.tags, "branches": self.branches}
def ls(self, path, detail=False, sha=None, _sha=None, **kwargs): """List files at given path
Parameters ---------- path: str Location to list, relative to repo root detail: bool If True, returns list of dicts, one per file; if False, returns list of full filenames only sha: str (optional) List at the given point in the repo history, branch or tag name or commit SHA _sha: str (optional) List this specific tree object (used internally to descend into trees) """ path = self._strip_protocol(path) if path == "": _sha = sha or self.root if _sha is None: parts = path.rstrip("/").split("/") so_far = "" _sha = sha or self.root for part in parts: out = self.ls(so_far, True, sha=sha, _sha=_sha) so_far += "/" + part if so_far else part out = [o for o in out if o["name"] == so_far] if not out: raise FileNotFoundError(path) out = out[0] if out["type"] == "file": if detail: return [out] else: return [out["name"]] _sha = out["sha"] if path not in self.dircache or sha not in [self.root, None]: r = requests.get( self.url.format(org=self.org, repo=self.repo, sha=quote(_sha, safe="")), timeout=self.timeout, **self.kw, ) if r.status_code == 404: raise FileNotFoundError(path) r.raise_for_status() types = {"blob": "file", "tree": "directory"} out = [ { "name": path + "/" + f["path"] if path else f["path"], "mode": f["mode"], "type": types[f["type"]], "size": f.get("size", 0), "sha": f["sha"], } for f in r.json()["tree"] if f["type"] in types ] if sha in [self.root, None]: self.dircache[path] = out else: out = self.dircache[path] if detail: return out else: return sorted([f["name"] for f in out])
def invalidate_cache(self, path=None): self.dircache.clear()
@classmethod def _strip_protocol(cls, path): opts = infer_storage_options(path) if "username" not in opts: return super()._strip_protocol(path) return opts["path"].lstrip("/")
@staticmethod def _get_kwargs_from_urls(path): opts = infer_storage_options(path) if "username" not in opts: return {} out = {"org": opts["username"], "repo": opts["password"]} if opts["host"]: out["sha"] = opts["host"] return out
def _open( self, path, mode="rb", block_size=None, cache_options=None, sha=None, **kwargs, ): if mode != "rb": raise NotImplementedError
# construct a url to hit the GitHub API's repo contents API url = self.content_url.format( org=self.org, repo=self.repo, path=quote(path), sha=quote(sha or self.root, safe=""), )
# make a request to this API, and parse the response as JSON r = requests.get(url, timeout=self.timeout, **self.kw) if r.status_code == 404: raise FileNotFoundError(path) r.raise_for_status() content_json = r.json()
# Inline base64 content may be empty for a zero-byte file. Large files # report encoding="none" and need the download fallback below. if content_json.get("encoding") == "base64": content = base64.b64decode(content_json["content"])
# as long as the content does not start with the string # "version https://git-lfs.github.com/" # then it is probably not a git-lfs pointer and we can just return # the content directly if not content.startswith(b"version https://git-lfs.github.com/"): return MemoryFile(None, None, content)
# we land here if the content was not present in the first response # (regular file over 1MB or git-lfs tracked file) # in this case, we get let the HTTPFileSystem handle the download if self.http_fs is None: raise ImportError( "Please install fsspec[http] to access github files >1 MB " "or git-lfs tracked files." ) return self.http_fs.open( content_json["download_url"], mode=mode, block_size=block_size, cache_options=cache_options, **kwargs, )
def rm(self, path, recursive=False, maxdepth=None, message=None): path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) for p in reversed(path): self.rm_file(p, message=message)
def rm_file(self, path, message=None, **kwargs): """ Remove a file from a specified branch using a given commit message.
Since Github DELETE operation requires a branch name, and we can't reliably determine whether the provided SHA refers to a branch, tag, or commit, we assume it's a branch. If it's not, the user will encounter an error when attempting to retrieve the file SHA or delete the file.
Parameters ---------- path: str The file's location relative to the repository root. message: str, optional The commit message for the deletion. """
if not self.username: raise ValueError("Authentication required")
path = self._strip_protocol(path)
# Attempt to get SHA from cache or Github API sha = self._get_sha_from_cache(path) if not sha: url = self.content_url.format( org=self.org, repo=self.repo, path=quote(path.lstrip("/")), sha=quote(self.root, safe=""), ) r = requests.get(url, timeout=self.timeout, **self.kw) if r.status_code == 404: raise FileNotFoundError(path) r.raise_for_status() sha = r.json()["sha"]
# Delete the file delete_url = self.content_url.format( org=self.org, repo=self.repo, path=quote(path), sha=quote(self.root, safe=""), ) branch = self.root data = { "message": message or f"Delete {path}", "sha": sha, **({"branch": branch} if branch else {}), }
r = requests.delete(delete_url, json=data, timeout=self.timeout, **self.kw) error_message = r.json().get("message", "") if re.search(r"Branch .+ not found", error_message): error = "Remove only works when the filesystem is initialised from a branch or default (None)" raise ValueError(error) r.raise_for_status()
self.invalidate_cache(path)
def _get_sha_from_cache(self, path): for entries in self.dircache.values(): for entry in entries: entry_path = entry.get("name") if entry_path and entry_path == path and "sha" in entry: return entry["sha"] return None1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069import asyncioimport ioimport loggingimport randomimport reimport weakreffrom copy import copyfrom urllib.parse import urlparse
import aiohttpimport yarl
from fsspec.asyn import AbstractAsyncStreamedFile, AsyncFileSystem, sync, sync_wrapperfrom fsspec.callbacks import DEFAULT_CALLBACKfrom fsspec.exceptions import FSTimeoutErrorfrom fsspec.spec import AbstractBufferedFilefrom fsspec.utils import ( DEFAULT_BLOCK_SIZE, glob_translate, isfilelike, nullcontext, range_response_window, response_is_requested_range, tokenize,)
from ..caching import AllBytes
# https://stackoverflow.com/a/15926317/3821154# The attribute scan must stay linear: it stops at the next "<" or ">" and the# whitespace before href is a lookbehind rather than a second quantifier, so a# page cannot make it backtrack cubically (1 KB of whitespace after "<a"# used to stall ls() for seconds, 10 KB for hours).ex = re.compile(r"""<(a|A)\s[^<>]*?(?<=\s)(href|HREF)=["'](?P<url>[^"']+)""")ex2 = re.compile(r"""(?P<url>http[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""")logger = logging.getLogger("fsspec.http")
_RETRYABLE_STATUSES = frozenset({408, 425, 429, 500, 502, 503, 504})# dropped or reset connections, truncated bodies, timeouts_RETRYABLE_EXCEPTIONS = ( aiohttp.ClientConnectionError, aiohttp.ClientPayloadError, asyncio.TimeoutError,)_RETRY_MAX_WAIT = 60.0
def _is_retryable(exc, statuses=_RETRYABLE_STATUSES, exceptions=None): """Whether a failed HTTP read is worth repeating.
A response error is retried when its status is in ``statuses``; any other error is retried when it is an instance of ``exceptions``. The default (None) is ``_RETRYABLE_EXCEPTIONS`` minus SSL failures, which are deterministic. Anything else (including the ``FileNotFoundError``/ ``PermissionError`` a subclass may map 4xx codes to) propagates at once. """ if isinstance(exc, aiohttp.ClientResponseError): return exc.status in statuses if exceptions is None: return isinstance(exc, _RETRYABLE_EXCEPTIONS) and not isinstance( exc, aiohttp.ClientSSLError ) return isinstance(exc, exceptions)
def _retry_after(exc): """Delta-seconds ``Retry-After`` carried by a response error, else None.""" headers = getattr(exc, "headers", None) if not headers: return None try: return max(0.0, float(headers.get("Retry-After"))) except (TypeError, ValueError): return None
async def _with_retries(attempt, fs, label): """Await ``attempt()``, repeating it on transient failures.
``attempt`` is a zero-argument coroutine function covering the whole request *and* body read, so a connection dropped mid-body counts as a failure too. The policy comes from the ``retries``, ``retry_wait``, ``retry_statuses`` and ``retry_exceptions`` attributes of ``fs``. A ``Retry-After`` header is honoured when present; otherwise the wait doubles from ``retry_wait`` on each retry, jittered. Either way the wait is capped at ``_RETRY_MAX_WAIT`` seconds. Non-retryable errors and the final failure propagate unchanged. """ retries = fs.retries for n in range(retries + 1): try: return await attempt() except Exception as exc: if n >= retries or not _is_retryable( exc, fs.retry_statuses, fs.retry_exceptions ): raise delay = _retry_after(exc) if delay is None: delay = fs.retry_wait * 2**n * (0.5 + random.random()) delay = min(_RETRY_MAX_WAIT, delay) logger.warning( "%s: attempt %d/%d failed (%r); retrying in %.1fs", label, n + 1, retries + 1, exc, delay, ) await asyncio.sleep(delay)
async def get_client(**kwargs): return aiohttp.ClientSession(**kwargs)
class HTTPFileSystem(AsyncFileSystem): """ Simple File-System for fetching data via HTTP(S)
``ls()`` is implemented by loading the parent page and doing a regex match on the result. If simple_link=True, anything of the form "http(s)://server.com/stuff?thing=other"; otherwise only links within HTML href tags will be used.
URLs are passed unfiltered to aiohttp, so all addresses are accessible. Where URLs are supplied by a user, the calling application may wish to filter to prevent scanning. """
protocol = ("http", "https") sep = "/"
def __init__( self, simple_links=True, block_size=None, same_scheme=True, size_policy=None, cache_type="bytes", cache_options=None, asynchronous=False, loop=None, client_kwargs=None, get_client=get_client, encoded=False, retries=3, retry_wait=1.0, retry_statuses=None, retry_exceptions=None, **storage_options, ): """ NB: if this is called async, you must await set_client
Parameters ---------- block_size: int Blocks to read bytes; if 0, will default to raw requests file-like objects instead of HTTPFile instances simple_links: bool If True, will consider both HTML <a> tags and anything that looks like a URL; if False, will consider only the former. same_scheme: True When doing ls/glob, if this is True, only consider paths that have http/https matching the input URLs. size_policy: this argument is deprecated client_kwargs: dict Passed to aiohttp.ClientSession, see https://docs.aiohttp.org/en/stable/client_reference.html For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}`` get_client: Callable[..., aiohttp.ClientSession] A callable, which takes keyword arguments and constructs an aiohttp.ClientSession. Its state will be managed by the HTTPFileSystem class. retries: int How many times a transient failure of a read (see below) is retried in ``cat_file``, ``HTTPFile`` block reads and the ``info`` lookup behind ``open``; 0 disables retries. retry_wait: float Seconds to wait before the first retry; doubled on each further retry, with jitter. A ``Retry-After`` header sent by the server takes precedence. Either wait is capped at 60 s. retry_statuses: container of int or None HTTP status codes of a failed read that are retried; default (None) is 408, 425, 429, 500, 502, 503 and 504. retry_exceptions: exception class, tuple of classes or None Errors other than a response status that are retried; default (None) is dropped or reset connections (except SSL failures), truncated bodies and timeouts. storage_options: key-value Any other parameters passed on to requests cache_type, cache_options: defaults used in open() """ super().__init__(self, asynchronous=asynchronous, loop=loop, **storage_options) self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE self.simple_links = simple_links self.same_schema = same_scheme self.cache_type = cache_type self.cache_options = cache_options self.client_kwargs = client_kwargs or {} self.get_client = get_client self.encoded = encoded if retries < 0: raise ValueError(f"retries must be >= 0, got {retries!r}") if retry_wait < 0: raise ValueError(f"retry_wait must be >= 0, got {retry_wait!r}") self.retries = retries self.retry_wait = retry_wait self.retry_statuses = ( retry_statuses if retry_statuses is not None else _RETRYABLE_STATUSES ) self.retry_exceptions = retry_exceptions self.kwargs = storage_options self._session = None
# Clean caching-related parameters from `storage_options` # before propagating them as `request_options` through `self.kwargs`. # TODO: Maybe rename `self.kwargs` to `self.request_options` to make # it clearer. request_options = copy(storage_options) self.use_listings_cache = request_options.pop("use_listings_cache", False) request_options.pop("listings_expiry_time", None) request_options.pop("max_paths", None) request_options.pop("skip_instance_cache", None) self.kwargs = request_options
@property def fsid(self): return "http"
def encode_url(self, url): return yarl.URL(url, encoded=self.encoded)
@staticmethod def close_session(loop, session): if loop is not None and loop.is_running(): try: sync(loop, session.close, timeout=0.1) return except (TimeoutError, FSTimeoutError, NotImplementedError, RuntimeError): pass connector = getattr(session, "_connector", None) if connector is not None: # close after loop is dead connector._close()
async def set_session(self): if self._session is None: self._session = await self.get_client(loop=self.loop, **self.client_kwargs) if not self.asynchronous: weakref.finalize(self, self.close_session, self.loop, self._session) return self._session
@classmethod def _strip_protocol(cls, path): """For HTTP, we always want to keep the full URL""" return path
@classmethod def _parent(cls, path): # override, since _strip_protocol is different for URLs par = super()._parent(path) if len(par) > 7: # "http://..." return par return ""
async def _ls_real(self, url, detail=True, **kwargs): # ignoring URL-encoded arguments kw = self.kwargs.copy() kw.update(kwargs) logger.debug(url) session = await self.set_session() async with session.get(self.encode_url(url), **kw) as r: self._raise_not_found_for_status(r, url)
if "Content-Type" in r.headers: mimetype = r.headers["Content-Type"].partition(";")[0] else: mimetype = None
if mimetype in ("text/html", None): try: text = await r.text(errors="ignore") if self.simple_links: links = ex2.findall(text) + [u[2] for u in ex.findall(text)] else: links = [u[2] for u in ex.findall(text)] except UnicodeDecodeError: links = [] # binary, not HTML else: links = []
out = set() parts = urlparse(url) for l in links: if isinstance(l, tuple): l = l[1] if l.startswith("/") and len(l) > 1: # absolute URL on this server l = f"{parts.scheme}://{parts.netloc}{l}" if l.startswith("http"): if self.same_schema and l.startswith(url.rstrip("/") + "/"): out.add(l) elif l.replace("https", "http").startswith( url.replace("https", "http").rstrip("/") + "/" ): # allowed to cross http <-> https out.add(l) else: if l not in ["..", "../"]: # Ignore FTP-like "parent" out.add("/".join([url.rstrip("/"), l.lstrip("/")])) if not out and url.endswith("/"): out = await self._ls_real(url.rstrip("/"), detail=False, **kwargs) if detail: return [ { "name": u, "size": None, "type": "directory" if u.endswith("/") else "file", } for u in out ] else: return sorted(out)
async def _ls(self, url, detail=True, **kwargs): if self.use_listings_cache and url in self.dircache: out = self.dircache[url] else: out = await self._ls_real(url, detail=True, **kwargs) self.dircache[url] = out if detail: return out return sorted(entry["name"] for entry in out)
ls = sync_wrapper(_ls)
def _raise_not_found_for_status(self, response, url): """ Raises FileNotFoundError for 404s, otherwise uses raise_for_status. """ if response.status == 404: raise FileNotFoundError(url) response.raise_for_status()
async def _cat_file(self, url, start=None, end=None, **kwargs): kw = self.kwargs.copy() kw.update(kwargs) logger.debug(url)
ranged = start is not None or end is not None if ranged: if start == end or (start is None and end == 0): return b"" headers = kw.pop("headers", {}).copy()
headers["Range"] = await self._process_limits(url, start, end) kw["headers"] = headers session = await self.set_session()
async def _once(): async with session.get(self.encode_url(url), **kw) as r: out = await r.read() self._raise_not_found_for_status(r, url) # a server that ignores the Range header replies with the whole # file, which is not the window the caller asked for return ( range_response_window(out, r.status, r.headers, start, end) if ranged else out )
return await _with_retries(_once, self, url)
async def _get_file( self, rpath, lpath, chunk_size=5 * 2**20, callback=DEFAULT_CALLBACK, **kwargs ): kw = self.kwargs.copy() kw.update(kwargs) logger.debug(rpath) session = await self.set_session() async with session.get(self.encode_url(rpath), **kw) as r: try: size = int(r.headers["content-length"]) except (ValueError, KeyError): size = None
callback.set_size(size) self._raise_not_found_for_status(r, rpath) if isfilelike(lpath): outfile = lpath else: outfile = open(lpath, "wb") # noqa: ASYNC230
try: chunk = True while chunk: chunk = await r.content.read(chunk_size) outfile.write(chunk) callback.relative_update(len(chunk)) finally: if not isfilelike(lpath): outfile.close()
async def _put_file( self, lpath, rpath, chunk_size=5 * 2**20, callback=DEFAULT_CALLBACK, method="post", mode="overwrite", **kwargs, ): if mode != "overwrite": raise NotImplementedError("Exclusive write")
async def gen_chunks(): # Support passing arbitrary file-like objects # and use them instead of streams. if isinstance(lpath, io.IOBase): context = nullcontext(lpath) use_seek = False # might not support seeking else: context = open(lpath, "rb") # noqa: ASYNC230 use_seek = True
with context as f: if use_seek: callback.set_size(f.seek(0, 2)) f.seek(0) else: callback.set_size(getattr(f, "size", None))
chunk = f.read(chunk_size) while chunk: yield chunk callback.relative_update(len(chunk)) chunk = f.read(chunk_size)
kw = self.kwargs.copy() kw.update(kwargs) session = await self.set_session()
method = method.lower() if method not in ("post", "put"): raise ValueError( f"method has to be either 'post' or 'put', not: {method!r}" )
meth = getattr(session, method) async with meth(self.encode_url(rpath), data=gen_chunks(), **kw) as resp: self._raise_not_found_for_status(resp, rpath)
async def _exists(self, path, strict=False, **kwargs): kw = self.kwargs.copy() kw.update(kwargs) try: logger.debug(path) session = await self.set_session() r = await session.get(self.encode_url(path), **kw) async with r: if strict: self._raise_not_found_for_status(r, path) return r.status < 400 except FileNotFoundError: return False except aiohttp.ClientError: if strict: raise return False
async def _isfile(self, path, **kwargs): return await self._exists(path, **kwargs)
def _open( self, path, mode="rb", block_size=None, autocommit=None, # XXX: This differs from the base class. cache_type=None, cache_options=None, size=None, **kwargs, ): """Make a file-like object
Parameters ---------- path: str Full URL with protocol mode: string must be "rb" block_size: int or None Bytes to download in one request; use instance value if None. If zero, will return a streaming Requests file-like instance. kwargs: key-value Any other parameters, passed to requests calls """ if mode != "rb": raise NotImplementedError block_size = block_size if block_size is not None else self.block_size kw = self.kwargs.copy() kw["asynchronous"] = self.asynchronous kw.update(kwargs) info = {} size = size or info.update(self.info(path, **kwargs)) or info["size"] session = sync(self.loop, self.set_session) if block_size and size and info.get("partial", True): return HTTPFile( self, path, session=session, block_size=block_size, mode=mode, size=size, cache_type=cache_type or self.cache_type, cache_options=cache_options or self.cache_options, loop=self.loop, **kw, ) else: return HTTPStreamFile( self, path, mode=mode, loop=self.loop, session=session, **kw, )
async def open_async(self, path, mode="rb", size=None, **kwargs): session = await self.set_session() if size is None: try: size = (await self._info(path, **kwargs))["size"] except FileNotFoundError: pass return AsyncStreamFile( self, path, loop=self.loop, session=session, size=size, **kwargs, )
def ukey(self, url): """Unique identifier; assume HTTP files are static, unchanging""" return tokenize(url, self.kwargs, self.protocol)
async def _info(self, url, **kwargs): """Get info of URL
Tries to access location via HEAD, and then GET methods, but does not fetch the data.
It is possible that the server does not supply any size information, in which case size will be given as None (and certain operations on the corresponding file will not work). """ info = {} session = await self.set_session()
async def _once(): # HEAD, then GET if that gave no size or failed for any reason # (many servers mishandle HEAD); only a GET failure counts as a # failed attempt. for policy in ["head", "get"]: try: info.update( await _file_info( self.encode_url(url), size_policy=policy, session=session, **self.kwargs, **kwargs, ) ) if info.get("size") is not None: break except Exception as exc: if policy == "get": raise logger.debug("", exc_info=exc)
try: await _with_retries(_once, self, url) except Exception as exc: # If get failed, then raise a FileNotFoundError raise FileNotFoundError(url) from exc
return {"name": url, "size": None, **info, "type": "file"}
async def _glob(self, path, maxdepth=None, **kwargs): """ Find files by glob-matching.
This implementation is idntical to the one in AbstractFileSystem, but "?" is not considered as a character for globbing, because it is so common in URLs, often identifying the "query" part. """ if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1") import re
ends_with_slash = path.endswith("/") # _strip_protocol strips trailing slash path = self._strip_protocol(path) append_slash_to_dirname = ends_with_slash or path.endswith(("/**", "/*")) idx_star = path.find("*") if path.find("*") >= 0 else len(path) idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
min_idx = min(idx_star, idx_brace)
detail = kwargs.pop("detail", False)
if not has_magic(path): if await self._exists(path, **kwargs): if not detail: return [path] else: return {path: await self._info(path, **kwargs)} else: if not detail: return [] # glob of non-existent returns empty else: return {} elif "/" in path[:min_idx]: min_idx = path[:min_idx].rindex("/") root = path[: min_idx + 1] depth = path[min_idx + 1 :].count("/") + 1 else: root = "" depth = path[min_idx + 1 :].count("/") + 1
if "**" in path: if maxdepth is not None: idx_double_stars = path.find("**") depth_double_stars = path[idx_double_stars:].count("/") + 1 depth = depth - depth_double_stars + maxdepth else: depth = None
allpaths = await self._find( root, maxdepth=depth, withdirs=True, detail=True, **kwargs )
pattern = glob_translate(path + ("/" if ends_with_slash else "")) pattern = re.compile(pattern)
out = { ( p.rstrip("/") if not append_slash_to_dirname and info["type"] == "directory" and p.endswith("/") else p ): info for p, info in sorted(allpaths.items()) if pattern.match(p.rstrip("/")) }
if detail: return out else: return list(out)
async def _isdir(self, path): # override, since all URLs are (also) files try: return bool(await self._ls(path)) except (FileNotFoundError, ValueError): return False
async def _pipe_file(self, path, value, mode="overwrite", **kwargs): """ Write bytes to a remote file over HTTP.
Parameters ---------- path : str Target URL where the data should be written value : bytes Data to be written mode : str Only 'overwrite' is accepted, allowing an unconditional PUT request. The server determines PUT behavior, so other modes are rejected defensively rather than assuming append or create semantics. **kwargs : dict Additional parameters to pass to the HTTP request """ if mode != "overwrite": raise ValueError( "HTTP pipe_file only accepts mode='overwrite'; " "PUT behavior is server-dependent, so other modes are " "rejected defensively" ) url = self._strip_protocol(path) headers = kwargs.pop("headers", {}) headers["Content-Length"] = str(len(value))
session = await self.set_session()
async with session.put( self.encode_url(url), data=value, headers=headers, **kwargs ) as r: r.raise_for_status()
class HTTPFile(AbstractBufferedFile): """ A file-like object pointing to a remote HTTP(S) resource
Supports only reading, with read-ahead of a predetermined block-size.
In the case that the server does not supply the filesize, only reading of the complete file in one go is supported.
Parameters ---------- url: str Full URL of the remote resource, including the protocol session: aiohttp.ClientSession or None All calls will be made within this session, to avoid restarting connections where the server allows this block_size: int or None The amount of read-ahead to do, in bytes. Default is 5MB, or the value configured for the FileSystem creating this file size: None or int If given, this is the size of the file in bytes, and we don't attempt to call the server to find the value. kwargs: all other key-values are passed to requests calls. """
def __init__( self, fs, url, session=None, block_size=None, mode="rb", cache_type="bytes", cache_options=None, size=None, loop=None, asynchronous=False, **kwargs, ): if mode != "rb": raise NotImplementedError("File mode not supported") self.asynchronous = asynchronous self.loop = loop self.url = url self.session = session self.details = {"name": url, "size": size, "type": "file"} super().__init__( fs=fs, path=url, mode=mode, block_size=block_size, cache_type=cache_type, cache_options=cache_options, **kwargs, )
def read(self, length=-1): """Read bytes from file
Parameters ---------- length: int Read up to this many bytes. If negative, read all content to end of file. If the server has not supplied the filesize, attempting to read only part of the data will raise a ValueError. """ if ( (length < 0 and self.loc == 0) # explicit read all # but not when the size is known and fits into a block anyways and not (self.size is not None and self.size <= self.blocksize) ): self._fetch_all() if self.size is None: if length < 0: self._fetch_all() else: length = min(self.size - self.loc, length) return super().read(length)
async def async_fetch_all(self): """Read whole file in one shot, without caching
This is only called when position is still at zero, and read() is called without a byte-count. """ logger.debug(f"Fetch all for {self}") if not isinstance(self.cache, AllBytes): r = await self.session.get(self.fs.encode_url(self.url), **self.kwargs) async with r: r.raise_for_status() out = await r.read() self.cache = AllBytes( size=len(out), fetcher=None, blocksize=None, data=out ) self.size = len(out)
_fetch_all = sync_wrapper(async_fetch_all)
async def async_fetch_range(self, start, end): """Download a block of data
The expectation is that the server returns only the requested bytes, with HTTP code 206. If this is not the case, we first check the headers, and then stream the output - if the data size is bigger than we requested, an exception is raised. """ logger.debug(f"Fetch range for {self}: {start}-{end}") kwargs = self.kwargs.copy() headers = kwargs.pop("headers", {}).copy() headers["Range"] = f"bytes={start}-{end - 1}" if not any(k.lower() == "accept-encoding" for k in headers) and not any( k.lower() == "accept-encoding" for k in self.session.headers ): # Match the unencoded size from _file_info unless explicitly overridden. headers["Accept-Encoding"] = "identity" logger.debug(f"{self.url} : {headers['Range']}")
async def _once(): r = await self.session.get( self.fs.encode_url(self.url), headers=headers, **kwargs ) async with r: if r.status == 416: if self.size is not None and start < self.size: # CloudFront answers 416 (with an HTML error page as # body) to a range inside the file when range requests # follow each other too quickly; treating it as EOF # would silently truncate the read, retrying with # backoff gets the data. See # https://github.com/fsspec/filesystem_spec/issues/1895 raise aiohttp.ClientPayloadError( f"{headers['Range']} of {self.url} reported " f"unsatisfiable, but the file has {self.size} bytes" ) # range request outside file return b"" r.raise_for_status()
# If the server has handled the range request, it should reply # with status 206 (partial content). But we'll guess that a # suitable Content-Range header or a Content-Length no more # than the requested range also mean we have got the desired # range. response_is_range = response_is_requested_range( r.status, r.headers, start, end )
if response_is_range: # partial content, as expected out = await r.read() if self.size is not None: expected = min(end, self.size) - start if len(out) < expected: # short body with consistent headers: a truncated # block would otherwise be served from the cache raise aiohttp.ClientPayloadError( f"{headers['Range']} of {self.url} returned " f"{len(out)} bytes, expected {expected}" ) elif start > 0: raise ValueError( "The HTTP server doesn't appear to support range " "requests. Only reading this file from the beginning " "is supported. Open with block_size=0 for a streaming " "file interface." ) else: # Response is not a range, but we want the start of the # file, so we can read the required amount anyway. cl = 0 out = [] while True: chunk = await r.content.read(2**20) # data size unknown, let's read until we have enough if chunk: out.append(chunk) cl += len(chunk) if cl > end - start: break else: break out = b"".join(out)[: end - start] return out
return await _with_retries(_once, self.fs, f"{self.url} ({headers['Range']})")
_fetch_range = sync_wrapper(async_fetch_range)
magic_check = re.compile("([*[])")
def has_magic(s): match = magic_check.search(s) return match is not None
class HTTPStreamFile(AbstractBufferedFile): def __init__(self, fs, url, mode="rb", loop=None, session=None, **kwargs): self.asynchronous = kwargs.pop("asynchronous", False) self.url = url self.loop = loop self.session = session if mode != "rb": raise ValueError self.details = {"name": url, "size": None} super().__init__(fs=fs, path=url, mode=mode, cache_type="none", **kwargs)
async def cor(): r = await self.session.get(self.fs.encode_url(url), **kwargs).__aenter__() self.fs._raise_not_found_for_status(r, url) return r
self.r = sync(self.loop, cor) self.loop = fs.loop
def seek(self, loc, whence=0): if loc == 0 and whence == 1: return self.loc if loc == self.loc and whence == 0: return self.loc raise ValueError("Cannot seek streaming HTTP file")
async def _read(self, num=-1): out = await self.r.content.read(num) self.loc += len(out) return out
read = sync_wrapper(_read)
async def _close(self): self.r.close()
def close(self): asyncio.run_coroutine_threadsafe(self._close(), self.loop) super().close()
class AsyncStreamFile(AbstractAsyncStreamedFile): def __init__( self, fs, url, mode="rb", loop=None, session=None, size=None, **kwargs ): self.url = url self.session = session self.r = None if mode != "rb": raise ValueError self.details = {"name": url, "size": None} self.kwargs = kwargs super().__init__(fs=fs, path=url, mode=mode, cache_type="none") self.size = size
def seek(self, loc, whence=0): if loc == 0 and whence == 1: return self.loc if loc == self.loc and whence == 0: return self.loc raise ValueError("Cannot seek streaming HTTP file")
def seekable(self): return False
async def read(self, num=-1): if self.closed: raise ValueError("I/O operation on closed file.") if self.r is None: r = await self.session.get( self.fs.encode_url(self.url), **self.kwargs ).__aenter__() self.fs._raise_not_found_for_status(r, self.url) self.r = r out = await self.r.content.read(num) self.loc += len(out) return out
async def close(self): if self.r is not None: self.r.close() self.r = None await super().close()
async def get_range(session, url, start, end, file=None, **kwargs): # explicit get a range when we know it must be safe kwargs = kwargs.copy() headers = kwargs.pop("headers", {}).copy() headers["Range"] = f"bytes={start}-{end - 1}" r = await session.get(url, headers=headers, **kwargs) r.raise_for_status() async with r: out = await r.read() if file: with open(file, "r+b") as f: # noqa: ASYNC230 f.seek(start) f.write(out) else: return out
async def _file_info(url, session, size_policy="head", **kwargs): """Call HEAD on the server to get details about the file (size/checksum etc.)
Default operation is to explicitly allow redirects and use encoding 'identity' (no compression) to get the true size of the target. """ logger.debug("Retrieve file size for %s", url) kwargs = kwargs.copy() ar = kwargs.pop("allow_redirects", True) head = kwargs.get("headers", {}).copy() head["Accept-Encoding"] = "identity" kwargs["headers"] = head
info = {} if size_policy == "head": r = await session.head(url, allow_redirects=ar, **kwargs) elif size_policy == "get": r = await session.get(url, allow_redirects=ar, **kwargs) else: raise TypeError(f'size_policy must be "head" or "get", got {size_policy}') async with r: r.raise_for_status()
if "Content-Length" in r.headers: # Some servers may choose to ignore Accept-Encoding and return # compressed content, in which case the returned size is unreliable. if "Content-Encoding" not in r.headers or r.headers["Content-Encoding"] in [ "identity", "", ]: info["size"] = int(r.headers["Content-Length"]) elif "Content-Range" in r.headers: info["size"] = int(r.headers["Content-Range"].split("/")[1])
if "Content-Type" in r.headers: info["mimetype"] = r.headers["Content-Type"].partition(";")[0]
if r.headers.get("Accept-Ranges") == "none": # Some servers may explicitly discourage partial content requests, but # the lack of "Accept-Ranges" does not always indicate they would fail info["partial"] = False
info["url"] = str(r.url)
for checksum_field in ["ETag", "Content-MD5", "Digest", "Last-Modified"]: if r.headers.get(checksum_field): info[checksum_field] = r.headers[checksum_field]
return info
async def _file_size(url, session=None, *args, **kwargs): if session is None: session = await get_client() info = await _file_info(url, session=session, *args, **kwargs) return info.get("size")
file_size = sync_wrapper(_file_size)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937"""This file is largely copied from http.py"""
import ioimport loggingimport reimport urllib.errorimport urllib.parsefrom copy import copyfrom json import dumps, loadsfrom urllib.parse import urlparse
try: import yarlexcept (ImportError, ModuleNotFoundError, OSError): yarl = False
from fsspec.callbacks import _DEFAULT_CALLBACKfrom fsspec.registry import register_implementationfrom fsspec.spec import AbstractBufferedFile, AbstractFileSystemfrom fsspec.utils import ( DEFAULT_BLOCK_SIZE, isfilelike, nullcontext, range_response_window, response_is_requested_range, tokenize,)
from ..caching import AllBytes
# https://stackoverflow.com/a/15926317/3821154# The attribute scan must stay linear: it stops at the next "<" or ">" and the# whitespace before href is a lookbehind rather than a second quantifier, so a# page cannot make it backtrack cubically (1 KB of whitespace after "<a"# used to stall ls() for seconds, 10 KB for hours).ex = re.compile(r"""<(a|A)\s[^<>]*?(?<=\s)(href|HREF)=["'](?P<url>[^"']+)""")ex2 = re.compile(r"""(?P<url>http[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""")logger = logging.getLogger("fsspec.http")
class JsHttpException(urllib.error.HTTPError): ...
class StreamIO(io.BytesIO): # fake class, so you can set attributes on it # will eventually actually stream ...
class ResponseProxy: """Looks like a requests response"""
def __init__(self, req, stream=False): self.request = req self.stream = stream self._data = None self._headers = None
@property def raw(self): if self._data is None: b = self.request.response.to_bytes() if self.stream: self._data = StreamIO(b) else: self._data = b return self._data
def close(self): if hasattr(self, "_data"): del self._data
@property def headers(self): if self._headers is None: self._headers = dict( [ _.split(": ") for _ in self.request.getAllResponseHeaders().strip().split("\r\n") ] ) return self._headers
@property def status_code(self): return int(self.request.status)
def raise_for_status(self): if not self.ok: raise JsHttpException( self.url, self.status_code, self.reason, self.headers, None )
def iter_content(self, chunksize, *_, **__): while True: out = self.raw.read(chunksize) if out: yield out else: break
@property def reason(self): return self.request.statusText
@property def ok(self): return self.status_code < 400
@property def url(self): return self.request.response.responseURL
@property def text(self): # TODO: encoding from headers return self.content.decode()
@property def content(self): self.stream = False return self.raw
def json(self): return loads(self.text)
class RequestsSessionShim: def __init__(self): self.headers = {}
def request( self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=None, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None, ): from js import Blob, XMLHttpRequest
logger.debug("JS request: %s %s", method, url)
if cert or verify or proxies or files or cookies or hooks: raise NotImplementedError if data and json: raise ValueError("Use json= or data=, not both") req = XMLHttpRequest.new() extra = auth if auth else () if params: url = f"{url}?{urllib.parse.urlencode(params)}" req.open(method, url, False, *extra) if timeout: req.timeout = timeout if headers: for k, v in headers.items(): req.setRequestHeader(k, v)
req.setRequestHeader("Accept", "application/octet-stream") req.responseType = "arraybuffer" if json: blob = Blob.new([dumps(data)], {type: "application/json"}) req.send(blob) elif data: if isinstance(data, io.IOBase): data = data.read() blob = Blob.new([data], {type: "application/octet-stream"}) req.send(blob) else: req.send(None) return ResponseProxy(req, stream=stream)
def get(self, url, **kwargs): return self.request("GET", url, **kwargs)
def head(self, url, **kwargs): return self.request("HEAD", url, **kwargs)
def post(self, url, **kwargs): return self.request("POST", url, **kwargs)
def put(self, url, **kwargs): return self.request("PUT", url, **kwargs)
def patch(self, url, **kwargs): return self.request("PATCH", url, **kwargs)
def delete(self, url, **kwargs): return self.request("DELETE", url, **kwargs)
class HTTPFileSystem(AbstractFileSystem): """ Simple File-System for fetching data via HTTP(S)
This is the BLOCKING version of the normal HTTPFileSystem. It uses requests in normal python and the JS runtime in pyodide.
***This implementation is extremely experimental, do not use unless you are testing pyodide/pyscript integration*** """
protocol = ("http", "https", "sync-http", "sync-https") sep = "/"
def __init__( self, simple_links=True, block_size=None, same_scheme=True, cache_type="readahead", cache_options=None, client_kwargs=None, encoded=False, **storage_options, ): """
Parameters ---------- block_size: int Blocks to read bytes; if 0, will default to raw requests file-like objects instead of HTTPFile instances simple_links: bool If True, will consider both HTML <a> tags and anything that looks like a URL; if False, will consider only the former. same_scheme: True When doing ls/glob, if this is True, only consider paths that have http/https matching the input URLs. size_policy: this argument is deprecated client_kwargs: dict Passed to aiohttp.ClientSession, see https://docs.aiohttp.org/en/stable/client_reference.html For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}`` storage_options: key-value Any other parameters passed on to requests cache_type, cache_options: defaults used in open """ super().__init__(self, **storage_options) self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE self.simple_links = simple_links self.same_schema = same_scheme self.cache_type = cache_type self.cache_options = cache_options self.client_kwargs = client_kwargs or {} self.encoded = encoded self.kwargs = storage_options
try: import js # noqa: F401
logger.debug("Starting JS session") self.session = RequestsSessionShim() self.js = True except Exception as e: import requests
logger.debug("Starting cpython session because of: %s", e) self.session = requests.Session(**(client_kwargs or {})) self.js = False
request_options = copy(storage_options) self.use_listings_cache = request_options.pop("use_listings_cache", False) request_options.pop("listings_expiry_time", None) request_options.pop("max_paths", None) request_options.pop("skip_instance_cache", None) self.kwargs = request_options
@property def fsid(self): return "sync-http"
def encode_url(self, url): if yarl: return yarl.URL(url, encoded=self.encoded) return url
@classmethod def _strip_protocol(cls, path: str) -> str: """For HTTP, we always want to keep the full URL""" path = path.replace("sync-http://", "http://").replace( "sync-https://", "https://" ) return path
@classmethod def _parent(cls, path): # override, since _strip_protocol is different for URLs par = super()._parent(path) if len(par) > 7: # "http://..." return par return ""
def _ls_real(self, url, detail=True, **kwargs): # ignoring URL-encoded arguments kw = self.kwargs.copy() kw.update(kwargs) logger.debug(url) r = self.session.get(self.encode_url(url), **kw) self._raise_not_found_for_status(r, url) text = r.text if self.simple_links: links = ex2.findall(text) + [u[2] for u in ex.findall(text)] else: links = [u[2] for u in ex.findall(text)] out = set() parts = urlparse(url) for l in links: if isinstance(l, tuple): l = l[1] if l.startswith("/") and len(l) > 1: # absolute URL on this server l = parts.scheme + "://" + parts.netloc + l if l.startswith("http"): if self.same_schema and l.startswith(url.rstrip("/") + "/"): out.add(l) elif l.replace("https", "http").startswith( url.replace("https", "http").rstrip("/") + "/" ): # allowed to cross http <-> https out.add(l) else: if l not in ["..", "../"]: # Ignore FTP-like "parent" out.add("/".join([url.rstrip("/"), l.lstrip("/")])) if not out and url.endswith("/"): out = self._ls_real(url.rstrip("/"), detail=False, **kwargs) if detail: return [ { "name": u, "size": None, "type": "directory" if u.endswith("/") else "file", } for u in out ] else: return sorted(out)
def ls(self, url, detail=True, **kwargs): if self.use_listings_cache and url in self.dircache: out = self.dircache[url] else: out = self._ls_real(url, detail=True, **kwargs) self.dircache[url] = out if detail: return out return sorted(entry["name"] for entry in out)
def _raise_not_found_for_status(self, response, url): """ Raises FileNotFoundError for 404s, otherwise uses raise_for_status. """ if response.status_code == 404: raise FileNotFoundError(url) response.raise_for_status()
def cat_file(self, url, start=None, end=None, **kwargs): kw = self.kwargs.copy() kw.update(kwargs) logger.debug(url)
ranged = start is not None or end is not None if ranged: if start == end or (start is None and end == 0): return b"" headers = kw.pop("headers", {}).copy()
headers["Range"] = self._process_limits(url, start, end) kw["headers"] = headers r = self.session.get(self.encode_url(url), **kw) self._raise_not_found_for_status(r, url) if not ranged: return r.content # a server that ignores the Range header replies with the whole file, # which is not the window the caller asked for return range_response_window(r.content, r.status_code, r.headers, start, end)
def get_file( self, rpath, lpath, chunk_size=5 * 2**20, callback=_DEFAULT_CALLBACK, **kwargs ): kw = self.kwargs.copy() kw.update(kwargs) logger.debug(rpath) r = self.session.get(self.encode_url(rpath), **kw) try: size = int( r.headers.get("content-length", None) or r.headers.get("Content-Length", None) ) except (ValueError, KeyError, TypeError): size = None
callback.set_size(size) self._raise_not_found_for_status(r, rpath) context = nullcontext(lpath) if isfilelike(lpath) else open(lpath, "wb") with context as outfile: for chunk in r.iter_content(chunk_size, decode_unicode=False): outfile.write(chunk) callback.relative_update(len(chunk))
def put_file( self, lpath, rpath, chunk_size=5 * 2**20, callback=_DEFAULT_CALLBACK, method="post", **kwargs, ): def gen_chunks(): # Support passing arbitrary file-like objects # and use them instead of streams. if isinstance(lpath, io.IOBase): context = nullcontext(lpath) use_seek = False # might not support seeking else: context = open(lpath, "rb") use_seek = True
with context as f: if use_seek: callback.set_size(f.seek(0, 2)) f.seek(0) else: callback.set_size(getattr(f, "size", None))
chunk = f.read(chunk_size) while chunk: yield chunk callback.relative_update(len(chunk)) chunk = f.read(chunk_size)
kw = self.kwargs.copy() kw.update(kwargs)
method = method.lower() if method not in ("post", "put"): raise ValueError( f"method has to be either 'post' or 'put', not: {method!r}" )
meth = getattr(self.session, method) resp = meth(rpath, data=gen_chunks(), **kw) self._raise_not_found_for_status(resp, rpath)
def _process_limits(self, url, start, end): """Helper for "Range"-based _cat_file""" size = None suff = False if start is not None and start < 0: # if start is negative and end None, end is the "suffix length" if end is None: end = -start start = "" suff = True else: size = size or self.info(url)["size"] start = size + start elif start is None: start = 0 if not suff: if end is not None and end < 0: if start is not None: size = size or self.info(url)["size"] end = size + end elif end is None: end = "" if isinstance(end, int): end -= 1 # bytes range is inclusive return f"bytes={start}-{end}"
def exists(self, path, strict=False, **kwargs): kw = self.kwargs.copy() kw.update(kwargs) try: logger.debug(path) r = self.session.get(self.encode_url(path), **kw) if strict: self._raise_not_found_for_status(r, path) return r.status_code < 400 except FileNotFoundError: return False except Exception: if strict: raise return False
def isfile(self, path, **kwargs): return self.exists(path, **kwargs)
def _open( self, path, mode="rb", block_size=None, autocommit=None, # XXX: This differs from the base class. cache_type=None, cache_options=None, size=None, **kwargs, ): """Make a file-like object
Parameters ---------- path: str Full URL with protocol mode: string must be "rb" block_size: int or None Bytes to download in one request; use instance value if None. If zero, will return a streaming Requests file-like instance. kwargs: key-value Any other parameters, passed to requests calls """ if mode != "rb": raise NotImplementedError block_size = block_size if block_size is not None else self.block_size kw = self.kwargs.copy() kw.update(kwargs) size = size or self.info(path, **kwargs)["size"] if block_size and size: return HTTPFile( self, path, session=self.session, block_size=block_size, mode=mode, size=size, cache_type=cache_type or self.cache_type, cache_options=cache_options or self.cache_options, **kw, ) else: return HTTPStreamFile( self, path, mode=mode, session=self.session, **kw, )
def ukey(self, url): """Unique identifier; assume HTTP files are static, unchanging""" return tokenize(url, self.kwargs, self.protocol)
def info(self, url, **kwargs): """Get info of URL
Tries to access location via HEAD, and then GET methods, but does not fetch the data.
It is possible that the server does not supply any size information, in which case size will be given as None (and certain operations on the corresponding file will not work). """ info = {} for policy in ["head", "get"]: try: info.update( _file_info( self.encode_url(url), size_policy=policy, session=self.session, **self.kwargs, **kwargs, ) ) if info.get("size") is not None: break except Exception as exc: if policy == "get": # If get failed, then raise a FileNotFoundError raise FileNotFoundError(url) from exc logger.debug(str(exc))
return {"name": url, "size": None, **info, "type": "file"}
def glob(self, path, maxdepth=None, **kwargs): """ Find files by glob-matching.
This implementation is idntical to the one in AbstractFileSystem, but "?" is not considered as a character for globbing, because it is so common in URLs, often identifying the "query" part. """ import re
ends = path.endswith("/") path = self._strip_protocol(path) indstar = path.find("*") if path.find("*") >= 0 else len(path) indbrace = path.find("[") if path.find("[") >= 0 else len(path)
ind = min(indstar, indbrace)
detail = kwargs.pop("detail", False)
if not has_magic(path): root = path depth = 1 if ends: path += "/*" elif self.exists(path): if not detail: return [path] else: return {path: self.info(path)} else: if not detail: return [] # glob of non-existent returns empty else: return {} elif "/" in path[:ind]: ind2 = path[:ind].rindex("/") root = path[: ind2 + 1] depth = None if "**" in path else path[ind2 + 1 :].count("/") + 1 else: root = "" depth = None if "**" in path else path[ind + 1 :].count("/") + 1
allpaths = self.find( root, maxdepth=maxdepth or depth, withdirs=True, detail=True, **kwargs ) # Escape characters special to python regex, leaving our supported # special characters in place. # See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html # for shell globbing details. pattern = ( "^" + ( path.replace("\\", r"\\") .replace(".", r"\.") .replace("+", r"\+") .replace("//", "/") .replace("(", r"\(") .replace(")", r"\)") .replace("|", r"\|") .replace("^", r"\^") .replace("$", r"\$") .replace("{", r"\{") .replace("}", r"\}") .rstrip("/") ) + "$" ) pattern = re.sub("[*]{2}", "=PLACEHOLDER=", pattern) pattern = re.sub("[*]", "[^/]*", pattern) pattern = re.compile(pattern.replace("=PLACEHOLDER=", ".*")) out = { p: allpaths[p] for p in sorted(allpaths) if pattern.match(p.replace("//", "/").rstrip("/")) } if detail: return out else: return list(out)
def isdir(self, path): # override, since all URLs are (also) files try: return bool(self.ls(path)) except (FileNotFoundError, ValueError): return False
class HTTPFile(AbstractBufferedFile): """ A file-like object pointing to a remove HTTP(S) resource
Supports only reading, with read-ahead of a predermined block-size.
In the case that the server does not supply the filesize, only reading of the complete file in one go is supported.
Parameters ---------- url: str Full URL of the remote resource, including the protocol session: requests.Session or None All calls will be made within this session, to avoid restarting connections where the server allows this block_size: int or None The amount of read-ahead to do, in bytes. Default is 5MB, or the value configured for the FileSystem creating this file size: None or int If given, this is the size of the file in bytes, and we don't attempt to call the server to find the value. kwargs: all other key-values are passed to requests calls. """
def __init__( self, fs, url, session=None, block_size=None, mode="rb", cache_type="bytes", cache_options=None, size=None, **kwargs, ): if mode != "rb": raise NotImplementedError("File mode not supported") self.url = url self.session = session self.details = {"name": url, "size": size, "type": "file"} super().__init__( fs=fs, path=url, mode=mode, block_size=block_size, cache_type=cache_type, cache_options=cache_options, **kwargs, )
def read(self, length=-1): """Read bytes from file
Parameters ---------- length: int Read up to this many bytes. If negative, read all content to end of file. If the server has not supplied the filesize, attempting to read only part of the data will raise a ValueError. """ if ( (length < 0 and self.loc == 0) # explicit read all # but not when the size is known and fits into a block anyways and not (self.size is not None and self.size <= self.blocksize) ): self._fetch_all() if self.size is None: if length < 0: self._fetch_all() else: length = min(self.size - self.loc, length) return super().read(length)
def _fetch_all(self): """Read whole file in one shot, without caching
This is only called when position is still at zero, and read() is called without a byte-count. """ logger.debug(f"Fetch all for {self}") if not isinstance(self.cache, AllBytes): r = self.session.get(self.fs.encode_url(self.url), **self.kwargs) r.raise_for_status() out = r.content self.cache = AllBytes(size=len(out), fetcher=None, blocksize=None, data=out) self.size = len(out)
def _fetch_range(self, start, end): """Download a block of data
The expectation is that the server returns only the requested bytes, with HTTP code 206. If this is not the case, we first check the headers, and then stream the output - if the data size is bigger than we requested, an exception is raised. """ logger.debug(f"Fetch range for {self}: {start}-{end}") kwargs = self.kwargs.copy() headers = kwargs.pop("headers", {}).copy() headers["Range"] = f"bytes={start}-{end - 1}" logger.debug("%s : %s", self.url, headers["Range"]) r = self.session.get(self.fs.encode_url(self.url), headers=headers, **kwargs) if r.status_code == 416: # range request outside file return b"" r.raise_for_status()
# If the server has handled the range request, it should reply # with status 206 (partial content). But we'll guess that a suitable # Content-Range header or a Content-Length no more than the # requested range also mean we have got the desired range. if response_is_requested_range(r.status_code, r.headers, start, end): # partial content, as expected out = r.content elif start > 0: raise ValueError( "The HTTP server doesn't appear to support range requests. " "Only reading this file from the beginning is supported. " "Open with block_size=0 for a streaming file interface." ) else: # Response is not a range, but we want the start of the file, # so we can read the required amount anyway. cl = 0 out = [] for chunk in r.iter_content(2**20, False): out.append(chunk) cl += len(chunk) out = b"".join(out)[: end - start] return out
magic_check = re.compile("([*[])")
def has_magic(s): match = magic_check.search(s) return match is not None
class HTTPStreamFile(AbstractBufferedFile): def __init__(self, fs, url, mode="rb", session=None, **kwargs): self.url = url self.session = session if mode != "rb": raise ValueError self.details = {"name": url, "size": None} super().__init__(fs=fs, path=url, mode=mode, cache_type="readahead", **kwargs)
r = self.session.get(self.fs.encode_url(url), stream=True, **kwargs) self.fs._raise_not_found_for_status(r, url) self.it = r.iter_content(1024, False) self.leftover = b""
self.r = r
def seek(self, *args, **kwargs): raise ValueError("Cannot seek streaming HTTP file")
def read(self, num=-1): bufs = [self.leftover] leng = len(self.leftover) while leng < num or num < 0: try: out = self.it.__next__() except StopIteration: break if out: bufs.append(out) else: break leng += len(out) out = b"".join(bufs) if num >= 0: self.leftover = out[num:] out = out[:num] else: self.leftover = b"" self.loc += len(out) return out
def close(self): self.r.close() self.closed = True
def get_range(session, url, start, end, **kwargs): # explicit get a range when we know it must be safe kwargs = kwargs.copy() headers = kwargs.pop("headers", {}).copy() headers["Range"] = f"bytes={start}-{end - 1}" r = session.get(url, headers=headers, **kwargs) r.raise_for_status() return r.content
def _file_info(url, session, size_policy="head", **kwargs): """Call HEAD on the server to get details about the file (size/checksum etc.)
Default operation is to explicitly allow redirects and use encoding 'identity' (no compression) to get the true size of the target. """ logger.debug("Retrieve file size for %s", url) kwargs = kwargs.copy() ar = kwargs.pop("allow_redirects", True) head = kwargs.get("headers", {}).copy() # TODO: not allowed in JS # head["Accept-Encoding"] = "identity" kwargs["headers"] = head
info = {} if size_policy == "head": r = session.head(url, allow_redirects=ar, **kwargs) elif size_policy == "get": r = session.get(url, allow_redirects=ar, **kwargs) else: raise TypeError(f'size_policy must be "head" or "get", got {size_policy}') r.raise_for_status()
# TODO: # recognise lack of 'Accept-Ranges', # or 'Accept-Ranges': 'none' (not 'bytes') # to mean streaming only, no random access => return None encoding = r.headers.get("Content-Encoding", r.headers.get("content-encoding", "")) # The transport length is not the size of the decoded stream. if encoding in ("identity", ""): if "Content-Length" in r.headers: info["size"] = int(r.headers["Content-Length"]) elif "Content-Range" in r.headers: info["size"] = int(r.headers["Content-Range"].split("/")[1]) elif "content-length" in r.headers: info["size"] = int(r.headers["content-length"]) elif "content-range" in r.headers: info["size"] = int(r.headers["content-range"].split("/")[1])
for checksum_field in ["ETag", "Content-MD5", "Digest"]: if r.headers.get(checksum_field): info[checksum_field] = r.headers[checksum_field]
return info
# importing this is enough to register itdef register(): register_implementation("http", HTTPFileSystem, clobber=True) register_implementation("https", HTTPFileSystem, clobber=True) register_implementation("sync-http", HTTPFileSystem, clobber=True) register_implementation("sync-https", HTTPFileSystem, clobber=True)
register()
def unregister(): from fsspec.implementations.http import HTTPFileSystem
register_implementation("http", HTTPFileSystem, clobber=True) register_implementation("https", HTTPFileSystem, clobber=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230"""Files in Internet Archive items, ``ia://<item>/<filename>``."""
import configparserimport osfrom dataclasses import dataclass
import aiohttpfrom aiohttp import hdrs
from ..utils import stringify_pathfrom .http import HTTPFileSystem
DOWNLOAD_URL = "https://archive.org/download/"AUTH_DOMAIN = ".archive.org"# The environment variable names the ``internetarchive`` package uses.ENV_ACCESS_KEY = "IA_ACCESS_KEY_ID"ENV_SECRET_KEY = "IA_SECRET_ACCESS_KEY"ENV_CONFIG_FILE = "IA_CONFIG_FILE"
def ia_config_path(): """The ``ia.ini`` written by ``ia configure``, or None.
Searched the way the ``internetarchive`` package searches: ``$IA_CONFIG_FILE``, ``$XDG_CONFIG_HOME/internetarchive/ia.ini`` (``XDG_CONFIG_HOME`` defaulting to ``~/.config``), ``~/.config/ia.ini``, ``~/.ia``. The first existing file wins. """ home = os.path.expanduser("~") xdg = os.environ.get("XDG_CONFIG_HOME") or os.path.join(home, ".config") candidates = [ os.environ.get(ENV_CONFIG_FILE), os.path.join(xdg, "internetarchive", "ia.ini"), os.path.join(home, ".config", "ia.ini"), os.path.join(home, ".ia"), ] return next((p for p in candidates if p and os.path.isfile(p)), None)
@dataclass(frozen=True)class IACredentials: """The IA-S3 key pair that logs a request in at archive.org; None means anonymous."""
access_key: "str | None" = None secret_key: "str | None" = None config_file: "str | None" = None # where they were read from
@property def anonymous(self): return not self.access_key
@property def authorization(self): """The ``Authorization`` header value, or None when anonymous.""" if self.anonymous: return None return f"LOW {self.access_key}:{self.secret_key}"
def load_ia_credentials(config_file=None): """Credentials from ``ia.ini`` and the environment; anonymous when there are none.
``[s3] access/secret`` are read from ``config_file`` (default: :func:`ia_config_path`); the ``[cookies]`` section ``ia configure`` also writes is ignored, as the keys log a request in on their own. ``IA_ACCESS_KEY_ID`` / ``IA_SECRET_ACCESS_KEY`` override the file's keys and must be set together. A missing file or section is not an error: public items need nothing. """ path = config_file or ia_config_path() access_key = secret_key = None if path and os.path.isfile(path): # RawConfigParser: the file's cookie values contain '%' (URL-encoded # emails), which the default interpolation would reject. parser = configparser.RawConfigParser() parser.read(path, encoding="utf-8") access_key = parser.get("s3", "access", fallback="").strip() or None secret_key = parser.get("s3", "secret", fallback="").strip() or None
env_access = os.environ.get(ENV_ACCESS_KEY) env_secret = os.environ.get(ENV_SECRET_KEY) if bool(env_access) != bool(env_secret): raise ValueError(f"{ENV_ACCESS_KEY} and {ENV_SECRET_KEY} must be set together") if env_access: access_key, secret_key = env_access, env_secret if not (access_key and secret_key): access_key = secret_key = None found = path if path and os.path.isfile(path) else None return IACredentials(access_key, secret_key, found)
def in_domain(host, domain): """Whether ``host`` is ``domain`` (leading dot optional) or a subdomain of it.""" if not host: return False domain = domain.lower().lstrip(".") host = host.lower().rstrip(".") return host == domain or host.endswith("." + domain)
def authorized_request_class( authorization, domain, base=aiohttp.ClientRequest, https_only=True): """A ``ClientRequest`` that sends ``authorization`` to every host in ``domain``.
aiohttp drops ``Authorization`` when a redirect changes origin, and every archive.org download is such a redirect (to a data node). It builds a new request from the session's ``request_class`` for each hop, so setting the header here puts it back on the data-node hop; testing the host keeps it from leaving ``domain`` should a data node redirect elsewhere. With ``https_only``, a plain http hop gets no header either, as aiohttp would also have dropped it on an https -> http redirect. """
class AuthorizedRequest(base): def update_headers(self, headers): super().update_headers(headers) if https_only and self.url.scheme != "https": return if in_domain(self.url.host, domain): self.headers[hdrs.AUTHORIZATION] = authorization
return AuthorizedRequest
class InternetArchiveFileSystem(HTTPFileSystem): """Files in Internet Archive items, addressed as ``ia://<item>/<filename>``.
Every path is read from ``https://archive.org/download/<item>/<filename>``, which redirects to a data node that honours HTTP Range requests, so this is ``HTTPFileSystem`` with a path mapping and archive.org credentials. (IA's S3-like API at ``s3.us.archive.org`` is not used: it ignores Range headers and redirects GET to plain-http data nodes, so block reads would fetch whole files.)
Public items need no credentials. Restricted items need the account's IA-S3 keys, as written by ``ia configure`` from the ``internetarchive`` package to ``ia.ini``; that file is found the way the package finds it (``$IA_CONFIG_FILE``, ``$XDG_CONFIG_HOME/internetarchive/ia.ini``, ``~/.config/ia.ini``, ``~/.ia``). Explicit arguments win over the file.
Parameters ---------- access_key, secret_key: str, optional IA S3 keys, sent as ``Authorization: LOW <access>:<secret>`` to every archive.org host, including the data node the download URL redirects to (aiohttp drops the header on a cross-origin redirect; the session's request class puts it back, and only for ``.archive.org`` hosts over https). Both or neither; ``IA_ACCESS_KEY_ID`` / ``IA_SECRET_ACCESS_KEY`` in the environment override ``ia.ini``. Pass empty strings to stay anonymous despite an ``ia.ini``. config_file: str, optional Path to an ``ia.ini`` to read credentials from instead of the default lookup. kwargs: Passed to ``HTTPFileSystem``. """
protocol = "ia" download_url = DOWNLOAD_URL auth_domain = AUTH_DOMAIN
def __init__(self, access_key=None, secret_key=None, config_file=None, **kwargs): if access_key is None and secret_key is None: found = load_ia_credentials(config_file) access_key, secret_key = found.access_key, found.secret_key elif bool(access_key) != bool(secret_key): raise ValueError("access_key and secret_key must be given together") credentials = IACredentials(access_key or None, secret_key or None) self.access_key = credentials.access_key self.authorization = credentials.authorization if self.authorization: client_kwargs = dict(kwargs.pop("client_kwargs", None) or {}) client_kwargs["request_class"] = authorized_request_class( self.authorization, self.auth_domain, client_kwargs.get("request_class", aiohttp.ClientRequest), https_only=self.download_url.startswith("https://"), ) kwargs["client_kwargs"] = client_kwargs super().__init__(**kwargs)
@property def fsid(self): return "ia"
@classmethod def _strip_protocol(cls, path): """``ia://item/file`` (or bare ``item/file``) becomes the download URL.
A URL passes through unchanged, so the mapping is idempotent. """ if isinstance(path, list): return [cls._strip_protocol(p) for p in path] path = stringify_path(path) if path.startswith("ia://"): path = path[5:] elif "://" in path: return path return cls.download_url + path.lstrip("/")
def unstrip_protocol(self, name): if name.startswith(self.download_url): return "ia://" + name[len(self.download_url) :] if name.startswith("ia://"): return name return "ia://" + name.lstrip("/")
# archive.org answers a restricted item with 403 (401 for a bad LOW key). # HTTPFileSystem reports a failed HEAD+GET as FileNotFoundError and any other # status through raise_for_status(); both become PermissionError so callers can # tell "no such file" from "log in". The two methods callers reach with an # ia:// path directly (open() strips before _open) map it here too. async def _info(self, url, **kwargs): url = self._strip_protocol(url) try: return await super()._info(url, **kwargs) except FileNotFoundError as exc: cause = exc.__cause__ if isinstance(cause, aiohttp.ClientResponseError) and cause.status in ( 401, 403, ): raise PermissionError(url) from cause raise
async def _cat_file(self, url, start=None, end=None, **kwargs): url = self._strip_protocol(url) return await super()._cat_file(url, start=start, end=end, **kwargs)
def _raise_not_found_for_status(self, response, url): if response.status in (401, 403): raise PermissionError(url) super()._raise_not_found_for_status(response, url)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132import base64import ioimport re
import requests
import fsspec
class JupyterFileSystem(fsspec.AbstractFileSystem): """View of the files as seen by a Jupyter server (notebook or lab)"""
protocol = ("jupyter", "jlab")
def __init__(self, url, tok=None, **kwargs): """
Parameters ---------- url : str Base URL of the server, like "http://127.0.0.1:8888". May include token in the string, which is given by the process when starting up tok : str If the token is obtained separately, can be given here kwargs """ if "?" in url: if tok is None: try: tok = re.findall("token=([a-z0-9]+)", url)[0] except IndexError as e: raise ValueError("Could not determine token") from e url = url.split("?", 1)[0] self.url = url.rstrip("/") + "/api/contents" self.session = requests.Session() if tok: self.session.headers["Authorization"] = f"token {tok}"
super().__init__(**kwargs)
def ls(self, path, detail=True, **kwargs): path = self._strip_protocol(path) r = self.session.get(f"{self.url}/{path}") if r.status_code == 404: raise FileNotFoundError(path) r.raise_for_status() out = r.json()
if out["type"] == "directory": out = out["content"] else: out = [out] for o in out: o["name"] = o.pop("path") o.pop("content") if o["type"] == "notebook": o["type"] = "file" if detail: return out return [o["name"] for o in out]
def cat_file(self, path, start=None, end=None, **kwargs): path = self._strip_protocol(path) # Ask for the raw file; by default notebooks come back as parsed JSON r = self.session.get( f"{self.url}/{path}", params={"type": "file", "format": "base64"} ) if r.status_code == 404: raise FileNotFoundError(path) r.raise_for_status() out = r.json() if out["format"] == "text": # data should be binary b = out["content"].encode() else: b = base64.b64decode(out["content"]) return b[start:end]
def pipe_file(self, path, value, **_): path = self._strip_protocol(path) json = { "name": path.rsplit("/", 1)[-1], "path": path, "size": len(value), "content": base64.b64encode(value).decode(), "format": "base64", "type": "file", } self.session.put(f"{self.url}/{path}", json=json)
def mkdir(self, path, create_parents=True, **kwargs): path = self._strip_protocol(path) if create_parents and "/" in path: self.mkdir(path.rsplit("/", 1)[0], True) json = { "name": path.rsplit("/", 1)[-1], "path": path, "size": None, "content": None, "type": "directory", } self.session.put(f"{self.url}/{path}", json=json)
def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs): if path1 == path2: return self.session.patch(f"{self.url}/{path1}", json={"path": path2})
def _rm(self, path): path = self._strip_protocol(path) self.session.delete(f"{self.url}/{path}")
def _open(self, path, mode="rb", **kwargs): path = self._strip_protocol(path) if mode == "rb": data = self.cat_file(path) return io.BytesIO(data) else: return SimpleFileWriter(self, path, mode="wb")
class SimpleFileWriter(fsspec.spec.AbstractBufferedFile): def _upload_chunk(self, final=False): """Never uploads a chunk until file is done
Not suitable for large files """ if final is False: return False self.buffer.seek(0) data = self.buffer.read() self.fs.pipe_file(self.path, data)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219from contextlib import contextmanagerfrom ctypes import ( CFUNCTYPE, POINTER, c_int, c_longlong, c_void_p, cast, create_string_buffer,)
import libarchiveimport libarchive.ffi as ffi
from fsspec import open_filesfrom fsspec.archive import AbstractArchiveFileSystemfrom fsspec.implementations.memory import MemoryFilefrom fsspec.utils import DEFAULT_BLOCK_SIZE
# Libarchive requires seekable files or memory only for certain archive# types. However, since we read the directory first to cache the contents# and also allow random access to any file, the file-like object needs# to be seekable no matter what.
# Seek call-backs (not provided in the libarchive python wrapper)SEEK_CALLBACK = CFUNCTYPE(c_longlong, c_int, c_void_p, c_longlong, c_int)read_set_seek_callback = ffi.ffi( "read_set_seek_callback", [ffi.c_archive_p, SEEK_CALLBACK], c_int, ffi.check_int)new_api = hasattr(ffi, "NO_OPEN_CB")
@contextmanagerdef custom_reader(file, format_name="all", filter_name="all", block_size=ffi.page_size): """Read an archive from a seekable file-like object.
The `file` object must support the standard `readinto` and 'seek' methods. """ buf = create_string_buffer(block_size) buf_p = cast(buf, c_void_p)
def read_func(archive_p, context, ptrptr): # readinto the buffer, returns number of bytes read length = file.readinto(buf) # write the address of the buffer into the pointer ptrptr = cast(ptrptr, POINTER(c_void_p)) ptrptr[0] = buf_p # tell libarchive how much data was written into the buffer return length
def seek_func(archive_p, context, offset, whence): file.seek(offset, whence) # tell libarchvie the current position return file.tell()
read_cb = ffi.READ_CALLBACK(read_func) seek_cb = SEEK_CALLBACK(seek_func)
if new_api: open_cb = ffi.NO_OPEN_CB close_cb = ffi.NO_CLOSE_CB else: open_cb = libarchive.read.OPEN_CALLBACK(ffi.VOID_CB) close_cb = libarchive.read.CLOSE_CALLBACK(ffi.VOID_CB)
with libarchive.read.new_archive_read(format_name, filter_name) as archive_p: read_set_seek_callback(archive_p, seek_cb) ffi.read_open(archive_p, None, open_cb, read_cb, close_cb) yield libarchive.read.ArchiveRead(archive_p)
class LibArchiveFileSystem(AbstractArchiveFileSystem): """Compressed archives as a file-system (read-only)
Supports the following formats: tar, pax , cpio, ISO9660, zip, mtree, shar, ar, raw, xar, lha/lzh, rar Microsoft CAB, 7-Zip, WARC
See the libarchive documentation for further restrictions. https://www.libarchive.org/
Keeps file object open while instance lives. It only works in seekable file-like objects. In case the filesystem does not support this kind of file object, it is recommended to cache locally.
This class is pickleable, but not necessarily thread-safe (depends on the platform). See libarchive documentation for details. """
root_marker = "" protocol = "libarchive" cachable = False
def __init__( self, fo="", mode="r", target_protocol=None, target_options=None, block_size=DEFAULT_BLOCK_SIZE, **kwargs, ): """ Parameters ---------- fo: str or file-like Contains ZIP, and must exist. If a str, will fetch file using :meth:`~fsspec.open_files`, which must return one file exactly. mode: str Currently, only 'r' accepted target_protocol: str (optional) If ``fo`` is a string, this value can be used to override the FS protocol inferred from a URL target_options: dict (optional) Kwargs passed when instantiating the target FS, if ``fo`` is a string. """ super().__init__(self, **kwargs) if mode != "r": raise ValueError("Only read from archive files accepted") if isinstance(fo, str): files = open_files(fo, protocol=target_protocol, **(target_options or {})) if len(files) != 1: raise ValueError( f'Path "{fo}" did not resolve to exactly one file: "{files}"' ) fo = files[0] self.of = fo self.fo = fo.__enter__() # the whole instance is a context self.block_size = block_size self.dir_cache = None
@contextmanager def _open_archive(self): self.fo.seek(0) with custom_reader(self.fo, block_size=self.block_size) as arc: yield arc
@classmethod def _strip_protocol(cls, path): # file paths are always relative to the archive root return cls._normalize_path(super()._strip_protocol(path))
@staticmethod def _normalize_path(path): return "/".join(part for part in path.split("/") if part not in ("", "."))
def ls(self, path, detail=True, **kwargs): entries = super().ls(path, detail=detail, **kwargs) return [entry for entry in entries if (entry["name"] if detail else entry)]
def _get_dirs(self): fields = { "name": "pathname", "size": "size", "created": "ctime", "mode": "mode", "uid": "uid", "gid": "gid", "mtime": "mtime", }
if self.dir_cache is not None: return
self.dir_cache = {} self._member_names = {} list_names = [] with self._open_archive() as arc: for entry in arc: if not entry.isdir and not entry.isfile: # Skip symbolic links, fifo entries, etc. continue f = {key: getattr(entry, fields[key]) for key in fields} f["type"] = "directory" if entry.isdir else "file" f["name"] = self._normalize_path(f["name"]) list_names.append(f["name"])
self.dir_cache[f["name"]] = f self._member_names[f["name"]] = entry.pathname # libarchive does not seem to return an entry for the directories (at least # not in all formats), so get the directories names from the files names for dirname in self._all_dirnames(list_names): self.dir_cache.setdefault( dirname, {"name": dirname, "size": 0, "type": "directory"} )
def _open( self, path, mode="rb", block_size=None, autocommit=True, cache_options=None, **kwargs, ): path = self._strip_protocol(path) if mode != "rb": raise NotImplementedError if not self.isfile(path): raise self._not_a_file(path)
data = b"" with self._open_archive() as arc: for entry in arc: if entry.pathname != self._member_names[path]: continue
if entry.size == 0: # empty file, so there are no blocks data = b"" continue
for block in entry.get_blocks(entry.size): data = block break else: raise ValueError return MemoryFile(fs=self, path=path, data=data)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537import datetimeimport ioimport loggingimport osimport os.path as ospimport shutilimport statimport tempfilefrom functools import lru_cache
from fsspec.compression import comprfrom fsspec.core import get_compressionfrom fsspec.utils import isfilelike, stringify_path
from ..spec import AbstractFileSystem
logger = logging.getLogger("fsspec.local")
class LocalFileSystem(AbstractFileSystem): """Interface to files on local storage
Parameters ---------- auto_mkdir: bool Whether, when opening a file, the directory containing it should be created (if it doesn't already exist). This is assumed by pyarrow code. """
root_marker = "/" protocol = "file", "local" local_file = True
def __init__(self, auto_mkdir=False, **kwargs): super().__init__(**kwargs) self.auto_mkdir = auto_mkdir
@property def fsid(self): return "local"
def mkdir(self, path, create_parents=True, **kwargs): path = self._strip_protocol(path) if self.exists(path): raise FileExistsError(path) if create_parents: self.makedirs(path, exist_ok=True) else: os.mkdir(path, **kwargs)
def makedirs(self, path, exist_ok=False): path = self._strip_protocol(path) os.makedirs(path, exist_ok=exist_ok)
def rmdir(self, path): path = self._strip_protocol(path) os.rmdir(path)
def ls(self, path, detail=False, **kwargs): path = self._strip_protocol(path) path_info = self.info(path) infos = [] if path_info["type"] == "directory": with os.scandir(path) as it: for f in it: try: # Only get the info if requested since it is a bit expensive (the stat call inside) # The strip_protocol is also used in info() and calls make_path_posix to always return posix paths info = self.info(f) if detail else self._strip_protocol(f.path) infos.append(info) except FileNotFoundError: pass else: infos = [path_info] if detail else [path_info["name"]]
return infos
def info(self, path, **kwargs): if isinstance(path, os.DirEntry): # scandir DirEntry out = path.stat(follow_symlinks=False) link = path.is_symlink() if path.is_dir(follow_symlinks=False): t = "directory" elif path.is_file(follow_symlinks=False): t = "file" else: t = "other"
size = out.st_size if link: try: out2 = path.stat(follow_symlinks=True) size = out2.st_size except OSError: size = 0 path = self._strip_protocol(path.path) else: # str or path-like path = self._strip_protocol(path) out = os.stat(path, follow_symlinks=False) link = stat.S_ISLNK(out.st_mode) if link: out = os.stat(path, follow_symlinks=True) size = out.st_size if stat.S_ISDIR(out.st_mode): t = "directory" elif stat.S_ISREG(out.st_mode): t = "file" else: t = "other"
# Check for the 'st_birthtime' attribute, which is not always present; fallback to st_ctime created_time = getattr(out, "st_birthtime", out.st_ctime)
result = { "name": path, "size": size, "type": t, "created": created_time, "islink": link, } for field in ["mode", "uid", "gid", "mtime", "ino", "nlink"]: result[field] = getattr(out, f"st_{field}") if link: result["destination"] = os.readlink(path) return result
def lexists(self, path, **kwargs): return osp.lexists(self._strip_protocol(path))
def cp_file(self, path1, path2, **kwargs): path1 = self._strip_protocol(path1) path2 = self._strip_protocol(path2) if self.auto_mkdir: self.makedirs(self._parent(path2), exist_ok=True) if self.isfile(path1): shutil.copyfile(path1, path2) elif self.isdir(path1): self.mkdirs(path2, exist_ok=True) else: raise FileNotFoundError(path1)
def isfile(self, path): path = self._strip_protocol(path) return os.path.isfile(path)
def isdir(self, path): path = self._strip_protocol(path) return os.path.isdir(path)
def get_file(self, path1, path2, callback=None, **kwargs): if isfilelike(path2): with open(self._strip_protocol(path1), "rb") as f: shutil.copyfileobj(f, path2) else: return self.cp_file(path1, path2, **kwargs)
def put_file(self, path1, path2, callback=None, mode="overwrite", **kwargs): if mode == "create" and self.exists(path2): raise FileExistsError(path2) return self.cp_file(path1, path2, **kwargs)
def mv(self, path1, path2, recursive: bool = True, **kwargs): """Move files/directories For the specific case of local, all ops on directories are recursive and the recursive= kwarg is ignored. """ path1 = self._strip_protocol(path1) path2 = self._strip_protocol(path2)
if self.auto_mkdir: self.makedirs(self._parent(path2), exist_ok=True)
shutil.move(path1, path2)
def link(self, src, dst, **kwargs): src = self._strip_protocol(src) dst = self._strip_protocol(dst) os.link(src, dst, **kwargs)
def symlink(self, src, dst, **kwargs): src = self._strip_protocol(src) dst = self._strip_protocol(dst) os.symlink(src, dst, **kwargs)
def islink(self, path) -> bool: return os.path.islink(self._strip_protocol(path))
def rm_file(self, path): os.remove(self._strip_protocol(path))
def rm(self, path, recursive=False, maxdepth=None): if not isinstance(path, list): path = [path]
for p in path: p = self._strip_protocol(p) if self.isdir(p) and not self.islink(p): if not recursive: raise ValueError("Cannot delete directory, set recursive=True") if osp.abspath(p) == os.getcwd(): raise ValueError("Cannot delete current working directory") if maxdepth is None: shutil.rmtree(p) else: # only delete down to maxdepth; a directory still holding # deeper files is kept paths = self.expand_path(p, recursive=True, maxdepth=maxdepth) for sub in reversed(paths): if not self.isdir(sub) or self.islink(sub): os.remove(sub) elif not os.listdir(sub): os.rmdir(sub) else: os.remove(p)
def unstrip_protocol(self, name): protocol = self.protocol if isinstance(self.protocol, str) else self.protocol[0] name = self._strip_protocol(name) # normalise for local/win/... return f"{protocol}://{name}"
def _open(self, path, mode="rb", block_size=None, **kwargs): path = self._strip_protocol(path) if self.auto_mkdir and ("w" in mode or "x" in mode or "a" in mode): self.makedirs(self._parent(path), exist_ok=True) return LocalFileOpener(path, mode, fs=self, **kwargs)
def touch(self, path, truncate=True, **kwargs): path = self._strip_protocol(path) if self.auto_mkdir: self.makedirs(self._parent(path), exist_ok=True) if self.exists(path): os.utime(path, None) else: open(path, "a").close() if truncate: os.truncate(path, 0)
def created(self, path): info = self.info(path=path) return datetime.datetime.fromtimestamp( info["created"], tz=datetime.timezone.utc )
def modified(self, path): info = self.info(path=path) return datetime.datetime.fromtimestamp(info["mtime"], tz=datetime.timezone.utc)
@classmethod def _parent(cls, path): path = cls._strip_protocol(path) if os.sep == "/": # posix native return path.rsplit("/", 1)[0] or "/" else: # NT path_ = path.rsplit("/", 1)[0] if len(path_) <= 3: if path_[1:2] == ":": # nt root (something like c:/) return path_[0] + ":/" # More cases may be required here return path_
@classmethod def _strip_protocol(cls, path): path = stringify_path(path) protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol prefixes = (protocol + sep for protocol in protos for sep in ("://", ":")) for prefix in prefixes: if path.startswith(prefix): path = path.removeprefix(prefix) break
path = make_path_posix(path) if os.sep != "/": # This code-path is a stripped down version of # > drive, path = ntpath.splitdrive(path) if path[1:2] == ":": # Absolute drive-letter path, e.g. X:\Windows # Relative path with drive, e.g. X:Windows drive, path = path[:2], path[2:] elif path[:2] == "//": # UNC drives, e.g. \\server\share or \\?\UNC\server\share # Device drives, e.g. \\.\device or \\?\device if (index1 := path.find("/", 2)) == -1 or ( index2 := path.find("/", index1 + 1) ) == -1: drive, path = path, "" else: drive, path = path[:index2], path[index2:] else: # Relative path, e.g. Windows drive = ""
path = path.rstrip("/") or cls.root_marker return drive + path
else: return path.rstrip("/") or cls.root_marker
def _isfilestore(self): # Inheriting from DaskFileSystem makes this False (S3, etc. were) # the original motivation. But we are a posix-like file system. # See https://github.com/dask/dask/issues/5526 return True
def chmod(self, path, mode): path = self._strip_protocol(path) return os.chmod(path, mode)
def make_path_posix(path): """Make path generic and absolute for current OS""" if not isinstance(path, str): if isinstance(path, (list, set, tuple)): return type(path)(make_path_posix(p) for p in path) else: path = stringify_path(path) if not isinstance(path, str): raise TypeError(f"could not convert {path!r} to string") if os.sep == "/": # Native posix if path.startswith("/"): # most common fast case for posix return path elif path.startswith("~"): return osp.expanduser(path) elif path.startswith("./"): path = path[2:] elif path == ".": path = "" return f"{os.getcwd()}/{path}" else: # NT handling if path[0:1] == "/" and path[2:3] == ":": # path is like "/c:/local/path" path = path[1:] if path[1:2] == ":": # windows full path like "C:\\local\\path" if len(path) == 2 or (len(path) == 3 and path[2] in "/\\"): # nt root (something like c:/). A three-character "c:x" is not a # root: it names "x" relative to that drive, so it falls through # instead of being collapsed to the drive root. return path[0] + ":/" path = path.replace("\\", "/") return path elif path[0:1] == "~": return make_path_posix(osp.expanduser(path)) elif path.startswith(("\\\\", "//")): # windows UNC/DFS-style paths return "//" + path[2:].replace("\\", "/") elif path.startswith(("\\", "/")): # windows relative path with root path = path.replace("\\", "/") return f"{osp.splitdrive(os.getcwd())[0]}{path}" else: path = path.replace("\\", "/") if path.startswith("./"): path = path[2:] elif path == ".": path = "" return f"{make_path_posix(os.getcwd())}/{path}"
def trailing_sep(path): """Return True if the path ends with a path separator.
A forward slash is always considered a path separator, even on Operating Systems that normally use a backslash. """ # TODO: if all incoming paths were posix-compliant then separator would # always be a forward slash, simplifying this function. # See https://github.com/fsspec/filesystem_spec/pull/1250 return path.endswith(os.sep) or (os.altsep is not None and path.endswith(os.altsep))
@lru_cache(maxsize=1)def get_umask(mask: int = 0o666) -> int: """Get the current umask.
Follows https://stackoverflow.com/a/44130549 to get the umask. Temporarily sets the umask to the given value, and then resets it to the original value. """ value = os.umask(mask) os.umask(value) return value
class LocalFileOpener(io.IOBase): def __init__( self, path, mode, autocommit=True, fs=None, compression=None, **kwargs ): logger.debug("open file: %s", path) self.path = path self.mode = mode self.fs = fs self.f = None self.autocommit = autocommit self.compression = get_compression(path, compression) self.blocksize = io.DEFAULT_BUFFER_SIZE self._open()
def _open(self): if self.f is None or self.f.closed: if self.autocommit or "w" not in self.mode: self.f = open(self.path, mode=self.mode) if self.compression: compress = compr[self.compression] self.f = compress(self.f, mode=self.mode) else: # TODO: check if path is writable? i, name = tempfile.mkstemp() os.close(i) # we want normal open and normal buffered file self.temp = name self.f = open(name, mode=self.mode) if "r" in self.mode: self.size = self.f.seek(0, 2) self.f.seek(0) self.f.size = self.size
def _fetch_range(self, start, end): # probably only used by cached FS if "r" not in self.mode: raise ValueError self._open() self.f.seek(start) return self.f.read(end - start)
def __setstate__(self, state): self.f = None loc = state.pop("loc", None) self.__dict__.update(state) if "r" in state["mode"]: self.f = None self._open() self.f.seek(loc)
def __getstate__(self): d = self.__dict__.copy() d.pop("f") if "r" in self.mode: d["loc"] = self.f.tell() else: if not self.f.closed: raise ValueError("Cannot serialise open write-mode local file") return d
def commit(self): if self.autocommit: raise RuntimeError("Can only commit if not already set to autocommit") if not self.f.closed: # a compression wrapper (e.g., GzipFile) does not close the file # object it was given, so buffered bytes and any trailer may still # be pending here. Windows also refuses to rename an open file. self.f.close() try: shutil.move(self.temp, self.path) except PermissionError as e: # shutil.move raises PermissionError if os.rename # and the default copy2 fallback with shutil.copystats fail. # The file should be there nonetheless, but without copied permissions. # If it doesn't exist, there was no permission to create the file. if not os.path.exists(self.path): raise e else: # If PermissionError is not raised, permissions can be set. try: mask = 0o666 os.chmod(self.path, mask & ~get_umask(mask)) except RuntimeError: pass
def discard(self): if self.autocommit: raise RuntimeError("Cannot discard if set to autocommit") os.remove(self.temp)
def readable(self) -> bool: return True
def writable(self) -> bool: return "r" not in self.mode
def read(self, *args, **kwargs): return self.f.read(*args, **kwargs)
def write(self, *args, **kwargs): return self.f.write(*args, **kwargs)
def tell(self, *args, **kwargs): return self.f.tell(*args, **kwargs)
def seek(self, *args, **kwargs): return self.f.seek(*args, **kwargs)
def seekable(self, *args, **kwargs): return self.f.seekable(*args, **kwargs)
def readline(self, *args, **kwargs): return self.f.readline(*args, **kwargs)
def readlines(self, *args, **kwargs): return self.f.readlines(*args, **kwargs)
def close(self): return self.f.close()
def truncate(self, size=None) -> int: return self.f.truncate(size)
@property def closed(self): return self.f.closed
def fileno(self): return self.raw.fileno()
def flush(self) -> None: self.f.flush()
def __iter__(self): return self.f.__iter__()
def __getattr__(self, item): return getattr(self.f, item)
def __enter__(self): self._incontext = True return self
def __exit__(self, exc_type, exc_value, traceback): self._incontext = False self.f.__exit__(exc_type, exc_value, traceback)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476from __future__ import annotations
import loggingfrom datetime import datetime, timezonefrom errno import ENOTEMPTYfrom io import BytesIOfrom pathlib import PurePath, PureWindowsPathfrom typing import Any
from fsspec import AbstractFileSystemfrom fsspec.implementations.local import LocalFileSystemfrom fsspec.utils import stringify_path, tokenize
logger = logging.getLogger("fsspec.memoryfs")
class MemoryFileSystem(AbstractFileSystem): """A filesystem based on a dict of BytesIO objects
By default, instances share a global in-memory filesystem. Pass ``global_store=False, skip_instance_cache=True`` to create a new instance with an independent store instead. """
store: dict[str, Any] = {} # shared by default pseudo_dirs = [""] # shared by default protocol = "memory" root_marker = "/"
def __init__(self, *args, global_store=True, **kwargs): """Create a memory filesystem.
Parameters ---------- global_store: bool Share files and directories with other default instances. If False, each instance starts with an empty, independent store. The normal instance cache still applies; pass ``skip_instance_cache=True`` to create a new instance on every call. Pickling an independent filesystem copies its files and directories; pickling a global filesystem retains the reference to the global store. """ super().__init__(*args, **kwargs) self.global_store = global_store if not global_store: self.store = {} self.pseudo_dirs = [""]
@property def _fs_token(self): if self.global_store: return super()._fs_token return tokenize(super()._fs_token, id(self))
def __reduce__(self): reduced = super().__reduce__() if self.global_store: return reduced factory, (cls, args, kwargs) = reduced # Restore into a new instance even when the source is cached. kwargs = {**kwargs, "skip_instance_cache": True} # Pickle's memo preserves the cycle through each MemoryFile.fs. return ( factory, (cls, args, kwargs), {"store": self.store, "pseudo_dirs": self.pseudo_dirs}, )
@classmethod def _strip_protocol(cls, path): if isinstance(path, PurePath): if isinstance(path, PureWindowsPath): return LocalFileSystem._strip_protocol(path) else: path = stringify_path(path)
path = path.removeprefix("memory://") if "::" in path or "://" in path: return path.rstrip("/") path = path.lstrip("/").rstrip("/") return "/" + path if path else ""
def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): # The base implementation calls ls() once per directory, and each ls() # scans the whole store, giving O(n_dirs * n_entries) behaviour # for a tree. Since the store is a flat mapping of every path, the same # result can be produced with a single pass over it. if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1") path = self._strip_protocol(path) if path in self.store: # path is itself a file if not detail: return [path] filelike = self.store[path] return { path: { "name": path, "size": filelike.size, "type": "file", "created": filelike.created.timestamp(), } }
# Uniform prefix so that the search root "" (the filesystem root) and a # nested path are handled the same way; rel depth is rel.count("/") + 1. prefix = path + "/" if path else "/" out = {} dirs = {}
def add_ancestor_dirs(name): # Register every directory implied between ``path`` and ``name`` that # is within maxdepth, mirroring how walk() surfaces implied dirs. idx = name.rfind("/") while idx > len(path): parent = name[:idx] if parent in dirs: break rel = parent[len(prefix) :] if maxdepth is None or rel.count("/") + 1 <= maxdepth: dirs[parent] = {"name": parent, "size": 0, "type": "directory"} idx = parent.rfind("/")
# `store` may be shared by multiple MemoryFileSystem instances, so iterate a # snapshot: a concurrent create/delete would otherwise raise # "dictionary changed size during iteration". ls() does the same. for name, filelike in tuple(self.store.items()): if not name.startswith(prefix): continue rel = name[len(prefix) :] if withdirs: add_ancestor_dirs(name) if maxdepth is not None and rel.count("/") + 1 > maxdepth: continue out[name] = { "name": name, "size": filelike.size, "type": "file", "created": filelike.created.timestamp(), }
if withdirs: # Explicitly-created (possibly empty) directories live in pseudo_dirs. for pdir in self.pseudo_dirs: if pdir and pdir.startswith(prefix): add_ancestor_dirs(pdir + "/") out.update(dirs) # Mirror the base find(): include the search root itself when it is # a directory (needed for posix glob compliance). if path != "" and self.isdir(path): out[path] = self.info(path)
names = sorted(out) return {name: out[name] for name in names} if detail else names
def ls(self, path, detail=True, **kwargs): path = self._strip_protocol(path) if path in self.store: # there is a key with this exact name if not detail: return [path] return [ { "name": path, "size": self.store[path].size, "type": "file", "created": self.store[path].created.timestamp(), } ] paths = set() starter = path + "/" out = [] for p2 in tuple(self.store): if p2.startswith(starter): if "/" not in p2[len(starter) :]: # exact child out.append( { "name": p2, "size": self.store[p2].size, "type": "file", "created": self.store[p2].created.timestamp(), } ) elif len(p2) > len(starter): # implied child directory ppath = starter + p2[len(starter) :].split("/", 1)[0] if ppath not in paths: out = out or [] out.append( { "name": ppath, "size": 0, "type": "directory", } ) paths.add(ppath) for p2 in self.pseudo_dirs: if p2.startswith(starter): if "/" not in p2[len(starter) :]: # exact child pdir if p2 not in paths: out.append({"name": p2, "size": 0, "type": "directory"}) paths.add(p2) else: # directory implied by deeper pdir ppath = starter + p2[len(starter) :].split("/", 1)[0] if ppath not in paths: out.append({"name": ppath, "size": 0, "type": "directory"}) paths.add(ppath) if not out: if path in self.pseudo_dirs: # empty dir return [] raise FileNotFoundError(path) if detail: return out return sorted([f["name"] for f in out])
def mkdir(self, path, create_parents=True, **kwargs): path = self._strip_protocol(path) if path in self.store or path in self.pseudo_dirs: raise FileExistsError(path) if self._parent(path).strip("/") and self.isfile(self._parent(path)): raise NotADirectoryError(self._parent(path)) if not create_parents and not self.isdir(self._parent(path)): raise FileNotFoundError(self._parent(path)) if create_parents and self._parent(path).strip("/"): try: self.mkdir(self._parent(path), create_parents, **kwargs) except FileExistsError: pass if path and path not in self.pseudo_dirs: self.pseudo_dirs.append(path)
def makedirs(self, path, exist_ok=False): try: self.mkdir(path, create_parents=True) except FileExistsError: if not exist_ok or self.isfile(path): raise
def pipe_file(self, path, value, mode="overwrite", **kwargs): """Set the bytes of given file
Avoids copies of the data if possible """ mode = "xb" if mode == "create" else "wb" self.open(path, mode=mode, data=value)
def rmdir(self, path): path = self._strip_protocol(path) if path == "": # silently avoid deleting FS root return if path in self.pseudo_dirs: if not self.ls(path): self.pseudo_dirs.remove(path) else: raise OSError(ENOTEMPTY, "Directory not empty", path) else: raise FileNotFoundError(path)
def info(self, path, **kwargs): logger.debug("info: %s", path) path = self._strip_protocol(path) if path in self.pseudo_dirs or any( p.startswith(path + "/") for p in list(self.store) + self.pseudo_dirs ): return { "name": path, "size": 0, "type": "directory", } elif path in self.store: filelike = self.store[path] return { "name": path, "size": filelike.size, "type": "file", "created": filelike.created.timestamp(), } else: raise FileNotFoundError(path)
def _open( self, path, mode="rb", block_size=None, autocommit=True, cache_options=None, **kwargs, ): if mode in {"rb+", "wb+", "ab+", "xb+"}: mode = mode[0] + "+b" path = self._strip_protocol(path) if "x" in mode and self.exists(path): raise FileExistsError if path in self.pseudo_dirs or ( path not in self.store and any(p.startswith(path + "/") for p in self.store) ): raise IsADirectoryError(path) parent = path while len(parent) > 1: parent = self._parent(parent) if self.isfile(parent): raise FileExistsError(parent) if mode in ["rb", "ab", "r+b", "a+b"]: if path in self.store: f = self.store[path] if self._intrans and "a" in mode: # append to a copy so the store is unchanged until commit f = MemoryFile(self, path, f.getvalue()) f.created = self.store[path].created if "a" in mode: # position at the end of file f.seek(0, 2) else: # position at the beginning of file f.seek(0) return f elif "a" in mode: # append modes create the file if it does not exist, matching # builtin open() and LocalFileSystem m = MemoryFile(self, path, kwargs.get("data")) if not self._intrans: m.commit() # position at the end of file, like the existing-file path above m.seek(0, 2) return m else: raise FileNotFoundError(path) elif mode in {"wb", "w+b", "xb", "x+b"}: if "x" in mode and self.exists(path): raise FileExistsError m = MemoryFile(self, path, kwargs.get("data")) if not self._intrans: m.commit() return m else: name = self.__class__.__name__ raise ValueError(f"unsupported file mode for {name}: {mode!r}")
def cp_file(self, path1, path2, **kwargs): path1 = self._strip_protocol(path1) path2 = self._strip_protocol(path2) source_is_file = self.isfile(path1) if not source_is_file and not self.isdir(path1): raise FileNotFoundError(path1) parent = path2 while len(parent) > 1: parent = self._parent(parent) if self.isfile(parent): raise FileExistsError(parent) if source_is_file: if self.isdir(path2): raise IsADirectoryError(path2) self.store[path2] = MemoryFile( self, path2, self.store[path1].getvalue() ) # implicit copy else: if self.isfile(path2): raise FileExistsError(path2) if path2 not in self.pseudo_dirs: self.pseudo_dirs.append(path2)
def cat_file(self, path, start=None, end=None, **kwargs): logger.debug("cat: %s", path) path = self._strip_protocol(path) try: return bytes(self.store[path].getbuffer()[start:end]) except KeyError as e: raise FileNotFoundError(path) from e
def _rm(self, path): path = self._strip_protocol(path) try: del self.store[path] except KeyError as e: raise FileNotFoundError(path) from e
def modified(self, path): path = self._strip_protocol(path) try: return self.store[path].modified except KeyError as e: raise FileNotFoundError(path) from e
def created(self, path): path = self._strip_protocol(path) try: return self.store[path].created except KeyError as e: raise FileNotFoundError(path) from e
def isfile(self, path): path = self._strip_protocol(path) return path in self.store
def rm(self, path, recursive=False, maxdepth=None): if isinstance(path, str): path = self._strip_protocol(path) else: path = [self._strip_protocol(p) for p in path] paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) # A non-recursive expand keeps a literal path whether or not it exists, # so record what exists before anything is deleted. existed = {p for p in paths if self.exists(p)} for p in reversed(paths): if self.isfile(p): self.rm_file(p) elif not self.exists(p): # A directory that is not in self.pseudo_dirs only exists while it # has files under it, so deleting those files earlier in this loop # makes it vanish. That is expected; a path that never existed is # not, and raises like rm_file and the other filesystems do. if p not in existed: raise FileNotFoundError(p) continue elif maxdepth is not None and self.ls(p, detail=False): # a directory still holding files deeper than maxdepth is kept continue else: self.rmdir(p)
class MemoryFile(BytesIO): """A BytesIO which can't close and works as a context manager
Can initialise with data. Each path should only be active once at any moment.
No need to provide fs, path if auto-committing (default) """
def __init__(self, fs=None, path=None, data=None): logger.debug("open file %s", path) self.fs = fs self.path = path self.created = datetime.now(tz=timezone.utc) self.modified = datetime.now(tz=timezone.utc) if data: super().__init__(data) self.seek(0)
@property def size(self): return self.getbuffer().nbytes
def write(self, data): written = super().write(data) if written: self.modified = datetime.now(tz=timezone.utc) return written
def writelines(self, lines): for line in lines: self.write(line)
def truncate(self, size=None): size = super().truncate(size) self.modified = datetime.now(tz=timezone.utc) return size
def __enter__(self): return self
def close(self): pass
def discard(self): pass
def commit(self): self.fs.store[self.path] = self self.modified = datetime.now(tz=timezone.utc)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387import base64import collectionsimport ioimport itertoolsimport loggingimport mathimport osfrom functools import lru_cachefrom itertools import chainfrom typing import TYPE_CHECKING, Literal
import fsspec.corefrom fsspec.spec import AbstractBufferedFile
try: import ujson as jsonexcept ImportError: if not TYPE_CHECKING: import json
from fsspec.asyn import AsyncFileSystemfrom fsspec.callbacks import DEFAULT_CALLBACKfrom fsspec.core import filesystem, open, split_protocolfrom fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapperfrom fsspec.utils import ( check_contained, isfilelike, merge_offset_ranges, other_paths,)
logger = logging.getLogger("fsspec.reference")
class ReferenceNotReachable(RuntimeError): def __init__(self, reference, target, *args): super().__init__(*args) self.reference = reference self.target = target
def __str__(self): return f'Reference "{self.reference}" failed to fetch target {self.target}'
def _first(d): return next(iter(d.values()))
def _inline_data(part): """The bytes an inline (in-memory) reference delivers to a reader.
A ``base64:`` prefix marks base64-encoded content; other text is encoded as UTF-8. ``info`` and ``ls`` measure the result of this rather than the stored form, so that a size always matches what ``cat`` returns. """ if isinstance(part, (str, bytes)): return _decode_inline(part) if hasattr(part, "to_bytes"): part = part.to_bytes() return _decode_inline(part)
@lru_cache(maxsize=1024)def _decode_inline(part): """Decode a stored inline part once and stash the result.
The same inline value is decoded for ``cat`` and again for the length check in ``info``/``ls``; caching avoids repeating the work for every listing. Inline references are small and few, so a bounded cache is enough. """ if isinstance(part, str): part = part.encode() if part.startswith(b"base64:"): return base64.b64decode(part[7:]) return part
def _prot_in_references(path, references): ref = references.get(path) if isinstance(ref, (list, tuple)) and isinstance(ref[0], str): return split_protocol(ref[0])[0] if ref[0] else ref[0]
def _protocol_groups(paths, references): if isinstance(paths, str): return {_prot_in_references(paths, references): [paths]} out = {} for path in paths: protocol = _prot_in_references(path, references) out.setdefault(protocol, []).append(path) return out
class RefsValuesView(collections.abc.ValuesView): def __iter__(self): for val in self._mapping.zmetadata.values(): yield json.dumps(val).encode() yield from self._mapping._items.values() for field in self._mapping.listdir(): chunk_sizes = self._mapping._get_chunk_sizes(field) if len(chunk_sizes) == 0: yield self._mapping[field + "/0"] continue yield from self._mapping._generate_all_records(field)
class RefsItemsView(collections.abc.ItemsView): def __iter__(self): return zip(self._mapping.keys(), self._mapping.values())
def ravel_multi_index(idx, sizes): val = 0 mult = 1 for i, s in zip(idx[::-1], sizes[::-1]): val += i * mult mult *= s return val
class LazyReferenceMapper(collections.abc.MutableMapping): """This interface can be used to read/write references from Parquet stores. It is not intended for other types of references. It can be used with Kerchunk's MultiZarrToZarr method to combine references into a parquet store. Examples of this use-case can be found here: https://fsspec.github.io/kerchunk/advanced.html?highlight=parquet#parquet-storage"""
# import is class level to prevent numpy dep requirement for fsspec @property def np(self): import numpy as np
return np
@property def pd(self): import pandas as pd
return pd
def __init__( self, root, fs=None, out_root=None, cache_size=128, categorical_threshold=10, engine: Literal["fastparquet", "pyarrow"] = "fastparquet", ): """
This instance will be writable, storing changes in memory until full partitions are accumulated or .flush() is called.
To create an empty lazy store, use .create()
Parameters ---------- root : str Root of parquet store fs : fsspec.AbstractFileSystem fsspec filesystem object, default is local filesystem. cache_size : int, default=128 Maximum size of LRU cache, where cache_size*record_size denotes the total number of references that can be loaded in memory at once. categorical_threshold : int Encode urls as pandas.Categorical to reduce memory footprint if the ratio of the number of unique urls to total number of refs for each variable is greater than or equal to this number. (default 10) engine: Literal["fastparquet","pyarrow"] Engine choice for reading parquet files. (default is "fastparquet") """
self.root = root self.chunk_sizes = {} self.cat_thresh = categorical_threshold self.engine = engine self.cache_size = cache_size self.url = self.root + "/{field}/refs.{record}.parq" # TODO: derive fs from `root` self.fs = fsspec.filesystem("file") if fs is None else fs self.out_root = self.fs.unstrip_protocol(out_root or self.root)
from importlib.util import find_spec
if self.engine == "pyarrow" and find_spec("pyarrow") is None: raise ImportError("engine choice `pyarrow` is not installed.")
# Apply `lru_cache` decorator manually per instance. # This way `self` reference is not held on class level. # WARNING: However, this means that self and its members are not reflected # in the cache key, so we expect they won't be mutated once a value is cached. self.listdir = lru_cache()(self.listdir) self._key_to_record = lru_cache(maxsize=4096)(self._key_to_record)
def __getattr__(self, item): if item in ("_items", "record_size", "zmetadata"): self.setup() # avoid possible recursion if setup fails somehow return self.__dict__[item] raise AttributeError(item)
def setup(self): self._items = {} self._items[".zmetadata"] = self.fs.cat_file( "/".join([self.root, ".zmetadata"]) ) met = json.loads(self._items[".zmetadata"]) self.record_size = met["record_size"] self.zmetadata = met["metadata"]
# Define function to open and decompress refs @lru_cache(maxsize=self.cache_size) def open_refs(field, record): """cached parquet file loader""" path = self.url.format(field=field, record=record) data = io.BytesIO(self.fs.cat_file(path)) try: df = self.pd.read_parquet(data, engine=self.engine) refs = {c: df[c].to_numpy(copy=True) for c in df.columns} except OSError: refs = None return refs
self.open_refs = open_refs
@staticmethod def create(root, storage_options=None, fs=None, record_size=10000, **kwargs): """Make empty parquet reference set
First deletes the contents of the given directory, if it exists.
Parameters ---------- root: str Directory to contain the output; will be created storage_options: dict | None For making the filesystem to use for writing is fs is None fs: FileSystem | None Filesystem for writing record_size: int Number of references per parquet file kwargs: passed to __init__
Returns ------- LazyReferenceMapper instance """ met = {"metadata": {}, "record_size": record_size} if fs is None: fs, root = fsspec.core.url_to_fs(root, **(storage_options or {})) if fs.exists(root): fs.rm(root, recursive=True) fs.makedirs(root, exist_ok=True) fs.pipe("/".join([root, ".zmetadata"]), json.dumps(met).encode()) return LazyReferenceMapper(root, fs, **kwargs)
def listdir(self): """List top-level directories""" dirs = (p.rsplit("/", 1)[0] for p in self.zmetadata if not p.startswith(".z")) return set(dirs)
def ls(self, path="", detail=True): """Shortcut file listings""" path = path.rstrip("/") pathdash = path + "/" if path else "" dirnames = self.listdir() dirs = [ d for d in dirnames if d.startswith(pathdash) and "/" not in d.lstrip(pathdash) ] if dirs: others = { f for f in chain( [".zmetadata"], (name for name in self.zmetadata), (name for name in self._items), ) if f.startswith(pathdash) and "/" not in f.lstrip(pathdash) } if detail is False: others.update(dirs) return sorted(others) dirinfo = [{"name": name, "type": "directory", "size": 0} for name in dirs] fileinfo = [ { "name": name, "type": "file", "size": len( json.dumps(self.zmetadata[name]) if name in self.zmetadata else self._items[name] ), } for name in others ] return sorted(dirinfo + fileinfo, key=lambda s: s["name"]) field = path others = set( [name for name in self.zmetadata if name.startswith(f"{path}/")] + [name for name in self._items if name.startswith(f"{path}/")] ) fileinfo = [ { "name": name, "type": "file", "size": len( json.dumps(self.zmetadata[name]) if name in self.zmetadata else self._items[name] ), } for name in others ] keys = self._keys_in_field(field)
if detail is False: return list(others) + list(keys) recs = self._generate_all_records(field) recinfo = [ {"name": name, "type": "file", "size": rec[-1]} for name, rec in zip(keys, recs) if rec[0] # filters out path==None, deleted/missing ] return fileinfo + recinfo
def _load_one_key(self, key): """Get the reference for one key
Returns bytes, one-element list or three-element list. """ if key in self._items: return self._items[key] elif key in self.zmetadata: return json.dumps(self.zmetadata[key]).encode() elif "/" not in key or self._is_meta(key): raise KeyError(key) field, _ = key.rsplit("/", 1) record, ri, chunk_size = self._key_to_record(key) maybe = self._items.get((field, record), {}).get(ri, False) if maybe is None: # explicitly deleted raise KeyError elif maybe: return maybe elif chunk_size == 0: return b""
# Chunk keys can be loaded from row group and cached in LRU cache try: refs = self.open_refs(field, record) except (ValueError, TypeError, FileNotFoundError) as exc: raise KeyError(key) from exc columns = ["path", "offset", "size", "raw"] selection = [refs[c][ri] if c in refs else None for c in columns] raw = selection[-1] if raw is not None: return raw if selection[0] is None: raise KeyError("This reference does not exist or has been deleted") if selection[1:3] == [0, 0]: # URL only return selection[:1] # URL, offset, size return selection[:3]
def _key_to_record(self, key): """Details needed to construct a reference for one key""" field, chunk = key.rsplit("/", 1) chunk_sizes = self._get_chunk_sizes(field) if len(chunk_sizes) == 0: return 0, 0, 0 chunk_idx = [int(c) for c in chunk.split(".")] chunk_number = ravel_multi_index(chunk_idx, chunk_sizes) record = chunk_number // self.record_size ri = chunk_number % self.record_size return record, ri, len(chunk_sizes)
def _get_chunk_sizes(self, field): """The number of chunks along each axis for a given field""" if field not in self.chunk_sizes: zarray = self.zmetadata[f"{field}/.zarray"] size_ratio = [ math.ceil(s / c) for s, c in zip(zarray["shape"], zarray["chunks"]) ] self.chunk_sizes[field] = size_ratio or [1] return self.chunk_sizes[field]
def _generate_record(self, field, record): """The references for a given parquet file of a given field""" refs = self.open_refs(field, record) it = iter(zip(*refs.values())) if len(refs) == 3: # All urls return (list(t) for t in it) elif len(refs) == 1: # All raws return refs["raw"] else: # Mix of urls and raws return (list(t[:3]) if not t[3] else t[3] for t in it)
def _generate_all_records(self, field): """Load all the references within a field by iterating over the parquet files""" nrec = 1 for ch in self._get_chunk_sizes(field): nrec *= ch nrec = math.ceil(nrec / self.record_size) for record in range(nrec): yield from self._generate_record(field, record)
def values(self): return RefsValuesView(self)
def items(self): return RefsItemsView(self)
def __hash__(self): return id(self)
def __getitem__(self, key): return self._load_one_key(key)
def __setitem__(self, key, value): if "/" in key and not self._is_meta(key): field, chunk = key.rsplit("/", 1) record, i, _ = self._key_to_record(key) subdict = self._items.setdefault((field, record), {}) subdict[i] = value if len(subdict) == self.record_size: self.write(field, record) else: # metadata or top-level if hasattr(value, "to_bytes"): val = value.to_bytes().decode() elif isinstance(value, bytes): val = value.decode() else: val = value self._items[key] = val new_value = json.loads(val) self.zmetadata[key] = {**self.zmetadata.get(key, {}), **new_value}
@staticmethod def _is_meta(key): return key.startswith(".z") or "/.z" in key
def __delitem__(self, key): if key in self._items: del self._items[key] elif key in self.zmetadata: del self.zmetadata[key] else: if "/" in key and not self._is_meta(key): field, _ = key.rsplit("/", 1) record, i, _ = self._key_to_record(key) subdict = self._items.setdefault((field, record), {}) subdict[i] = None if len(subdict) == self.record_size: self.write(field, record) else: # metadata or top-level self._items[key] = None
def write(self, field, record, base_url=None, storage_options=None): # extra requirements if writing import kerchunk.df import numpy as np import pandas as pd
partition = self._items[(field, record)] original = False if len(partition) < self.record_size: try: original = self.open_refs(field, record) except OSError: pass
if original: paths = original["path"] offsets = original["offset"] sizes = original["size"] raws = original["raw"] else: paths = np.full(self.record_size, np.nan, dtype="O") offsets = np.zeros(self.record_size, dtype="int64") sizes = np.zeros(self.record_size, dtype="int64") raws = np.full(self.record_size, np.nan, dtype="O") for j, data in partition.items(): if isinstance(data, list): if ( str(paths.dtype) == "category" and data[0] not in paths.dtype.categories ): paths = paths.add_categories(data[0]) paths[j] = data[0] if len(data) > 1: offsets[j] = data[1] sizes[j] = data[2] elif data is None: # delete paths[j] = None offsets[j] = 0 sizes[j] = 0 raws[j] = None else: # this is the only call into kerchunk, could remove raws[j] = kerchunk.df._proc_raw(data) # TODO: only save needed columns df = pd.DataFrame( { "path": paths, "offset": offsets, "size": sizes, "raw": raws, }, copy=False, ) if df.path.count() / (df.path.nunique() or 1) > self.cat_thresh: df["path"] = df["path"].astype("category") object_encoding = {"raw": "bytes", "path": "utf8"} has_nulls = ["path", "raw"]
fn = f"{base_url or self.out_root}/{field}/refs.{record}.parq" self.fs.mkdirs(f"{base_url or self.out_root}/{field}", exist_ok=True)
if self.engine == "pyarrow": df_backend_kwargs = {"write_statistics": False} elif self.engine == "fastparquet": df_backend_kwargs = { "stats": False, "object_encoding": object_encoding, "has_nulls": has_nulls, } else: raise NotImplementedError(f"{self.engine} not supported") df.to_parquet( fn, engine=self.engine, storage_options=storage_options or getattr(self.fs, "storage_options", None), compression="zstd", index=False, **df_backend_kwargs, )
partition.clear() self._items.pop((field, record))
def flush(self, base_url=None, storage_options=None): """Output any modified or deleted keys
Parameters ---------- base_url: str Location of the output """
# write what we have so far and clear sub chunks for thing in list(self._items): if isinstance(thing, tuple): field, record = thing self.write( field, record, base_url=base_url, storage_options=storage_options, )
# gather .zmetadata from self._items and write that too for k in list(self._items): if k != ".zmetadata" and ".z" in k: self.zmetadata[k] = json.loads(self._items.pop(k)) met = {"metadata": self.zmetadata, "record_size": self.record_size} self._items.clear() self._items[".zmetadata"] = json.dumps(met).encode() self.fs.pipe( "/".join([base_url or self.out_root, ".zmetadata"]), self._items[".zmetadata"], )
# TODO: only clear those that we wrote to? self.open_refs.cache_clear()
def __len__(self): # Caveat: This counts expected references, not actual - but is fast count = 0 for field in self.listdir(): if field.startswith("."): count += 1 else: count += math.prod(self._get_chunk_sizes(field)) count += len(self.zmetadata) # all metadata keys # any other files not in reference partitions count += sum(1 for _ in self._items if not isinstance(_, tuple)) return count
def __iter__(self): # Caveat: returns only existing keys, so the number of these does not # match len(self) metas = set(self.zmetadata) metas.update(self._items) for bit in metas: if isinstance(bit, str): yield bit for field in self.listdir(): for k in self._keys_in_field(field): if k in self: yield k
def __contains__(self, item): try: self._load_one_key(item) return True except KeyError: return False
def _keys_in_field(self, field): """List key names in given field
Produces strings like "field/x.y" appropriate from the chunking of the array """ chunk_sizes = self._get_chunk_sizes(field) if len(chunk_sizes) == 0: yield field + "/0" return inds = itertools.product(*(range(i) for i in chunk_sizes)) for ind in inds: yield field + "/" + ".".join([str(c) for c in ind])
class ReferenceFileSystem(AsyncFileSystem): """View byte ranges of some other file as a file system Initial version: single file system target, which must support async, and must allow start and end args in _cat_file. Later versions may allow multiple arbitrary URLs for the targets. This FileSystem is read-only. It is designed to be used with async targets (for now). We do not get original file details from the target FS. Configuration is by passing a dict of references at init, or a URL to a JSON file containing the same; this dict can also contain concrete data for some set of paths. Reference dict format: {path0: bytes_data, path1: (target_url, offset, size)} https://github.com/fsspec/kerchunk/blob/main/README.md
simple_references: if True (default), no jinja interpreting is done, which is the safe option. """
protocol = "reference" cachable = False
def __init__( self, fo, target=None, ref_storage_args=None, target_protocol=None, target_options=None, remote_protocol=None, remote_options=None, fs=None, template_overrides=None, simple_templates=True, max_gap=64_000, max_block=256_000_000, cache_size=128, **kwargs, ): """ Parameters ---------- fo : dict or str The set of references to use for this instance, with a structure as above. If str referencing a JSON file, will use fsspec.open, in conjunction with target_options and target_protocol to open and parse JSON at this location. If a directory, then assume references are a set of parquet files to be loaded lazily. target : str For any references having target_url as None, this is the default file target to use ref_storage_args : dict If references is a str, use these kwargs for loading the JSON file. Deprecated: use target_options instead. target_protocol : str Used for loading the reference file, if it is a path. If None, protocol will be derived from the given path target_options : dict Extra FS options for loading the reference file ``fo``, if given as a path remote_protocol : str The protocol of the filesystem on which the references will be evaluated (unless fs is provided). If not given, will be derived from the first URL that has a protocol in the templates or in the references, in that order. remote_options : dict kwargs to go with remote_protocol fs : AbstractFileSystem | dict(str, (AbstractFileSystem | dict)) Directly provide a file system(s): - a single filesystem instance - a dict of protocol:filesystem, where each value is either a filesystem instance, or a dict of kwargs that can be used to create in instance for the given protocol
If this is given, remote_options and remote_protocol are ignored. template_overrides : dict Swap out any templates in the references file with these - useful for testing. simple_templates: bool Whether templates can be processed with simple replace (True) or if jinja is needed (False, much slower). All reference sets produced by ``kerchunk`` are simple in this sense, but the spec allows for complex. max_gap, max_block: int For merging multiple concurrent requests to the same remote file. Neighboring byte ranges will only be merged when their inter-range gap is <= ``max_gap``. Default is 64KB. Set to 0 to only merge when it requires no extra bytes. Pass a negative number to disable merging, appropriate for local target files. Neighboring byte ranges will only be merged when the size of the aggregated range is <= ``max_block``. Default is 256MB. cache_size : int Maximum size of LRU cache, where cache_size*record_size denotes the total number of references that can be loaded in memory at once. Only used for lazily loaded references. kwargs : passed to parent class """ super().__init__(**kwargs) self.target = target self.template_overrides = template_overrides self.simple_templates = simple_templates self.templates = {} self.fss = {} self._dircache = {} self.max_gap = max_gap self.max_block = max_block if isinstance(fo, str): dic = dict( **(ref_storage_args or target_options or {}), protocol=target_protocol ) ref_fs, fo2 = fsspec.core.url_to_fs(fo, **dic) if ".json" not in fo2 and ( fo.endswith(("parq", "parquet", "/")) or ref_fs.isdir(fo2) ): # Lazy parquet refs logger.info("Open lazy reference dict from URL %s", fo) self.references = LazyReferenceMapper( fo2, fs=ref_fs, cache_size=cache_size, ) else: # text JSON with fsspec.open(fo, "rb", **dic) as f: logger.info("Read reference from URL %s", fo) text = json.load(f) self._process_references(text, template_overrides) else: # dictionaries self._process_references(fo, template_overrides) if isinstance(fs, dict): self.fss = { k: ( fsspec.filesystem(k.split(":", 1)[0], **opts) if isinstance(opts, dict) else opts ) for k, opts in fs.items() } if None not in self.fss: self.fss[None] = filesystem("file") return if fs is not None: # single remote FS remote_protocol = ( fs.protocol[0] if isinstance(fs.protocol, tuple) else fs.protocol ) self.fss[remote_protocol] = fs
if remote_protocol is None: # get single protocol from any templates for ref in self.templates.values(): if callable(ref): ref = ref() protocol, _ = fsspec.core.split_protocol(ref) if protocol and protocol not in self.fss: fs = filesystem(protocol, **(remote_options or {})) self.fss[protocol] = fs if remote_protocol is None: # get single protocol from references # TODO: warning here, since this can be very expensive? for ref in self.references.values(): if callable(ref): ref = ref() if isinstance(ref, list) and ref[0]: protocol, _ = fsspec.core.split_protocol(ref[0]) if protocol not in self.fss: fs = filesystem(protocol, **(remote_options or {})) self.fss[protocol] = fs # only use first remote URL break
if remote_protocol and remote_protocol not in self.fss: fs = filesystem(remote_protocol, **(remote_options or {})) self.fss[remote_protocol] = fs
self.fss[None] = fs or filesystem("file") # default one # Wrap any non-async filesystems to ensure async methods are available below for k, f in self.fss.items(): if not f.async_impl: self.fss[k] = AsyncFileSystemWrapper(f, asynchronous=self.asynchronous) elif self.asynchronous ^ f.asynchronous: raise ValueError( "Reference-FS's target filesystem must have same value " "of asynchronous" )
def _cat_common(self, path, start=None, end=None): path = self._strip_protocol(path) logger.debug(f"cat: {path}") try: part = self.references[path] except KeyError as exc: raise FileNotFoundError(path) from exc if isinstance(part, str): part = part.encode() if hasattr(part, "to_bytes"): part = part.to_bytes() if isinstance(part, bytes): logger.debug(f"Reference: {path}, type bytes") return _inline_data(part), None, None
if len(part) == 1: logger.debug(f"Reference: {path}, whole file => {part}") url = part[0] start1, end1 = start, end else: url, start0, size = part logger.debug(f"Reference: {path} => {url}, offset {start0}, size {size}") end0 = start0 + size
# Resolve offsets like slicing the part, so they never reach target # bytes outside the referenced range. if start is not None: if start >= 0: start1 = min(start0 + start, end0) else: start1 = max(end0 + start, start0) else: start1 = start0 if end is not None: if end >= 0: end1 = min(start0 + end, end0) else: end1 = max(end0 + end, start0) else: end1 = end0 if url is None: url = self.target return url, start1, end1
async def _cat_file(self, path, start=None, end=None, **kwargs): part_or_url, start0, end0 = self._cat_common(path, start=start, end=end) if isinstance(part_or_url, bytes): return part_or_url[start:end] protocol, _ = split_protocol(part_or_url) try: return await self.fss[protocol]._cat_file( part_or_url, start=start0, end=end0 ) except Exception as e: raise ReferenceNotReachable(path, part_or_url) from e
def cat_file(self, path, start=None, end=None, **kwargs): part_or_url, start0, end0 = self._cat_common(path, start=start, end=end) if isinstance(part_or_url, bytes): return part_or_url[start:end] protocol, _ = split_protocol(part_or_url) try: return self.fss[protocol].cat_file(part_or_url, start=start0, end=end0) except Exception as e: raise ReferenceNotReachable(path, part_or_url) from e
def pipe_file(self, path, value, **_): """Temporarily add binary data or reference as a file""" self.references[path] = value
async def _get_file(self, rpath, lpath, **kwargs): if self.isdir(rpath): return os.makedirs(lpath, exist_ok=True) data = await self._cat_file(rpath) with open(lpath, "wb") as f: f.write(data)
def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, **kwargs): if self.isdir(rpath): return os.makedirs(lpath, exist_ok=True) data = self.cat_file(rpath, **kwargs) callback.set_size(len(data)) if isfilelike(lpath): lpath.write(data) else: with open(lpath, "wb") as f: f.write(data) callback.absolute_update(len(data))
def get(self, rpath, lpath, recursive=False, maxdepth=None, **kwargs): if recursive: # trigger directory build self.ls("") rpath = self.expand_path(rpath, recursive=recursive, maxdepth=maxdepth) fs = fsspec.filesystem("file", auto_mkdir=True) targets = other_paths(rpath, lpath) if isinstance(lpath, str): # The names came from the source listing; ".." in one of them # would otherwise place the copy above the destination. When # lpath is a list the caller named every destination itself. check_contained(lpath, targets) if recursive: data = self.cat([r for r in rpath if not self.isdir(r)]) else: data = self.cat(rpath) for remote, local in zip(rpath, targets): if remote in data: fs.pipe_file(local, data[remote])
def cat(self, path, recursive=False, on_error="raise", **kwargs): if isinstance(path, str) and recursive: raise NotImplementedError if isinstance(path, list) and (recursive or any("*" in p for p in path)): raise NotImplementedError # TODO: if references is lazy, pre-fetch all paths in batch before access proto_dict = _protocol_groups(path, self.references) out = {} for proto, paths in proto_dict.items(): fs = self.fss[proto] urls, starts, ends, valid_paths = [], [], [], [] for p in paths: # find references or label not-found. Early exit if any not # found and on_error is "raise" try: u, s, e = self._cat_common(p) if not isinstance(u, (bytes, str)): # nan/None from parquet continue except FileNotFoundError as err: if on_error == "raise": raise if on_error != "omit": out[p] = err else: urls.append(u) starts.append(s) ends.append(e) valid_paths.append(p)
# process references into form for merging urls2 = [] starts2 = [] ends2 = [] paths2 = [] whole_files = set() for u, s, e, p in zip(urls, starts, ends, valid_paths): if isinstance(u, bytes): # data out[p] = u elif s is None: # whole file - limits are None, None, but no further # entries take for this file whole_files.add(u) urls2.append(u) starts2.append(s) ends2.append(e) paths2.append(p) for u, s, e, p in zip(urls, starts, ends, valid_paths): # second run to account for files that are to be loaded whole if s is not None and u not in whole_files: urls2.append(u) starts2.append(s) ends2.append(e) paths2.append(p)
# merge and fetch consolidated ranges new_paths, new_starts, new_ends = merge_offset_ranges( list(urls2), list(starts2), list(ends2), sort=True, max_gap=self.max_gap, max_block=self.max_block, ) bytes_out = fs.cat_ranges(new_paths, new_starts, new_ends)
# unbundle from merged bytes - simple approach for u, s, e, p in zip(urls, starts, ends, valid_paths): if p in out: continue # was bytes, already handled for np, ns, ne, b in zip(new_paths, new_starts, new_ends, bytes_out): if np == u and (ns is None or ne is None): if isinstance(b, Exception): out[p] = b else: out[p] = b[s:e] elif np == u and s >= ns and e <= ne: if isinstance(b, Exception): out[p] = b else: out[p] = b[s - ns : (e - ne) or None]
for k, v in out.copy().items(): # these were valid references, but fetch failed, so transform exc if isinstance(v, Exception) and k in self.references: ex = out[k] new_ex = ReferenceNotReachable(k, self.references[k]) new_ex.__cause__ = ex if on_error == "raise": raise new_ex elif on_error != "omit": out[k] = new_ex else: del out[k]
if len(out) == 1 and isinstance(path, str) and "*" not in path: return _first(out) return out
def _process_references(self, references, template_overrides=None): vers = references.get("version", None) if vers is None: self._process_references0(references) elif vers == 1: self._process_references1(references, template_overrides=template_overrides) else: raise ValueError(f"Unknown reference spec version: {vers}") # TODO: we make dircache by iterating over all entries, but for Spec >= 1, # can replace with programmatic. Is it even needed for mapper interface?
def _process_references0(self, references): """Make reference dict for Spec Version 0""" if isinstance(references, dict): # do not do this for lazy/parquet backend, which will not make dicts, # but must remain writable in the original object references = { key: json.dumps(val) if isinstance(val, dict) else val for key, val in references.items() } self.references = references
def _process_references1(self, references, template_overrides=None): if not self.simple_templates or self.templates: import jinja2.sandbox self.references = {} self._process_templates(references.get("templates", {}))
@lru_cache(1000) def _render_jinja(u): return ( jinja2.sandbox.SandboxedEnvironment() .from_string(u) .render(**self.templates) )
for k, v in references.get("refs", {}).items(): if isinstance(v, str): if v.startswith("base64:"): self.references[k] = base64.b64decode(v[7:]) self.references[k] = v elif isinstance(v, dict): self.references[k] = json.dumps(v) elif self.templates: u = v[0] if "{{" in u: if self.simple_templates: u = ( u.replace("{{", "{") .replace("}}", "}") .format(**self.templates) ) else: u = _render_jinja(u) self.references[k] = [u] if len(v) == 1 else [u, v[1], v[2]] else: self.references[k] = v self.references.update(self._process_gen(references.get("gen", [])))
def _process_templates(self, tmp): self.templates = {} if self.template_overrides is not None: tmp.update(self.template_overrides) for k, v in tmp.items(): if "{{" in v: import jinja2.sandbox
self.templates[k] = ( lambda temp=v, **kwargs: jinja2.sandbox.SandboxedEnvironment() .from_string(temp) .render(**kwargs) ) else: self.templates[k] = v
def _process_gen(self, gens): out = {} if self.simple_templates: return out for gen in gens: dimension = { k: ( v if isinstance(v, list) else range(v.get("start", 0), v["stop"], v.get("step", 1)) ) for k, v in gen["dimensions"].items() } products = ( dict(zip(dimension.keys(), values)) for values in itertools.product(*dimension.values()) ) for pr in products: import jinja2.sandbox
key = ( jinja2.sandbox.SandboxedEnvironment() .from_string(gen["key"]) .render(**pr, **self.templates) ) url = ( jinja2.sandbox.SandboxedEnvironment() .from_string(gen["url"]) .render(**pr, **self.templates) ) if ("offset" in gen) and ("length" in gen): offset = int( jinja2.sandbox.SandboxedEnvironment() .from_string(gen["offset"]) .render(**pr, **self.templates) ) length = int( jinja2.sandbox.SandboxedEnvironment() .from_string(gen["length"]) .render(**pr, **self.templates) ) out[key] = [url, offset, length] elif ("offset" in gen) ^ ("length" in gen): raise ValueError( "Both 'offset' and 'length' are required for a " "reference generator entry if either is provided." ) else: out[key] = [url] return out
def _dircache_from_items(self): self.dircache = {"": []} it = self.references.items() for path, part in it: if isinstance(part, (bytes, str)) or hasattr(part, "to_bytes"): size = len(_inline_data(part)) elif len(part) == 1: size = None else: _, _, size = part par = path.rsplit("/", 1)[0] if "/" in path else "" par0 = par subdirs = [par0] while par0 and par0 not in self.dircache: # collect parent directories par0 = self._parent(par0) subdirs.append(par0)
subdirs.reverse() for parent, child in zip(subdirs, subdirs[1:]): # register newly discovered directories assert child not in self.dircache assert parent in self.dircache self.dircache[parent].append( {"name": child, "type": "directory", "size": 0} ) self.dircache[child] = []
self.dircache[par].append({"name": path, "type": "file", "size": size})
def _open(self, path, mode="rb", block_size=None, cache_options=None, **kwargs): part_or_url, start0, end0 = self._cat_common(path) # This logic is kept outside `ReferenceFile` to avoid unnecessary redirection. # That does mean `_cat_common` gets called twice if it eventually reaches `ReferenceFile`. if isinstance(part_or_url, bytes): return io.BytesIO(part_or_url[start0:end0])
protocol, _ = split_protocol(part_or_url) if start0 is None and end0 is None: return self.fss[protocol]._open( part_or_url, mode, block_size=block_size, cache_options=cache_options, **kwargs, )
return ReferenceFile( self, path, mode, block_size=block_size, cache_options=cache_options, **kwargs, )
def ls(self, path, detail=True, **kwargs): logger.debug("list %s", path) path = self._strip_protocol(path) if isinstance(self.references, LazyReferenceMapper): try: return self.references.ls(path, detail) except KeyError: pass raise FileNotFoundError(f"'{path}' is not a known key") if not self.dircache: self._dircache_from_items() out = self._ls_from_cache(path) if out is None: raise FileNotFoundError(path) if detail: return out return [o["name"] for o in out]
def exists(self, path, **kwargs): # overwrite auto-sync version return self.isdir(path) or self.isfile(path)
def isdir(self, path): # overwrite auto-sync version if self.dircache: return path in self.dircache elif isinstance(self.references, LazyReferenceMapper): return path in self.references.listdir() else: # this may be faster than building dircache for single calls, but # by looping will be slow for many calls; could cache it? return any(_.startswith(f"{path}/") for _ in self.references)
def isfile(self, path): # overwrite auto-sync version return path in self.references
async def _ls(self, path, detail=True, **kwargs): # calls fast sync code return self.ls(path, detail, **kwargs)
def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): if withdirs: return super().find( path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, **kwargs ) if path: path = self._strip_protocol(path) r = sorted(k for k in self.references if k.startswith(path)) else: r = sorted(self.references) if detail: if not self.dircache: self._dircache_from_items() return {k: self._ls_from_cache(k)[0] for k in r} else: return r
def info(self, path, **kwargs): out = self.references.get(path) if out is not None: if isinstance(out, (str, bytes)): return {"name": path, "type": "file", "size": len(_inline_data(out))} elif len(out) > 1: return {"name": path, "type": "file", "size": out[2]} else: out0 = [{"name": path, "type": "file", "size": None}] else: out = self.ls(path, True) out0 = [o for o in out if o["name"] == path] if not out0: return {"name": path, "type": "directory", "size": 0} if out0[0]["size"] is None: # if this is a whole remote file, update size using remote FS prot, _ = split_protocol(self.references[path][0]) out0[0]["size"] = self.fss[prot].size(self.references[path][0]) return out0[0]
async def _info(self, path, **kwargs): out = self.references.get(path) if isinstance(out, (list, tuple)) and len(out) == 1: # whole remote file: the size must come from the remote FS, which # cannot be called synchronously from inside the event loop prot, _ = split_protocol(out[0]) fs = self.fss[prot] if fs.async_impl: size = await fs._size(out[0]) else: size = fs.size(out[0]) return {"name": path, "type": "file", "size": size} return self.info(path) # calls fast sync code
async def _rm_file(self, path, **kwargs): self.references.pop( path, None ) # ignores FileNotFound, just as well for directories self.dircache.clear() # this is a bit heavy handed
async def _pipe_file(self, path, data, mode="overwrite", **kwargs): if mode == "create" and self.exists(path): raise FileExistsError # can be str or bytes self.references[path] = data self.dircache.clear() # this is a bit heavy handed
async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs): # puts binary if mode == "create" and self.exists(rpath): raise FileExistsError with open(lpath, "rb") as f: self.references[rpath] = f.read() self.dircache.clear() # this is a bit heavy handed
def save_json(self, url, **storage_options): """Write modified references into new location""" out = {} for k, v in self.references.items(): if isinstance(v, bytes): try: out[k] = v.decode("ascii") except UnicodeDecodeError: out[k] = (b"base64:" + base64.b64encode(v)).decode() else: out[k] = v with fsspec.open(url, "wb", **storage_options) as f: f.write(json.dumps({"version": 1, "refs": out}).encode())
class ReferenceFile(AbstractBufferedFile): def __init__( self, fs, path, mode="rb", block_size="default", autocommit=True, cache_type="readahead", cache_options=None, size=None, **kwargs, ): super().__init__( fs, path, mode=mode, block_size=block_size, autocommit=autocommit, size=size, cache_type=cache_type, cache_options=cache_options, **kwargs, ) part_or_url, self.start, self.end = self.fs._cat_common(self.path) protocol, _ = split_protocol(part_or_url) self.src_fs = self.fs.fss[protocol] self.src_path = part_or_url self._f = None
@property def f(self): if self._f is None or self._f.closed: self._f = self.src_fs._open( self.src_path, mode=self.mode, block_size=self.blocksize, autocommit=self.autocommit, cache_type="none", **self.kwargs, ) return self._f
def close(self): if self._f is not None: self._f.close() return super().close()
def _fetch_range(self, start, end): start = start + self.start end = min(end + self.start, self.end) self.f.seek(start) return self.f.read(end - start).gitattributes+1
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/async.rstAdded+188
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/changelog.rstAdded+1765
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/code-of-conduct.rstAdded+126
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/conf.pyAdded+193
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/copying.rstAdded+348
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/developer.rstAdded+130
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/features.rstAdded+470
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/img/gui.pngAdded

Large File Pointer Details
- SHA256: 9c64da8e5d520086fc9fda105fd23191a85ce53365704985122deb8869d9edf5
- Pointer size: 131 Bytes
- Size of remote file: 117 kB
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/index.rstAdded+129
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/intro.rstAdded+99
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/usage.rstAdded+179
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/__init__.pyAdded+75
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/_version.pyAdded+24
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/archive.pyAdded+86
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/asyn.pyAdded+1335
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/caching.pyAdded+1158
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/callbacks.pyAdded+324
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/compression.pyAdded+185
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/config.pyAdded+131
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/conftest.pyAdded+125
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/core.pyAdded+765
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/dircache.pyAdded+125
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/exceptions.pyAdded+18
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/fuse.pyAdded+324
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/generic.pyAdded+409
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/gui.pyAdded+417
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/__init__.pyAdded
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/arrow.pyAdded+333
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/asyn_wrapper.pyAdded+135
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/cache_mapper.pyAdded+75
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/cache_metadata.pyAdded+217
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/cached.pyAdded+1224
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/chained.pyAdded+23
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/dask.pyAdded+152
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/data.pyAdded+73
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/dbfs.pyAdded+498
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/dirfs.pyAdded+492
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/ftp.pyAdded+445
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/gist.pyAdded+241
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/git.pyAdded+123
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/github.pyAdded+348
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/http.pyAdded+1069
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/http_sync.pyAdded+937
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/ia.pyAdded+230
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/jupyter.pyAdded+132
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/libarchive.pyAdded+219
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/local.pyAdded+537
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/memory.pyAdded+476
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/reference.pyAdded+1387