Debian Codegraph @

docs/source/how-to/connect-to-remote-data.rst

raw
1 Connect to remote data
2 ======================
3
4 Dask can read data from a variety of data stores including local file systems,
5 network file systems, cloud object stores, and Hadoop. Typically this is done
6 by prepending a protocol like ``"s3://"`` to paths used in common data access
7 functions like ``dd.read_csv``:
8
9 .. code-block:: python
10
11 import dask.dataframe as dd
12 df = dd.read_csv('s3://bucket/path/to/data-*.csv')
13 df = dd.read_parquet('gcs://bucket/path/to/data-*.parq')
14
15 import dask.bag as db
16 b = db.read_text('hdfs://path/to/*.json').map(json.loads)
17
18 Dask uses `fsspec`_ for local, cluster and remote data IO. Other file interaction, such
19 as loading of configuration, is done using ordinary python method.
20
21 The following remote services are well supported and tested against the main
22 codebase:
23
24 - **Local or Network File System**: ``file://`` - the local file system, default in the absence of any protocol.
25
26 - **Hadoop File System**: ``hdfs://`` - Hadoop Distributed File System, for resilient, replicated
27 files within a cluster. This uses PyArrow_ as the backend.
28
29 - **Amazon S3**: ``s3://`` - Amazon S3 remote binary store, often used with Amazon EC2,
30 using the library s3fs_.
31
32 - **Google Cloud Storage**: ``gcs://`` or ``gs://`` - Google Cloud Storage, typically used with Google Compute
33 resource using gcsfs_.
34
35 - **Microsoft Azure Storage**: ``adl://``, ``abfs://`` or ``az://`` - Microsoft Azure Storage using adlfs_.
36
37 - **Hugging Face**: ``hf://`` - Hugging Face Hub of datasets for AI, using the huggingface_hub_ library.
38
39 - **HTTP(s)**: ``http://`` or ``https://`` for reading data directly from HTTP web servers.
40
41 `fsspec`_ also provides other file systems that may be of interest to Dask users, such as
42 ssh, ftp, webhdfs and dropbox. See the documentation for more information.
43
44 When specifying a storage location, a URL should be provided using the general
45 form ``protocol://path/to/data``. If no protocol is provided, the local
46 file system is assumed (same as ``file://``).
47
48 .. _fsspec: https://filesystem-spec.readthedocs.io/
49 .. _s3fs: https://s3fs.readthedocs.io/
50 .. _adlfs: https://github.com/dask/adlfs
51 .. _gcsfs: https://gcsfs.readthedocs.io/en/latest/
52 .. _PyArrow: https://arrow.apache.org/docs/python/
53 .. _huggingface_hub: https://huggingface.co/docs/huggingface_hub
54
55 Lower-level details on how Dask handles remote data is described
56 below in the Internals section
57
58 Optional Parameters
59 -------------------
60
61 Two methods exist for passing parameters to the backend file system driver:
62 extending the URL to include username, password, server, port, etc.; and
63 providing ``storage_options``, a dictionary of parameters to pass on. The
64 second form is more general, as any number of file system-specific options
65 can be passed.
66
67 Examples:
68
69 .. code-block:: python
70
71 df = dd.read_csv('hdfs://user@server:port/path/*.csv')
72
73 df = dd.read_parquet('s3://bucket/path',
74 storage_options={'anon': True, 'use_ssl': False})
75
76 Details on how to provide configuration for the main back-ends
77 are listed next, but further details can be found in the documentation pages of the
78 relevant back-end.
79
80 Each back-end has additional installation requirements and may not be available
81 at runtime. The dictionary ``fsspec.registry`` contains the
82 currently imported file systems. To see which backends ``fsspec`` knows how
83 to import, you can do
84
85 .. code-block:: python
86
87 from fsspec.registry import known_implementations
88 known_implementations
89
90 Note that some backends appear twice, if they can be referenced with multiple
91 protocol strings, like "http" and "https".
92
93 .. _connect-to-remote-data-local:
94
95 Local File System
96 -----------------
97
98 Local files are always accessible, and all parameters passed as part of the URL
99 (beyond the path itself) or with the ``storage_options``
100 dictionary will be ignored.
101
102 This is the default back-end, and the one used if no protocol is passed at all.
103
104 We assume here that each worker has access to the same file system - either
105 the workers are co-located on the same machine, or a network file system
106 is mounted and referenced at the same path location for every worker node.
107
108 Locations specified relative to the current working directory will, in
109 general, be respected (as they would be with the built-in python ``open``),
110 but this may fail in the case that the client and worker processes do not
111 necessarily have the same working directory.
112
113 Hadoop File System
114 ------------------
115
116 The Hadoop File System (HDFS) is a widely deployed, distributed, data-local file
117 system written in Java. This file system backs many clusters running Hadoop and
118 Spark. HDFS support can be provided by PyArrow_.
119
120 By default, the back-end attempts to read the default server and port from
121 local Hadoop configuration files on each node, so it may be that no
122 configuration is required. However, the server, port, and user can be passed as
123 part of the url: ``hdfs://user:pass@server:port/path/to/data``, or using the
124 ``storage_options=`` kwarg.
125
126
127 Extra Configuration for PyArrow
128 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
129
130 The following additional options may be passed to the ``PyArrow`` driver via
131 ``storage_options``:
132
133 - ``host``, ``port``, ``user``: Basic authentication
134 - ``kerb_ticket``: Path to kerberos ticket cache
135
136 PyArrow's ``libhdfs`` driver can also be affected by a few environment
137 variables. For more information on these, see the `PyArrow documentation`_.
138
139 .. _PyArrow documentation: https://arrow.apache.org/docs/python/filesystems_deprecated.html#hadoop-file-system-hdfs
140
141 .. _connect-to-remote-data-s3:
142
143 Amazon S3
144 ---------
145
146 Amazon S3 (Simple Storage Service) is a web service offered by Amazon Web
147 Services.
148
149 The S3 back-end available to Dask is s3fs_, and is importable when Dask is
150 imported.
151
152 Authentication for S3 is provided by the underlying library boto3. As described
153 in the `auth docs`_, this could be achieved by placing credentials files in one
154 of several locations on each node: ``~/.aws/credentials``, ``~/.aws/config``,
155 ``/etc/boto.cfg``, and ``~/.boto``. Alternatively, for nodes located
156 within Amazon EC2, IAM roles can be set up for each node, and then no further
157 configuration is required. The final authentication option for user
158 credentials can be passed directly in the URL
159 (``s3://keyID:keySecret/bucket/key/name``) or using ``storage_options``. In
160 this case, however, the key/secret will be passed to all workers in-the-clear,
161 so this method is only recommended on well-secured networks.
162
163 .. _auth docs: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html
164
165 The following parameters may be passed to s3fs using ``storage_options``:
166
167 - anon: Whether access should be anonymous (default False)
168
169 - key, secret: For user authentication
170
171 - token: If authentication has been done with some other S3 client
172
173 - use_ssl: Whether connections are encrypted and secure (default True)
174
175 - client_kwargs: Dict passed to the `boto3 client`_, with keys such
176 as `region_name` or `endpoint_url`. Notice: do not pass the `config`
177 option here, please pass it's content to `config_kwargs` instead.
178
179 - config_kwargs: Dict passed to the `s3fs.S3FileSystem`_, which passes it to
180 the `boto3 client's config`_ option.
181
182 - requester_pays: Set True if the authenticated user will assume transfer
183 costs, which is required by some providers of bulk data
184
185 - default_block_size, default_fill_cache: These are not of particular
186 interest to Dask users, as they concern the behaviour of the buffer
187 between successive reads
188
189 - kwargs: Other parameters are passed to the `boto3 Session`_ object,
190 such as `profile_name`, to pick one of the authentication sections from
191 the configuration files referred to above (see `here`_)
192
193 .. _boto3 client: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html#boto3.session.Session.client
194 .. _boto3 Session: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
195 .. _here: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html#shared-credentials-file
196 .. _s3fs.S3FileSystem: https://s3fs.readthedocs.io/en/latest/api.html#s3fs.core.S3FileSystem
197 .. _boto3 client's config: https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
198
199 Using Other S3-Compatible Services
200 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
201
202 By using the `endpoint_url` option, you may use other s3-compatible services,
203 for example, using `AlibabaCloud OSS`:
204
205 .. code-block:: python
206
207 dask_function(...,
208 storage_options={
209 "key": ...,
210 "secret": ...,
211 "client_kwargs": {
212 "endpoint_url": "http://some-region.some-s3-compatible.com",
213 },
214 # this dict goes to boto3 client's `config`
215 # `addressing_style` is required by AlibabaCloud, other services may not
216 "config_kwargs": {"s3": {"addressing_style": "virtual"}},
217 })
218
219 .. _connect-to-remote-data-gc:
220
221 Google Cloud Storage
222 --------------------
223
224 Google Cloud Storage is a RESTful online file storage web service for storing
225 and accessing data on Google's infrastructure.
226
227 The GCS back-end is identified by the
228 protocol identifiers ``gcs`` and ``gs``, which are identical in their effect.
229
230 Multiple modes of authentication are supported. These options should be
231 included in the ``storage_options`` dictionary as ``{'token': ..}`` submitted with your call
232 to a storage-based Dask function/method. See the `gcsfs`_ documentation for further
233 details.
234
235
236 General recommendations for distributed clusters, in order:
237
238 - use ``anon`` for public data
239 - use ``cloud`` if this is available
240 - use `gcloud`_ to generate a JSON file, and distribute this to all workers, and
241 supply the path to the file
242
243 - use gcsfs directly with the ``browser`` method to generate a token cache file
244 (``~/.gcs_tokens``) and distribute this to all workers, thereafter using method ``cache``
245
246 .. _gcloud: https://cloud.google.com/sdk/docs/
247
248 A final suggestion is shown below, which may be the fastest and simplest for authenticated access (as
249 opposed to anonymous), since it will not require re-authentication. However, this method
250 is not secure since credentials will be passed directly around the cluster. This is fine if
251 you are certain that the cluster is itself secured. You need to create a ``GCSFileSystem`` object
252 using any method that works for you and then pass its credentials directly:
253
254 .. code-block:: python
255
256 gcs = GCSFileSystem(...)
257 dask_function(..., storage_options={'token': gcs.session.credentials})
258
259 Microsoft Azure Storage
260 -----------------------
261
262 Microsoft Azure Storage is comprised of Data Lake Storage (Gen1) and Blob Storage (Gen2).
263 These are identified by the protocol identifiers ``adl`` and ``abfs``, respectively,
264 provided by the adlfs_ back-end.
265
266 Authentication for ``adl`` requires ``tenant_id``, ``client_id`` and ``client_secret``
267 in the ``storage_options`` dictionary.
268
269 Authentication for ``abfs`` requires ``storage_options`` to contain ``account_name``,
270 ``tenant_id``, ``client_id`` and ``client_secret`` for the `RBAC and ACL`_ access models,
271 or ``account_name`` and ``account_key`` for the `shared key`_ access model.
272
273 .. _RBAC and ACL: https://docs.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-access-control-model/
274 .. _shared key: https://docs.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-access-control-model#shared-key-and-shared-access-signature-sas-authorization
275
276 HTTP(S)
277 -------
278
279 Direct file-like access to arbitrary URLs is available over HTTP and HTTPS. However,
280 there is no such thing as ``glob`` functionality over HTTP, so only explicit lists
281 of files can be used.
282
283 Server implementations differ in the information they provide - they may or may
284 not specify the size of a file via a HEAD request or at the start of a download -
285 and some servers may not respect byte range requests. The HTTPFileSystem therefore
286 offers best-effort behaviour: the download is streamed but, if more data is seen
287 than the configured block-size, an error will be raised. To be able to access such
288 data you must read the whole file in one shot (and it must fit in memory).
289
290 Using a block size of 0 will return normal ``requests`` streaming file-like objects,
291 which are stable, but provide no random access.
292
293 Developer API
294 -------------
295
296 The prototype for any file system back-end can be found in
297 ``fsspec.spec.AbstractFileSystem``. Any new implementation should provide the
298 same API, or directly subclass, and make itself available as a protocol to Dask. For example, the
299 following would register the protocol "myproto", described by the implementation
300 class ``MyProtoFileSystem``. URLs of the form ``myproto://`` would thereafter
301 be dispatched to the methods of this class:
302
303 .. code-block:: python
304
305 fsspec.registry['myproto'] = MyProtoFileSystem
306
307 However, it would be better to submit a PR to ``fsspec`` to include the class in
308 the ``known_implementations``.
309
310 Internals
311 ---------
312
313 Dask contains internal tools for extensible data ingestion in the
314 ``dask.bytes`` package and uses external tools like ``open_files`` from `fsspec`_.
315 . *These functions are developer-focused rather than for
316 direct consumption by users. These functions power user-facing functions like*
317 ``dd.read_csv`` *and* ``db.read_text`` *which are probably more useful for most
318 users.*
319
320
321 .. currentmodule:: dask.bytes
322
323 .. autosummary::
324 read_bytes
325
326 This function is extensible in its output format (bytes),
327 its input locations (file system, S3, HDFS), line delimiters, and compression
328 formats.
329
330 This function is *lazy*, returning pointers to blocks of bytes (``read_bytes``).
331 It handles different storage backends by prepending
332 protocols like ``s3://`` or ``hdfs://`` (see below). It handles compression formats
333 listed in ``fsspec.compression``, some of which may require additional packages
334 to be installed.
335
336 This function is not used for all data sources. Some data sources like HDF5
337 are quite particular and receive custom treatment.
338
339 Delimiters
340 ^^^^^^^^^^
341
342 The ``read_bytes`` function takes a path (or globstring of paths) and produces
343 a sample of the first file and a list of delayed objects for each of the other
344 files. If passed a delimiter such as ``delimiter=b'\n'``, it will ensure that
345 the blocks of bytes start directly after a delimiter and end directly before a
346 delimiter. This allows other functions, like ``pd.read_csv``, to operate on
347 these delayed values with expected behavior.
348
349 These delimiters are useful both for typical line-based formats (log files,
350 CSV, JSON) as well as other delimited formats like Avro, which may separate
351 logical chunks by a complex sentinel string. Note that the delimiter finding
352 algorithm is simple, and will not account for characters that are escaped,
353 part of a UTF-8 code sequence or within the quote marks of a string.
354
355 Compression
356 ^^^^^^^^^^^
357
358 These functions support widely available compression technologies like ``gzip``,
359 ``bz2``, ``xz``, ``snappy``, and ``lz4``. More compressions can be easily
360 added by inserting functions into dictionaries available in the
361 ``fsspec.compression`` module. This can be done at runtime and need not be
362 added directly to the codebase.
363
364 However, most compression technologies like ``gzip`` do not support efficient
365 random access, and so are useful for streaming ``fsspec.open_files`` but not useful for
366 ``read_bytes`` which splits files at various points.
367
368 API
369 ^^^
370
371 .. autofunction:: read_bytes