Source code for dclab.http_utils

import functools
import io
import os
import re
import socket
import time
from unittest import mock
from urllib.parse import urlparse
import warnings

import numpy as np

from .cached import umbrella_cache


try:
    import requests
except ModuleNotFoundError:
    requests = mock.Mock()
    REQUESTS_AVAILABLE = False
else:
    REQUESTS_AVAILABLE = True


#: Regular expression for matching a regular HTTP URL
REGEXP_HTTP_URL = re.compile(
    r"^(https?:\/\/)"  # protocol (http or https or omitted)
    r"([a-z0-9-\.]*)(\:[0-9]*)?\/"  # host:port
    r".+"  # path
)


def httpfile_cache_handler(httpfile):
    return [
        # Only the base URL is used. We don't warn URL parameters,
        # such as "ExpiresAt" in the cache key.
        httpfile.url.split("?")[0],
        # Unique identifier for the dataset online.
        httpfile.etag,
        # Another sanity check.
        httpfile.length,
        # Chunk size is important, because we use `index` as a cache key.
        httpfile.chunk_size
    ]


class ETagNotInResponseHeaderWarning(UserWarning):
    """Used for cases where the requests.Response does not contain an ETag"""


class ConnectionTimeoutWarning(UserWarning):
    """Used when a connection fails or times out"""


[docs] class HTTPFile(io.IOBase): def __init__(self, url, chunk_size=2**18): """Chunk-cached access to a URL supporting range requests Range requests (https://en.wikipedia.org/wiki/Byte_serving) allow clients to access specific parts of a file via HTTP without downloading the entire file. This class creates a file-like object from a URL that can then be passed on to e.g. h5py for reading. In addition, this class keeps a chunk cache of the URL, making it (A) fast to access frequently used parts of the file and (B) fast to slice through large files since the ratio of data downloaded versus (time-consuming) HTTP requests is very large. Parameters ---------- url: str URL of the file chunk_size: int Download chunk size. The entire file is split up into equally-sized (and thus indexable) chunks. Notes ----- Caching is done with dclab's :class:`.umbrella_cache`. """ self.url = url self._chunk_size = chunk_size self.session = session_cache.get_session(url) self._len = None self._etag = None self._pos = 0 def _parse_header(self): """parse the header sent by the server, populates length and etag""" if self._len is None: # Do not use `self.session.head`, because it might return a # wrong content-length for pre-signed S3 URLS. resp = self.session.get(self.url, stream=True, timeout=0.5) if resp.status_code != 200: raise ValueError( f"Server replied with status code {resp.status_code} " f"{resp.reason} for '{self.url}'") self._len = int(resp.headers["content-length"]) # Try to determine the etag of the file. etag = resp.headers.get("etag", "").strip("'").strip('"') if len(etag) < 5: etag = None warnings.warn(f"Got empty ETag header for {self.url}", ETagNotInResponseHeaderWarning) self._etag = etag @property def chunk_size(self) -> int: """The chunk size of the HTTPFile in bytes""" return self._chunk_size @property def etag(self): """Unique identifier for this resource (version) by the web server""" self._parse_header() return self._etag @property def length(self) -> int: self._parse_header() return self._len
[docs] def close(self): """Close the file This closes the requests session and then calls `close` on the super class. """ self.session.close() super().close()
[docs] def download_range(self, start, stop) -> bytes: """Download bytes given by the range (`start`, `stop`) `stop` is not inclusive (In the HTTP range request it normally is). Transient server errors (e.g. "503 SlowDown" from S3) are retried. For any other error response, :class:`requests.HTTPError` is raised. This makes sure that error messages from the server are never returned (and cached) as file data. """ for ii in range(10): if ii: # wait before retrying time.sleep(min(0.1 * 2**(ii - 1), 2)) resp = self.session.get( self.url, headers={"Range": f"bytes={start}-{stop-1}"} ) if resp.status_code not in [408, 429, 500, 502, 503, 504]: break resp.raise_for_status() if len(resp.content) != stop - start: raise ValueError( f"Server replied with {len(resp.content)} bytes instead of " f"{stop - start} (status code {resp.status_code}) for range " f"request {start}-{stop-1} of '{self.url}'") return resp.content
[docs] @umbrella_cache(topic="httpfile", custom_handlers={"HTTPFile": httpfile_cache_handler}) def get_chunk(self, index: int) -> bytes: """Return the cache chunk defined by `index` If the chunk is not cached (see :class:`.umbrella_cache`), it is downloaded. """ start = index*self._chunk_size stop = min((index + 1) * self._chunk_size, self.length) return self.download_range(start, stop)
[docs] def read(self, size: int = -1, /) -> bytes: """Cache-supported read operation (file object)""" if size is None or size < 0: # read until the end of the file stop = self.length else: stop = self._pos + size data = self.read_range(self._pos, stop) self._pos += len(data) return data
[docs] def read_range(self, start, stop) -> bytes: """Concatenate the requested bytes from chunks This calls `get_chunk` and thus downloads cache chunks when they are not already cached with `umbrella_cache`. """ # do not request data beyond the end of the file stop = min(stop, self.length) toread = stop - start # compute the chunk indices between start and stop chunk_start = np.int64(start // self._chunk_size) chunk_stop = np.int64(stop // self._chunk_size + 1) data = b"" pos = start for chunk_index in range(chunk_start, chunk_stop): if toread <= 0: # Don't download the next chunk if we are done (this might # also be a chunk beyond the end of the file). break chunk = self.get_chunk(chunk_index) chunk_start = pos % self._chunk_size if chunk_start + toread >= self._chunk_size: data += chunk[chunk_start:] chunks_read = self._chunk_size - chunk_start else: chunk_end = stop % self._chunk_size data += chunk[chunk_start:chunk_end] chunks_read = chunk_end - chunk_start toread -= chunks_read pos += chunks_read return data
[docs] def seek(self, offset, whence=os.SEEK_SET): """Seek to a position (file object)""" if whence == os.SEEK_SET: self._pos = offset elif whence == os.SEEK_CUR: self._pos += offset elif whence == os.SEEK_END: self._pos = self.length + offset
[docs] def seekable(self): """The HTTP file is seekable""" return True
[docs] def tell(self): """Tell the position (file object)""" return self._pos
class ResoluteRequestsSessionCache: def __init__(self): """A multiprocessing-safe cache for requests session objects This class implements empty `__getstate__` and `__setstate__` methods, so that when used in a multiprocessing context, sessions are never mirrored to the subprocesses. Each subprocess creates its own sessions. Note that only :class:`ResoluteRequestsSession` objects are used, which is ideal for the use-case of unstable internet connections. """ #: This dictionary holds all sessions in use by the current process. #: Sessions are stored with the host name / netloc as the key. self.sessions = {} def __getstate__(self): """Returns None, so sessions are not pickled into subprocesses""" def __setstate__(self, state): """Does nothing (see `__getstate__`)""" def get_session(self, url: str): """Return a requests session for the specified URL For each hostname, a different session is returned, but for identical hostnames, cached sessions are used. """ urlp = urlparse(url) key = urlp.netloc if key not in self.sessions: self.sessions[key] = ResoluteRequestsSession() return self.sessions[key] class ResoluteRequestsSession(requests.Session): """A session with built-in retry for `get`""" def get(self, *args, **kwargs): kwargs.setdefault("timeout", 0.5) for ii in range(100): try: resp = super().get(*args, **kwargs) except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout, requests.urllib3.exceptions.ConnectionError, requests.urllib3.exceptions.ReadTimeoutError) as e: warnings.warn(f"Encountered {e} for {args} {kwargs}", ConnectionTimeoutWarning) continue else: break else: raise requests.exceptions.ReadTimeout( f"Resolute session failed for {args} and {kwargs}!") return resp def is_url_available(url: str, ret_reason=False): """Check whether a URL is available Parameters ---------- url: str full URL to the object ret_reason: bool whether to return reason for unavailability Returns ------- available: bool whether the URL is available reason: str reason for the URL not being available if `available` is False; only returned if `ret_reason` is True """ avail = False reason = "none" if is_http_url(url): urlp = urlparse(url) # default to https if no scheme or port is specified port = urlp.port or (80 if urlp.scheme == "http" else 443) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.settimeout(1) # Try to connect to the host try: # Use `hostname`, not `netloc`, because `netloc` contains # the port number which we do not want here. s.connect((urlp.hostname, port)) except (socket.gaierror, OSError): reason = "no connection" else: # Try to access the url try: ses = session_cache.get_session(url) req = ses.get(url, stream=True, timeout=1) avail = req.ok if not avail: reason = req.reason.lower() except OSError: reason = "oserror" else: reason = "invalid" if ret_reason: return avail, reason else: return avail @functools.lru_cache def is_http_url(string): """Check whether `string` is a valid URL using regexp""" if not isinstance(string, str): return False else: return REGEXP_HTTP_URL.match(string.strip()) #: cache of requests sessions for current process session_cache = ResoluteRequestsSessionCache()