diff --git a/.ai/ARCHITECTURE.md b/.ai/ARCHITECTURE.md index a1eff98ce4..b0b7246951 100644 --- a/.ai/ARCHITECTURE.md +++ b/.ai/ARCHITECTURE.md @@ -899,17 +899,18 @@ gap rather than a silent hole). A `Subscription` is iterable synchronously ### Backends -Three backends ship, differing only in **how far state reaches**. Pick by the +Four backends ship, differing only in **how far state reaches**. Pick by the deployment topology — critically, whether the app runs behind a load balancer as more than one container/pod (see [Deployment Topology](#deployment-topology-and-shared-storage) below). | Backend | Backing store | Reaches | Extra | |---------|---------------|---------|-------| | `LocalSharedStorage` | in-memory, owner-elected socket | one **container** (all its workers) | none (`dash[shared_storage]` for the persistent modes) | +| `ClusterSharedStorage` | in-memory, owner elected across replicas over TCP | every **pod/container** that resolves the same name | none (same as local) | | `DiskcacheSharedStorage` | a `diskcache.Cache` | one **host** (all processes sharing the dir) | `dash[diskcache]` | | `RedisSharedStorage` | Redis (Streams for pub/sub) | **any** process/container/pod | `dash[redis]` | -All three implement the same `BaseSharedStorage` contract (KV + ordered, +All four implement the same `BaseSharedStorage` contract (KV + ordered, replayable pub/sub with `SharedStorageGap` on buffer overrun), so app code is identical across them — only the constructor differs. @@ -995,6 +996,149 @@ Dash(shared_storage=LocalSharedStorage(mode="persist")) Dash(shared_storage=LocalSharedStorage(mode="persist-reset", flush_interval=30)) ``` +**`ClusterSharedStorage`**: `LocalSharedStorage` stretched across replicas, +with no external service and no consensus (`_shared_storage/cluster.py`, +`_cluster_lock.py`). + +- *Discovery.* `host` is a name that resolves to every replica (a Kubernetes + headless Service, a podman or Docker network alias). `peers=` replaces DNS + with a function returning `(host, port)` lock addresses. +- *Ports.* `port` (default 7100) runs the election, `port + 1` serves the store. + Both must be reachable between replicas. +- *Inside a replica* the first process to bind `port` runs the `ClusterLock`; + the bind is the per-replica lease, as the socket bind is for local. Other + workers ask it on `127.0.0.1:port` where the owner is. +- *Election.* Every probe interval (1s) each lock asks every peer for its view. + It follows the owner it sees, picking the one that has owned longest (a + monotonic duration, so clock skew does not matter). When two owners meet, + only the lower id judges: it steps down to an older owner, or keeps owning + and lists the other as a rival, and an owner steps down once a lower id + lists it. Both sides comparing ages deadlocked: each sees its own age now and + the other's from a probe ago, so owners that claimed within a round trip of + each other both thought they were older. With no owner, the lowest id among + reachable peers claims a fresh term; a higher id waits for it at most `miss_limit` (3) + probes. A follower gives up on an owner after 3 missed probes, so a dead + owner is replaced in about 5 to 6 seconds (measured with 3 Docker containers). +- *Lock changes* are applied by a `dash-cluster-changes` thread, not in the + probe thread's `on_change`: a request electing holds the coordinator lock + while it waits for the probe thread to settle, so the probe thread must + never wait on that lock (it deadlocked until `settle_timeout`). +- *Resign.* An elected replica that cannot serve the store (`port + 1` taken) + calls `ClusterLock.resign`: it steps down, shows `resigned` in its view, and + stays out of elections for 3 leases, so peers skip it as the lowest id or + candidate instead of following an owner that serves nothing. +- *Failover.* Calls retry for up to 10s (`failover_window`) while followers + notice a dead owner, so a write during a failover waits instead of failing. + `_local` raises `_OwnerGone` when the engine closed under it, and the call + retries on the new owner. Elections that can block run in the executor on + asyncio paths (`_aelect`). A deposed owner abandons its engine + (`StoreEngine.abandon`): no final flush, so a persistent store on a shared + volume keeps the new owner's data. +- *Fencing.* The term is the data connection token. The owner's server checks + `ClusterLock.is_owner(term)` before every request and drops the connection + once it lost the term; clients then re-elect and get `SharedStorageGap`. Every + subscription takes the token before reading the head, and gaps when a poll + or a reconnect finds another one, so it never reads a new owner's topic with + an old owner's cursor. +- *Network.* Client sockets time out after 10s and long polls last 5s (20s + locally), since a vanished pod does not close its sockets; a caller's longer + `poll(timeout)` is cut to one cycle. The async handshake has the same + timeout. TCP keepalive is on. A request that failed or was cancelled + closes its connection with a reset (`SO_LINGER` 0, `_transport.abort`): + a plain close keeps retransmitting what is queued, so after a partition + healed the old owner applied a write the caller had already retried on the + new owner, over newer writes (caught by `tests/cluster_harness`). A request + that reached the old owner before the cut can still land twice (at least + once, like any retry after a lost answer). The data port is reachable + from other hosts, so before a connection shows the token it gets 5s, one + frame of at most 1 KB, and one of 64 handshake slots (accept waits for a + slot rather than refuse a client, which would take the owner for dead). + The accept loop survives errors such as running out of descriptors. Lock + messages are JSON whatever the store codec, so replicas with and without + msgspec still see each other. +- *Auth.* `secret` (default `$DASH_SECRET_KEY`, run through HMAC so the signing + key is not reused as is) is proven both ways with an HMAC challenge and never + sent. Views are MACed. Without TLS the data channel and its token travel in + clear: keep the ports on a private network, as with Redis without TLS. +- *TLS (optional).* `tls_cert` + `tls_key` (PEM; `?tls_cert=&tls_key=&tls_ca=` + on the URL) turn every connection between replicas into mutual TLS (1.2+): + election probes, the data channel, and a worker's loopback hops to its own + replica. Each side checks the other's certificate against `tls_ca`, which + defaults to `tls_cert`, so one self-signed pair mounted in every replica is + enough (`openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 + -nodes -subj /CN=dash -keyout key.pem -out cert.pem`); a CA with one + certificate per pod (cert-manager) works too. Hostnames are not checked, + since replicas are reached by IP: trust comes from the CA, and the HMAC + secret is still required on top. Stdlib only, hence files and not keys + derived from the secret (TLS-PSK needs Python 3.13). TLS and plaintext + replicas do not see each other, so roll it out to all replicas at once. Each + certificate is used as client and server certificate: it needs no extended + key usage or both `serverAuth` and `clientAuth` (a `serverAuth`-only + certificate fails with `unsupported certificate`; set cert-manager's + `usages` accordingly). A failed peer handshake is logged once per peer. + Files are read at startup, so restart replicas after rotating them. Probes + get 1s instead of 0.5s with TLS, since each is a full handshake. +- *Majority mode (optional).* `replicas=N` (`?replicas=3`), the number of + replicas the app runs, fixed like raposa's `cluster_size` rather than read + from DNS, which changes as pods start and stop. + - *Lease.* An owner renews `ClusterLock.lease` (4 probe gaps of interval + + timeout: 6s, 8s with TLS) only on a probe where a majority, itself + included, follows its term. `is_owner` checks the lease on the owner's + clock, so a stalled probe thread fences itself; a lapsed owner steps + down and never renews. + - *Votes.* Each electing replica publishes a ballot: the lowest electing id + it sees, plus a counter bumped on every change (following an owner + counts as a change). A replica claims once a majority, itself included, + has shown it the same ballot naming it for longer than a lease. Two + majorities share a peer, and that peer neither followed an owner nor + backed anyone else during the run, so a minority owner's lease has run + out and no second claimant had its vote. A plain "majority seen + electing" rule was not enough: after a one-way cut, two replicas each + counted the same quiet peer and both claimed. A candidate that has not + claimed after 3 leases (it cannot reach a majority itself) is passed + over for 3 leases. Followers never claim directly; they drop to + electing first, which restarts their ballot. + - *Assumes* monotonic clocks run at about the same rate on all hosts. + - *Boot.* Every replica must vote before any request reaches it, so in + this mode `Dash()` starts the storage in a thread at construction + (`starts_at_boot`), unlike the lazy default. A forked child (gunicorn + `--preload`) drops the parent's objects through `os.register_at_fork` + (`after_fork`, closing inherited sockets without shutting them down) + and reaches the parent's lock on loopback. It reaches a backend still + starting too (`_shared_storage_starting`), since gunicorn forks while + the boot thread is still electing. `forget` also unregisters the + inherited `atexit` close: run in a child that exits normally, it + flushed the parent's store as of the fork over newer data. + - *Claim timing.* A backer's run counts up to the probe round's start, + where the claim's lease starts, not up to when the votes are counted: + after a stall in between, a voter could have gone back to the old owner. + - *Cost.* No owner without a majority up: calls fail after + `settle_timeout` (30s here). Failover takes 10 to 20s (measured 10s for + a killed owner, 20s for a cut-off one with 3 containers), so + `failover_window` is 30s. A follower that sees its owner lapse drops to + electing at once, so a quorum hiccup longer than a lease costs an + election. Use an odd N: with 2, losing either stops the store. + - *N must be right.* Majorities only intersect if every replica uses the + same N and no more than N run: a rolling update's surge pod during a + partition, or an N set too low, can let both sides claim. A failed boot + start is logged and retried on first use, which waits up to + `settle_timeout`. + - *Fork.* The child does not boot again (a multiprocessing child for a + background callback must not take the replica's port); it starts lazily + like any worker, and `after_fork` runs once per process even when one + instance backs several apps. +- *What it gives up.* When replicas briefly see different DNS answers (all of + them waking from zero at once is the usual case) two owners exist until they + probe each other; writes to the one that steps down are lost. Replicas that + cannot reach each other at all stay split, and an isolated owner keeps + owning (both without `replicas`). The owner's store is lost with it (`mode="memory"`); the persistent + modes only help when `path` is on a volume every replica mounts. Every + replica probes every other each second, fine at the 1-10 pods an HPA runs. + +```python +Dash(shared_storage=ClusterSharedStorage(host="myapp-headless", secret="...")) +``` + **`DiskcacheSharedStorage`** — KV + an append-log pub/sub on a `diskcache.Cache`, the same store `DiskcacheManager` uses; pass an existing `cache` to share one. Every process on one host that opens the same directory shares state, so it @@ -1006,8 +1150,9 @@ topic (an atomic `INCR`+`XADD` script keeps sequences ordered; `MAXLEN` bounds the replay window; a subscriber past the trimmed floor gets `SharedStorageGap`). Redis is the single source of truth, so no owner election. Pass a `url` (defaults to `$REDIS_URL`) or an existing `client` to reuse a connection pool. -This is the only backend correct for **horizontally-scaled, multi-pod** -deployments. On an event loop it uses `redis.asyncio` (one client per loop), +One of the two backends for **horizontally-scaled, multi-pod** deployments, +with `ClusterSharedStorage`. Redis keeps its data when app pods come and go; +the cluster backend loses its store with the owner pod. On an event loop it uses `redis.asyncio` (one client per loop), and one reader task per loop serves every async subscription with a single multi-stream `XREAD`; a new subscription interrupts it through a private wake stream. Never park a blocking read in the executor per subscription: at a dozen @@ -1032,17 +1177,21 @@ election only reaches processes in the same network + filesystem namespace. an HPA, routed round-robin with no session affinity): **each pod elects its own isolated owner**, so `set()`/`publish()` on one pod are invisible on another. This works at 1 pod and fragments silently once it scales — use - `RedisSharedStorage` (one Redis shared by all pods) instead. + `RedisSharedStorage` (one Redis shared by all pods) or + `ClusterSharedStorage` (the pods elect one owner among themselves) instead. A hosting platform can switch the backend without editing the app through `DASH_SHARED_STORAGE` (`_shared_storage/_env.py`), read only when the app did not pass `shared_storage=` (the default is a sentinel, so an explicit argument, `None` included, always wins): `local`, `none` (same as unset or empty), -`diskcache:///abs/path`, or a `redis://` / `rediss://` URL. A `key_prefix` query +`diskcache:///abs/path`, a `redis://` / `rediss://` URL, or +`cluster://[:secret@]host[:port]`. A `key_prefix` query parameter on the Redis URL (`redis://host/0?key_prefix=myapp`) sets `RedisSharedStorage(key_prefix=)` and is stripped before the URL reaches -redis-py; the diskcache path is percent-decoded. `cluster://` is reserved and -raises; anything else raises `InvalidConfig` at construction, without echoing +redis-py; the diskcache path is percent-decoded. A `cluster://` URL takes only +a host, an optional port (default 7100, below 65535 since the next port is used +too) and a percent-decoded password as the secret, falling back to +`DASH_SECRET_KEY`; with neither it raises. Anything else raises `InvalidConfig` at construction, without echoing the value (it can hold credentials). The value becomes a zero-argument factory, so nothing is built or connected until `app.shared_storage` is first read, but a missing extra (`dash[redis]`, `dash[diskcache]`, `dash[shared_storage]`) fails @@ -1082,6 +1231,8 @@ Dash core. It plugs in the same way as a built-in: | `_shared_storage/base.py` | Abstract interface: `BaseSharedStorage`, `Subscription`, `SharedStorageError`, `SharedStorageGap` | | `_shared_storage/_engine.py` | `StoreEngine`: authoritative in-memory kv map + per-topic ordered log with bounded replay buffer (thread-safe, transport-agnostic) | | `_shared_storage/local.py` | `LocalSharedStorage`: owner election; owner hosts the engine, clients proxy | +| `_shared_storage/cluster.py` | `ClusterSharedStorage`: the local backend with the owner elected across replicas | +| `_shared_storage/_cluster_lock.py` | `ClusterLock`: owner election among replicas over TCP, HMAC-authenticated | | `_shared_storage/diskcache.py` | `DiskcacheSharedStorage`: KV + append-log pub/sub on a `diskcache.Cache` | | `_shared_storage/redis.py` | `RedisSharedStorage`: KV + Redis Streams pub/sub (atomic `INCR`+`XADD`) | | `_shared_storage/_polling.py` | `PollingSubscription`: shared poll-loop subscription for the diskcache/Redis backends | diff --git a/CHANGELOG.md b/CHANGELOG.md index 970ddb7f0f..5c51118703 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ This project adheres to [Semantic Versioning](https://semver.org/). ## [UNRELEASED] ### Added +- [#4116](https://github.com/plotly/dash/pull/4116) Add `ClusterSharedStorage` (`DASH_SHARED_STORAGE=cluster://:secret@host:port`): shared storage across pods or containers with no external service, the replicas electing one owner among themselves, with optional mutual TLS and majority mode (`?replicas=3`). An owner change loses its data, like a local re-election. - [#4203](https://github.com/plotly/dash/pull/4203) Add a Copy button to each error in the debug toolbar, which copies the error message and its traceback to the clipboard. Closes [#3624](https://github.com/plotly/dash/issues/3624). - [#4204](https://github.com/plotly/dash/pull/4204) Add `DASH_HOST` and `DASH_PORT` environment variables to set the listen address for `Dash.run`, taking precedence over the generic `HOST` and `PORT` variables. Fixes [#3400](https://github.com/plotly/dash/issues/3400). diff --git a/dash/__init__.py b/dash/__init__.py index 9b219f7959..7fdc2df64a 100644 --- a/dash/__init__.py +++ b/dash/__init__.py @@ -46,6 +46,7 @@ from ._shared_storage import ( # noqa: F401,E402 BaseSharedStorage, + ClusterSharedStorage, DiskcacheSharedStorage, LocalSharedStorage, RedisSharedStorage, @@ -107,6 +108,7 @@ def _jupyter_nbextension_paths(): "hooks", "stringify_id", "BaseSharedStorage", + "ClusterSharedStorage", "DiskcacheSharedStorage", "LocalSharedStorage", "RedisSharedStorage", diff --git a/dash/_shared_storage/__init__.py b/dash/_shared_storage/__init__.py index a26079595c..38880fb6b1 100644 --- a/dash/_shared_storage/__init__.py +++ b/dash/_shared_storage/__init__.py @@ -3,6 +3,8 @@ Exposes the ``BaseSharedStorage`` interface and its backends: - ``LocalSharedStorage``: in-memory, owner-elected -- one container. +- ``ClusterSharedStorage``: the same, owner elected across replicas -- pods, + with no external service. - ``DiskcacheSharedStorage``: on a ``diskcache.Cache`` -- one machine, not pods. - ``RedisSharedStorage``: on Redis -- across processes and containers. """ @@ -13,12 +15,14 @@ SharedStorageGap, Subscription, ) +from .cluster import ClusterSharedStorage from .diskcache import DiskcacheSharedStorage from .local import LocalSharedStorage from .redis import RedisSharedStorage __all__ = [ "BaseSharedStorage", + "ClusterSharedStorage", "DiskcacheSharedStorage", "LocalSharedStorage", "RedisSharedStorage", diff --git a/dash/_shared_storage/_cluster_lock.py b/dash/_shared_storage/_cluster_lock.py new file mode 100644 index 0000000000..3db3891d07 --- /dev/null +++ b/dash/_shared_storage/_cluster_lock.py @@ -0,0 +1,645 @@ +"""Network lock that elects one owner among the replicas of an app. + +Every replica runs a ``ClusterLock`` on the same port. It finds its peers +through a name that resolves to all of them (a Kubernetes headless Service, a +podman network alias), asks each one who owns the store, and follows the owner +it finds. With no owner in sight, the lowest id among the replicas it reaches +claims ownership under a fresh term. + +There is no consensus. Two owners exist for a while when replicas see +different DNS answers, which is normal when they all boot at once from zero. +Owners probe each other too: when they meet, the one that has owned longer +wins and the other steps down. The shared-storage contract already allows +this, since an owner change loses its buffer and readers get a gap. A data +server checks its term with ``is_owner`` so a deposed owner stops taking +writes. An owner cut off from every peer keeps owning until it can reach them +again, and replicas that cannot reach each other at all stay split. + +With ``replicas`` set (the number of replicas the app runs), a majority is +needed. Each electing replica backs one candidate, the lowest electing id it +sees, and a replica claims only once a majority (itself included) has backed +it without a break for a whole lease. An owner holds a lease that it renews +only while a majority follows its term. An owner on the minority side of a +partition stops owning when its lease runs out, before the majority side may +claim, a peer backs one claimant at a time, and a replica that starts alone +waits for its peers. + +Peers prove they hold the shared secret with an HMAC challenge both ways, and +the view a replica answers with is MACed too, so the secret never crosses the +wire and an on-path attacker cannot forge a view. Nothing is encrypted. +""" + +import hashlib +import hmac +import json +import logging +import secrets +import socket +import ssl +import struct +import threading +import time +from concurrent.futures import ThreadPoolExecutor +from typing import Any, Callable, Dict, List, NamedTuple, Optional, Set, Tuple + +Addr = Tuple[str, int] + +ELECTING = "electing" +FOLLOWER = "follower" +OWNER = "owner" +_ROLES = (ELECTING, FOLLOWER, OWNER) + +_MAX_PROBE_WORKERS = 16 +_MAX_CONNECTIONS = 64 +_MAX_FRAME = 16384 + +logger = logging.getLogger(__name__) + + +class LockState(NamedTuple): + role: str + term: Optional[str] = None + owner_id: Optional[str] = None + # The owner's lock address as this replica reached it, and what the owner + # advertises (its data port, ...). None for the owner itself. + owner_addr: Optional[Addr] = None + advert: Any = None + + +class TLS(NamedTuple): + """Mutual TLS between replicas: each side presents its certificate and + checks the other's against the CA. Peers are reached by IP, so there is no + hostname to check; trust comes from the CA (and the shared secret).""" + + server: ssl.SSLContext + client: ssl.SSLContext + + +def tls_contexts(cert: str, key: str, ca: Optional[str] = None) -> TLS: + """Contexts from PEM files. ``ca`` defaults to ``cert``, so a single + self-signed certificate mounted in every replica is enough.""" + server = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + client = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + client.check_hostname = False + for context in (server, client): + context.minimum_version = ssl.TLSVersion.TLSv1_2 + context.verify_mode = ssl.CERT_REQUIRED + # An encrypted key would prompt for a password on a terminal. + context.load_cert_chain(cert, key, password=_no_password) + context.load_verify_locations(ca or cert) + return TLS(server, client) + + +def _no_password() -> str: + raise ssl.SSLError("the cluster TLS key must not be encrypted") + + +def resolve_peers(host: str, port: int) -> List[Addr]: + """Every address ``host`` resolves to, on ``port``. Empty when it does not + resolve, which is normal while the first replicas start.""" + try: + infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM) + except socket.gaierror: + return [] + return sorted({(str(info[4][0]), port) for info in infos}) + + +def listen(host: str, port: int) -> socket.socket: + """A listening TCP socket. ``host`` of ``""`` takes every address, IPv4 and + IPv6 both where the host has them.""" + if host == "" and socket.has_dualstack_ipv6(): + return socket.create_server( + ("", port), family=socket.AF_INET6, dualstack_ipv6=True + ) + return socket.create_server((host or "0.0.0.0", port)) + + +def _mac(secret: bytes, label: bytes, *parts: str) -> str: + return hmac.new( + secret, label + "\0".join(parts).encode(), hashlib.sha256 + ).hexdigest() + + +# JSON, not the store's codec: whether msgspec is installed must not split +# replicas that differ only in that extra (a rolling update adding it). +def _send(conn: socket.socket, obj: Any) -> None: + data = json.dumps(obj).encode() + conn.sendall(struct.pack("!I", len(data)) + data) + + +def _recv(conn: socket.socket, deadline: float) -> Any: + """One small frame, read before ``deadline`` (monotonic) or not at all, so + a peer that drips bytes or claims a huge frame cannot hold a thread.""" + + def exactly(n: int) -> bytes: + chunks = [] + while n: + left = deadline - time.monotonic() + if left <= 0: + raise TimeoutError("cluster lock exchange timed out") + conn.settimeout(left) + chunk = conn.recv(n) + if not chunk: + raise ConnectionError("peer closed") + chunks.append(chunk) + n -= len(chunk) + return b"".join(chunks) + + (length,) = struct.unpack("!I", exactly(4)) + if length > _MAX_FRAME: + raise ValueError("cluster lock frame too large") + return json.loads(exactly(length)) + + +# Peers whose TLS handshake failed, so the warning is logged once per peer +# until it succeeds again. +_tls_failed: Set[Addr] = set() + + +def probe( + addr: Addr, + secret: bytes, + timeout: float, + tls: Optional[ssl.SSLContext] = None, +) -> Optional[Dict[str, Any]]: + """Ask the lock at ``addr`` for its view: its id, role and term, plus the + owner's advert (and, from a follower, the owner's host). None when it does + not answer or cannot prove it holds ``secret``. ``tls`` is the client + context when the replicas talk TLS.""" + deadline = time.monotonic() + timeout + try: + raw = socket.create_connection(addr, timeout=timeout) + conn = tls.wrap_socket(raw) if tls is not None else raw + _tls_failed.discard(addr) + with conn: + nonce = secrets.token_hex(16) + _send(conn, nonce) + challenge, proof = _recv(conn, deadline) + if not hmac.compare_digest(proof, _mac(secret, b"server", nonce)): + return None + _send(conn, _mac(secret, b"client", challenge)) + raw, view_mac = _recv(conn, deadline) + if not hmac.compare_digest(view_mac, _mac(secret, b"view", nonce, raw)): + return None + view = json.loads(raw) + except ssl.SSLError as err: + # Otherwise silent: replicas would just never see each other. + if addr not in _tls_failed: + _tls_failed.add(addr) + logger.warning("dash cluster TLS handshake with %s failed: %s", addr, err) + return None + except Exception: # pylint: disable=broad-exception-caught + return None + if not _valid_view(view): + return None + return dict(view) + + +def _valid_view(view: Any) -> bool: + if not isinstance(view, dict): + return False + if not isinstance(view.get("id"), str) or view.get("role") not in _ROLES: + return False + if view["role"] == OWNER: + age = view.get("age") + return ( + isinstance(view.get("term"), str) + and isinstance(age, (int, float)) + and not isinstance(age, bool) + and age >= 0 + and isinstance(view.get("rivals"), list) + and all(isinstance(r, str) for r in view["rivals"]) + ) + if view["role"] == FOLLOWER: + return isinstance(view.get("term"), str) and isinstance( + view.get("owner_host"), str + ) + ballot = view.get("ballot") + return ballot is None or ( + isinstance(ballot, list) + and len(ballot) == 2 + and (ballot[0] is None or isinstance(ballot[0], str)) + and isinstance(ballot[1], int) + and not isinstance(ballot[1], bool) + ) + + +class ClusterLock: # pylint: disable=too-many-instance-attributes + """Elects and tracks the owner among the replicas ``peers`` returns. + + ``peers`` is called every probe and returns lock addresses, this replica's + own included or not. ``advert`` is handed to followers along with the + owner's address. ``on_change`` is called with the new ``LockState`` from + the probe thread whenever the role, owner or term changes. + + ``miss_limit`` probes in a row without its owner make a follower give up + on it; a replica waiting on a lower id to claim waits that many probes too. + """ + + def __init__( + self, + peers: Callable[[], List[Addr]], + secret: bytes, + bind: Addr = ("0.0.0.0", 0), + advert: Any = None, + on_change: Optional[Callable[[LockState], None]] = None, + tls: Optional[TLS] = None, + probe_interval: float = 1.0, + probe_timeout: float = 0.5, + miss_limit: int = 3, + replicas: Optional[int] = None, + ): + if not secret: + raise ValueError("ClusterLock needs a non-empty secret") + if replicas is not None and ( + not isinstance(replicas, int) or isinstance(replicas, bool) or replicas < 1 + ): + raise ValueError("replicas must be a positive integer") + self.id = secrets.token_hex(8) + self._peers = peers + self._secret = secret + self._advert = advert + self._on_change = on_change + self._tls = tls + self._interval = probe_interval + self._timeout = probe_timeout + self._miss_limit = miss_limit + self._misses = 0 + self._deferred = 0 + self._owned_since = 0.0 + # Owners this one judged younger than itself, which must step down. + self._rivals: List[str] = [] + self._majority = replicas // 2 + 1 if replicas else None + # Ticks start at most interval + timeout apart. A new owner needs + # about three of them to see its followers follow, and a lease of four + # survives a dropped probe after that. + self.lease = 4 * (probe_interval + probe_timeout) + self._quorum_at = 0.0 + # Majority mode: whom this replica would see own (its candidate) and + # a counter bumped on every change, since when, and which candidates + # it gave up on. Peers backing this replica: id -> (their counter, + # first seen with it). + self._ballot: Tuple[Optional[str], int] = (None, 0) + self._ballot_since = time.monotonic() + self._banned: Dict[str, float] = {} + self._backers: Dict[str, Tuple[int, float]] = {} + self._resigned_until = 0.0 + self._state = LockState(ELECTING) + self._cond = threading.Condition() + self._closed = threading.Event() + self._slots = threading.BoundedSemaphore(_MAX_CONNECTIONS) + self._sock = listen(*bind) + self.port = self._sock.getsockname()[1] + self._pool = ThreadPoolExecutor( + _MAX_PROBE_WORKERS, thread_name_prefix="dash-cluster-probe" + ) + self._threads = [ + threading.Thread(target=self._serve, name="dash-cluster-lock", daemon=True), + threading.Thread(target=self._run, name="dash-cluster-probe", daemon=True), + ] + + # --- public ------------------------------------------------------------ + def start(self) -> "ClusterLock": + for thread in self._threads: + thread.start() + return self + + def close(self) -> None: + if self._closed.is_set(): + return + self._closed.set() + try: + # close() alone does not wake a thread blocked in accept() on Linux. + self._sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + try: + self._sock.close() + except OSError: + pass + self._pool.shutdown(wait=False, cancel_futures=True) + with self._cond: + self._cond.notify_all() + + @property + def state(self) -> LockState: + return self._state + + def is_owner(self, term: Optional[str]) -> bool: + state = self._state + return ( + not self._closed.is_set() + and state.role == OWNER + and term is not None + and state.term == term + and self._leased() + ) + + def _leased(self) -> bool: + return ( + self._majority is None or time.monotonic() - self._quorum_at <= self.lease + ) + + def resign(self, term: Optional[str]) -> None: + """Give up ``term`` and stay out of elections for a while: this + replica cannot serve the store, and its peers would keep following it.""" + self._resigned_until = time.monotonic() + 3 * self.lease + state = self._state + if state.role == OWNER and state.term == term: + self._step_down() + + def _resigned(self) -> bool: + return time.monotonic() < self._resigned_until + + def wait_settled(self, timeout: Optional[float] = None) -> LockState: + """Block until this replica is an owner or a follower, or the timeout + passes. Returns the state either way.""" + with self._cond: + self._cond.wait_for( + lambda: self._state.role != ELECTING or self._closed.is_set(), + timeout, + ) + return self._state + + # --- server ------------------------------------------------------------ + def _view(self) -> Dict[str, Any]: + state = self._state + if state.role == OWNER and not self._leased(): + state = LockState(ELECTING) + view = {"id": self.id, "role": state.role, "term": state.term} + if state.role == ELECTING and self._majority is not None: + view["ballot"] = list(self._ballot) + if state.role == ELECTING and self._resigned(): + view["resigned"] = True + if state.role == OWNER: + view["age"] = time.monotonic() - self._owned_since + view["advert"] = self._advert + view["rivals"] = list(self._rivals) + elif state.role == FOLLOWER: + view["owner_id"] = state.owner_id + view["owner_host"] = state.owner_addr[0] if state.owner_addr else None + view["advert"] = state.advert + return view + + def _serve(self) -> None: + while not self._closed.is_set(): + try: + conn, _ = self._sock.accept() + except OSError: + if self._closed.is_set(): + return + # Out of file descriptors or similar: an owner that stops + # answering looks dead to its peers, so keep trying. + time.sleep(0.1) + continue + if not self._slots.acquire( # pylint: disable=consider-using-with + blocking=False + ): + conn.close() + continue + threading.Thread(target=self._answer, args=(conn,), daemon=True).start() + + def _answer(self, conn: socket.socket) -> None: + deadline = time.monotonic() + self._timeout + try: + if self._tls is not None: + conn.settimeout(self._timeout) + conn = self._tls.server.wrap_socket(conn, server_side=True) + with conn: + nonce = _recv(conn, deadline) + if not isinstance(nonce, str) or not 0 < len(nonce) <= 64: + return + challenge = secrets.token_hex(16) + _send(conn, [challenge, _mac(self._secret, b"server", nonce)]) + proof = _recv(conn, deadline) + expected = _mac(self._secret, b"client", challenge) + if not isinstance(proof, str) or not hmac.compare_digest( + proof, expected + ): + return + if self._closed.is_set(): + return + view = json.dumps(self._view(), sort_keys=True) + _send(conn, [view, _mac(self._secret, b"view", nonce, view)]) + except Exception: # pylint: disable=broad-exception-caught + # Garbage, a timeout or a dropped peer: it just gets no answer. + pass + finally: + self._slots.release() + + # --- probing ----------------------------------------------------------- + def _probe(self, addr: Addr) -> Optional[Dict[str, Any]]: + return probe( + addr, + self._secret, + self._timeout, + self._tls.client if self._tls is not None else None, + ) + + def _run(self) -> None: + while not self._closed.is_set(): + try: + self._tick() + except Exception: # pylint: disable=broad-exception-caught + if self._closed.is_set(): + return + logger.exception("dash cluster lock probe failed") + self._closed.wait(self._interval) + + def _tick(self) -> None: + # pylint: disable=too-many-branches,too-many-return-statements + started = time.monotonic() + peers = list(self._peers()) + views = {} + for addr, view in zip(peers, self._pool.map(self._probe, peers)): + if view is not None and view["id"] != self.id: + views[view["id"]] = (addr, view) + if self._closed.is_set(): + return + if self._majority is not None: + self._vote(views) + + state = self._state + if state.role == FOLLOWER: + if state.owner_id in views: + self._misses = 0 + else: + # Its owner may be briefly unreachable: stick with it rather + # than flap to another owner or claim. + self._misses += 1 + if self._misses < self._miss_limit: + return + + owners = { + view_id: (addr, view) + for view_id, (addr, view) in views.items() + if view["role"] == OWNER + } + if owners: + self._misses = 0 + self._deferred = 0 + if state.role == OWNER: + if self._majority is not None: + if not self._leased(): + # Peers may already count it as electing: never renew. + self._step_down() + return + following = [ + view + for _, view in views.values() + if view["role"] == FOLLOWER and view["term"] == state.term + ] + if 1 + len(following) >= self._majority: + self._quorum_at = started + self._resolve_owners(owners) + return + if owners: + # Longest owned, then lowest id. Ages are monotonic durations, so + # wall clocks that disagree across hosts do not matter. + owner_id = min(owners, key=lambda o: (-owners[o][1]["age"], o)) + self._follow(owner_id, *owners[owner_id]) + return + + if self._resigned(): + self._set(LockState(ELECTING)) + return + + if self._majority is not None: + if self._may_claim(started): + self._claim(started) + else: + self._set(LockState(ELECTING)) + return + + # No owner anywhere: the lowest id claims. Wait on a lower one only so + # long, in case it follows an owner this replica cannot reach. + if all( + self.id < other + for other, (_, view) in views.items() + if not view.get("resigned") + ) or (self._deferred >= self._miss_limit): + self._claim(started) + else: + self._deferred += 1 + self._set(LockState(ELECTING)) + + def _claim(self, started: float) -> None: + if self._resigned(): # resigned while this round ran + return + self._deferred = 0 + self._misses = 0 + self._owned_since = time.monotonic() + # Majority mode: lease from the probe round that saw the backing, not + # from now. A voter may switch right after answering, and a slow + # round would otherwise stretch this lease past that switch. + self._quorum_at = started + self._rivals = [] + self._set(LockState(OWNER, secrets.token_hex(8), self.id)) + + def _vote(self, views: Dict[str, Tuple[Addr, Dict[str, Any]]]) -> None: + """Back the lowest electing id in sight, and track who backs this one. + + A candidate that never manages to claim (it cannot reach a majority + itself) is passed over for a while, so the others are not stuck.""" + now = time.monotonic() + if self._state.role != ELECTING: + candidate = None + else: + self._banned = {i: t for i, t in self._banned.items() if t > now} + electing = [ + view_id + for view_id, (_, view) in views.items() + if view["role"] == ELECTING + and view_id not in self._banned + and not view.get("resigned") + ] + if not self._resigned(): + electing.append(self.id) + candidate = min(electing) if electing else None + stuck = now - self._ballot_since > 3 * self.lease + if ( + candidate is not None + and candidate == self._ballot[0] != self.id + and stuck + ): + self._banned[candidate] = now + 3 * self.lease + if candidate != self._ballot[0]: + self._ballot = (candidate, self._ballot[1] + 1) + self._ballot_since = now + backers = {} + for view_id, (_, view) in views.items(): + ballot = view.get("ballot") + if view["role"] != ELECTING or not ballot or ballot[0] != self.id: + continue + seen = self._backers.get(view_id) + same = seen is not None and seen[0] == ballot[1] + backers[view_id] = seen if same else (ballot[1], now) + self._backers = backers + + def _may_claim(self, started: float) -> bool: + """A majority, this replica included, that has backed it without a + break for longer than a lease, up to ``started``: the lease runs from + then, and a voter may have switched since it answered. + + A ballot stands for one candidate; any change, following an owner + included, bumps its counter and restarts the run. An owner renews only + from peers that follow it, and two majorities share a peer: a peer + that backed this replica for a whole lease neither followed an owner + (whose lease has run out since) nor backed another claimant then. + """ + assert self._majority is not None + if self._state.role == FOLLOWER: + return False + if self._ballot[0] != self.id or started - self._ballot_since <= self.lease: + return False + backed = [ + since for _, since in self._backers.values() if started - since > self.lease + ] + return 1 + len(backed) >= self._majority + + def _step_down(self) -> None: + self._rivals = [] + self._misses = 0 + self._deferred = 0 + self._set(LockState(ELECTING)) + + def _resolve_owners(self, owners: Dict[str, Tuple[Addr, Dict[str, Any]]]) -> None: + """Settle which of several owners keeps owning. + + Both sides comparing ages would deadlock: each measures its own age + now and the other's as reported a moment ago, so two owners that + claimed within a round trip of each other would each think they are + older. Instead only the lower id judges. It steps down to an older + owner, or keeps owning and lists the younger ones as rivals; an owner + steps down once a lower id lists it. + """ + judged_by = [ + o for o in owners if o < self.id and self.id in owners[o][1]["rivals"] + ] + if judged_by: + winner = min(judged_by) + self._follow(winner, *owners[winner]) + return + age = time.monotonic() - self._owned_since + older = [o for o in owners if o > self.id and owners[o][1]["age"] > age] + if older: + winner = max(older, key=lambda o: owners[o][1]["age"]) + self._follow(winner, *owners[winner]) + return + self._rivals = sorted(o for o in owners if o > self.id) + + def _follow(self, owner_id: str, addr: Addr, view: Dict[str, Any]) -> None: + self._rivals = [] + self._set(LockState(FOLLOWER, view["term"], owner_id, addr, view.get("advert"))) + + def _set(self, state: LockState) -> None: + with self._cond: + if state == self._state or self._closed.is_set(): + return + self._state = state + self._cond.notify_all() + if self._on_change is not None: + try: + self._on_change(state) + except Exception: # pylint: disable=broad-exception-caught + logger.exception("dash cluster lock on_change failed") diff --git a/dash/_shared_storage/_engine.py b/dash/_shared_storage/_engine.py index fc6ac6fd17..58cc48bdba 100644 --- a/dash/_shared_storage/_engine.py +++ b/dash/_shared_storage/_engine.py @@ -285,6 +285,13 @@ async def _apoll(self, t: _Topic, after_seq: int, timeout: float) -> PollResult: if waiter in t.waiters: t.waiters.remove(waiter) + def abandon(self) -> None: + """Close without persisting: this engine lost its ownership.""" + persistence, self._persistence = self._persistence, None + if persistence is not None: + persistence.abandon() + self.close() + def close(self) -> None: self._closed = True if self._persistence is not None: diff --git a/dash/_shared_storage/_env.py b/dash/_shared_storage/_env.py index e8d80d1b83..67cc404be0 100644 --- a/dash/_shared_storage/_env.py +++ b/dash/_shared_storage/_env.py @@ -5,10 +5,12 @@ """ import functools +import os from typing import Any, Dict, Optional from urllib.parse import parse_qsl, unquote, urlencode, urlparse from ..exceptions import InvalidConfig +from .cluster import DEFAULT_PORT, SECRET_ENV, ClusterSharedStorage from .diskcache import DiskcacheSharedStorage, _require_diskcache from .local import LocalSharedStorage from .redis import RedisSharedStorage, _require_redis @@ -20,7 +22,8 @@ def _invalid(reason: str) -> InvalidConfig: # The value can hold credentials, so it stays out of the message. return InvalidConfig( f"{ENV_VAR} is not valid: {reason}. Use 'local', 'none', " - "'diskcache:///absolute/path', or a redis:// or rediss:// URL." + "'diskcache:///absolute/path', a redis:// or rediss:// URL, or " + "cluster://host[:port]." ) @@ -40,6 +43,54 @@ def _redis_from_url(raw: str) -> Any: return functools.partial(RedisSharedStorage, url=url, **kwargs) +_CLUSTER_OPTIONS = ("tls_cert", "tls_key", "tls_ca", "replicas") + + +def _cluster_from_url(raw: str) -> Any: + parsed = urlparse(raw) + try: + host = parsed.hostname + port = parsed.port + except ValueError: + raise _invalid("cluster needs a valid port") from None + if port is None: + port = DEFAULT_PORT + elif port == 0: + raise _invalid("cluster needs a valid port") + if not host: + raise _invalid("cluster needs a host that resolves to every replica") + if parsed.path not in ("", "/") or parsed.fragment: + raise _invalid("cluster takes only a host, a port, a secret and options") + options: Dict[str, Any] = {} + # Not parse_qsl: it turns "+" into a space, and these are file paths. + for pair in filter(None, parsed.query.split("&")): + name, _, value = pair.partition("=") + if name not in _CLUSTER_OPTIONS or name in options or not value: + raise _invalid( + "cluster takes only tls_cert, tls_key, tls_ca and replicas, once each" + ) + options[name] = unquote(value) + if "replicas" in options: + replicas = options["replicas"] + if not (replicas.isascii() and replicas.isdigit()) or int(replicas) < 1: + raise _invalid("cluster replicas must be a positive integer") + options["replicas"] = int(replicas) + if bool(options.get("tls_cert")) != bool(options.get("tls_key")): + raise _invalid("cluster TLS needs both tls_cert and tls_key") + if port >= 65535: + raise _invalid("cluster needs a port below 65535, the next one is used too") + if parsed.username and not parsed.password: + raise _invalid("put the cluster secret after a colon: cluster://:secret@host") + secret = unquote(parsed.password) if parsed.password else None + if not secret and not os.environ.get(SECRET_ENV): + raise _invalid( + f"cluster needs a secret: cluster://:secret@host or {SECRET_ENV}" + ) + return functools.partial( + ClusterSharedStorage, host=host, port=port, secret=secret, **options + ) + + def storage_from_env(value: Optional[str]) -> Any: """Turn a ``DASH_SHARED_STORAGE`` value into a ``shared_storage`` argument. @@ -68,8 +119,5 @@ def storage_from_env(value: Optional[str]) -> Any: _require_diskcache() return functools.partial(DiskcacheSharedStorage, directory=unquote(parsed.path)) if scheme == "cluster": - raise InvalidConfig( - f"{ENV_VAR}: the cluster:// backend is not supported in this " - "version of Dash." - ) + return _cluster_from_url(raw) raise _invalid("unknown backend") diff --git a/dash/_shared_storage/_persistence.py b/dash/_shared_storage/_persistence.py index 1032a20bc4..e9257d92cd 100644 --- a/dash/_shared_storage/_persistence.py +++ b/dash/_shared_storage/_persistence.py @@ -272,6 +272,17 @@ def _run(self) -> None: # not silently kill the flush thread and stop all persistence. logger.exception("shared-storage persist-reset flush failed") + def abandon(self) -> None: + """Stop without the final flush: another owner has the store now, and + this one's state would overwrite it.""" + if self._closed: + return + self._closed = True + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=self._flush_interval + 5) + self._drain() + def close(self) -> None: if self._closed: return diff --git a/dash/_shared_storage/_transport.py b/dash/_shared_storage/_transport.py index 97eb2f3f94..0ebb43813c 100644 --- a/dash/_shared_storage/_transport.py +++ b/dash/_shared_storage/_transport.py @@ -4,10 +4,12 @@ (AF_UNIX where available, TCP loopback otherwise). Messages are length-prefixed: a 4-byte big-endian length followed by a body encoded by ``_codec`` (msgspec msgpack, or JSON without the ``dash[shared_storage]`` extra). The codec is -data-only -- the socket is localhost-only, but deserializing untrusted bytes off -a socket is a remote-code-execution hazard, so the transport carries only data. The channel is -additionally gated by a per-owner random token; only same-host clients that read -the owner's advertisement file (written 0600) can attach. +data-only: deserializing untrusted bytes off a socket is a remote-code-execution +hazard, so the transport carries only data. The channel is additionally gated by +a per-owner random token. Locally only same-host clients that read the owner's +advertisement file (written 0600) can attach; a cluster owner's socket is +reachable from the other replicas, so what a connection may do before it shows +the token is bounded in time, size and number. The consequence is that stored values and published messages must be JSON-serializable -- the same constraint as ``dcc.Store`` and callback outputs. @@ -20,13 +22,21 @@ import asyncio import socket +import ssl import struct +import sys import threading -from typing import Any, Optional, Tuple +import time +from typing import Any, Callable, Optional, Set, Tuple from ._codec import decode, encode EOF = object() # returned by recv_frame on a clean close +_HANDSHAKE_TIMEOUT = 5.0 +# Connections that have not shown the token yet, and the largest frame one may +# send before it does. +_MAX_HANDSHAKES = 64 +_MAX_TOKEN_FRAME = 1024 OK = ["ok", None] @@ -47,11 +57,44 @@ def _recv_exactly(sock: socket.socket, n: int) -> Optional[bytes]: return b"".join(chunks) -def recv_frame(sock: socket.socket) -> Any: +class _Expiry: + """Shuts ``sock`` down after the handshake timeout unless stopped first.""" + + def __init__(self, sock: socket.socket): + self._sock = sock + self._lock = threading.Lock() + self._done = False + self._timer = threading.Timer(_HANDSHAKE_TIMEOUT, self._expire) + self._timer.daemon = True + self._timer.start() + + def _expire(self) -> None: + with self._lock: + if self._done: + return + self._done = True + try: + self._sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + def stop(self) -> bool: + """Whether it was stopped in time (the socket was not shut down).""" + self._timer.cancel() + with self._lock: + if self._done: + return False + self._done = True + return True + + +def recv_frame(sock: socket.socket, max_size: Optional[int] = None) -> Any: header = _recv_exactly(sock, 4) if header is None: return EOF (length,) = struct.unpack("!I", header) + if max_size is not None and length > max_size: + raise ValueError("frame too large") body = _recv_exactly(sock, length) if body is None: return EOF @@ -75,13 +118,30 @@ async def arecv_frame(reader: asyncio.StreamReader) -> Any: class OwnerServer: - """Serves one StoreEngine to client workers over ``listen_sock``.""" + """Serves one StoreEngine to client workers over ``listen_sock``. + + ``guard``, when given, is checked before every request; once it returns + False the server drops the connection instead of answering, so a cluster + owner that lost its term stops taking writes. + """ - def __init__(self, engine, listen_sock: socket.socket, token: str): + def __init__( + self, + engine, + listen_sock: socket.socket, + token: str, + guard: Optional[Callable[[], bool]] = None, + ssl_context: Optional[ssl.SSLContext] = None, + ): self._engine = engine + self._ssl = ssl_context self._sock = listen_sock self._token = token + self._guard = guard self._closed = threading.Event() + self._conns: Set[socket.socket] = set() + self._conns_lock = threading.Lock() + self._handshakes = threading.BoundedSemaphore(_MAX_HANDSHAKES) self._accept_thread = threading.Thread( target=self._accept_loop, name="dash-shared-owner", daemon=True ) @@ -92,25 +152,74 @@ def start(self) -> None: def _accept_loop(self) -> None: while not self._closed.is_set(): + # Wait for a slot rather than turn a client away: a refused client + # takes the owner for dead. + if not self._handshakes.acquire( # pylint: disable=consider-using-with + timeout=0.5 + ): + continue try: conn, _ = self._sock.accept() except OSError: - break + self._handshakes.release() + if self._closed.is_set(): + break + # Out of file descriptors or similar: an owner that stops + # accepting still looks alive to its peers, so keep trying. + time.sleep(0.1) + continue threading.Thread(target=self._handle, args=(conn,), daemon=True).start() + def _serving(self) -> bool: + return not self._closed.is_set() and (self._guard is None or self._guard()) + + def _handshake(self, conn: socket.socket): + """The connection, TLS wrapped if need be, once it showed the token; + None (and closed) otherwise.""" + # A socket timeout bounds each read, not the whole handshake: a client + # dripping a byte at a time would keep its slot forever. + expiry = _Expiry(conn) + try: + conn.settimeout(_HANDSHAKE_TIMEOUT) + if self._ssl is not None: + conn = self._ssl.wrap_socket(conn, server_side=True) + if recv_frame(conn, _MAX_TOKEN_FRAME) == self._token and expiry.stop(): + conn.settimeout(None) + return conn + except Exception: # pylint: disable=broad-exception-caught + pass # garbage, a timeout, a failed TLS handshake + finally: + expiry.stop() + self._handshakes.release() + try: + conn.close() + except OSError: + pass + return None + def _handle(self, conn: socket.socket) -> None: + conn = self._handshake(conn) + if conn is None: + return + with self._conns_lock: + if self._closed.is_set(): + conn.close() + return + self._conns.add(conn) try: - if recv_frame(conn) != self._token: + if not self._serving(): return send_frame(conn, OK) - while not self._closed.is_set(): + while True: req = recv_frame(conn) - if req is EOF: + if req is EOF or not self._serving(): break send_frame(conn, self._dispatch(req)) except (OSError, EOFError, ValueError): pass finally: + with self._conns_lock: + self._conns.discard(conn) try: conn.close() except OSError: @@ -140,37 +249,104 @@ def _dispatch(self, req): # pylint: disable=too-many-return-statements def close(self) -> None: self._closed.set() - try: - self._sock.close() - except OSError: - pass + # close() alone does not wake a thread blocked in accept() on Linux, + # and clients of a closed owner must notice now, not on their next + # request. + with self._conns_lock: + conns = list(self._conns) + for sock in [self._sock, *conns]: + try: + sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + try: + sock.close() + except OSError: + pass self._engine.close() async def aconnect_to_owner( - family: int, address, token: str, timeout: float = 5.0 + family: int, + address, + token: str, + timeout: float = 5.0, + ssl_context: Optional[ssl.SSLContext] = None, ) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]: - """Async counterpart of :func:`connect_to_owner` (asyncio streams).""" - if family == socket.AF_INET: - host, port = address - opener = asyncio.open_connection(host, port) - else: + """Async counterpart of :func:`connect_to_owner` (asyncio streams). The + timeout covers the handshake too: an owner that accepts but never answers + must not hang the caller.""" + if family == getattr(socket, "AF_UNIX", None): opener = asyncio.open_unix_connection(address) + else: + host, port = address + opener = asyncio.open_connection(host, port, ssl=ssl_context) reader, writer = await asyncio.wait_for(opener, timeout) - await asend_frame(writer, token) - if await arecv_frame(reader) != OK: + try: + await asyncio.wait_for(asend_frame(writer, token), timeout) + ok = await asyncio.wait_for(arecv_frame(reader), timeout) == OK + except BaseException: + writer.close() + raise + if not ok: writer.close() raise ConnectionError("shared-storage owner rejected the handshake") return reader, writer -def connect_to_owner(family: int, address, token: str, timeout: float = 5.0): +# l_onoff=1, l_linger=0: close() resets the connection and drops what is queued. +_ABORT_LINGER = struct.pack("HH" if sys.platform == "win32" else "ii", 1, 0) + + +def _drop_unsent(sock) -> None: + try: + if sock is not None and sock.family != getattr(socket, "AF_UNIX", None): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, _ABORT_LINGER) + except OSError: + pass + + +def abort(sock: socket.socket) -> None: + """Close a connection to the owner that failed, dropping any request the + kernel still holds. A plain close keeps retransmitting it, so after a + partition heals the old owner would apply a write the caller has since + retried on the new owner, over newer writes.""" + _drop_unsent(sock) + try: + sock.close() + except OSError: + pass + + +def aabort(writer: asyncio.StreamWriter) -> None: + """``abort`` for an asyncio stream.""" + _drop_unsent(writer.get_extra_info("socket")) + writer.transport.abort() + + +def connect_to_owner( + family: int, + address, + token: str, + timeout: float = 5.0, + ssl_context: Optional[ssl.SSLContext] = None, +): """Open a client connection and complete the token handshake.""" - sock = socket.socket(family, socket.SOCK_STREAM) - sock.settimeout(timeout) - sock.connect(address) - send_frame(sock, token) - if recv_frame(sock) != OK: + if family == getattr(socket, "AF_UNIX", None): + sock = socket.socket(family, socket.SOCK_STREAM) + sock.settimeout(timeout) + sock.connect(address) + else: + sock = socket.create_connection(tuple(address), timeout=timeout) + if ssl_context is not None: + sock = ssl_context.wrap_socket(sock) + try: + send_frame(sock, token) + ok = recv_frame(sock) == OK + except BaseException: + sock.close() + raise + if not ok: sock.close() raise ConnectionError("shared-storage owner rejected the handshake") sock.settimeout(None) diff --git a/dash/_shared_storage/cluster.py b/dash/_shared_storage/cluster.py new file mode 100644 index 0000000000..3fc613c231 --- /dev/null +++ b/dash/_shared_storage/cluster.py @@ -0,0 +1,523 @@ +"""Shared storage across the replicas of an app, with no external service. + +``ClusterSharedStorage`` is ``LocalSharedStorage`` stretched across pods or +containers. In each replica the first process to bind the cluster port runs a +:class:`ClusterLock`, which elects one owner among the replicas. The owner's +lock process hosts the ``StoreEngine`` on the next port up; every other worker, +in any replica, proxies to it over TCP. Workers that did not get the cluster +port ask their replica's lock process, on loopback, where the owner is. + +The owner's term is the token clients present, so an owner change looks like +a re-election does locally: the buffer is gone and readers get +``SharedStorageGap``. A deposed owner's server stops answering at once. +Without ``tls_cert``/``tls_key`` data crosses the network unencrypted, so keep +the ports on a private network, as with a Redis without TLS; with them, every +connection between replicas is mutual TLS. +""" + +import atexit +import errno +import functools +import hashlib +import hmac +import logging +import os +import socket +import ssl +import threading +import time +from typing import Any, Callable, Dict, List, Optional, Tuple + +from ._cluster_lock import ( + ELECTING, + FOLLOWER, + OWNER, + TLS, + Addr, + ClusterLock, + LockState, + listen, + probe, + resolve_peers, + tls_contexts, +) +from ._engine import DEFAULT_BUFFER +from ._transport import OwnerServer +from .base import SharedStorageError +from .local import LocalSharedStorage, _Coordinator + +DEFAULT_PORT = 7100 +SECRET_ENV = "DASH_SECRET_KEY" + +_PROBE_INTERVAL = 1.0 +_PROBE_TIMEOUT = 0.5 +# A probe over TLS is a full handshake: give it room on a busy pod. +_TLS_PROBE_TIMEOUT = 1.0 +_SETTLE_TIMEOUT = 15.0 +# A pod that vanishes does not close its sockets, so a client could wait on it +# forever: keep long polls short and give up on an answer that never comes. +_CLIENT_POLL_TIMEOUT = 5.0 +_RECV_TIMEOUT = _CLIENT_POLL_TIMEOUT + 5.0 +# Followers need a few missed probes to give up on a dead owner. +_FAILOVER_WINDOW = 10.0 +# With replicas set, a claim also waits for the old owner's lease to run out. +_QUORUM_FAILOVER_WINDOW = 30.0 +_ADDR_IN_USE = {errno.EADDRINUSE, getattr(errno, "WSAEADDRINUSE", errno.EADDRINUSE)} + +logger = logging.getLogger(__name__) + + +def _derive_secret(secret: str) -> bytes: + # The app's signing secret signs other things too: never use it as is. + return hmac.new( + secret.encode(), b"dash-shared-storage-cluster", hashlib.sha256 + ).digest() + + +def _load_tls( + cert: Optional[str], key: Optional[str], ca: Optional[str] +) -> Optional[TLS]: + if cert is None and key is None and ca is None: + return None + if not (cert and key): + raise SharedStorageError("cluster TLS needs both tls_cert and tls_key") + try: + return tls_contexts(cert, key, ca) + except (OSError, ssl.SSLError) as err: + raise SharedStorageError(f"cannot load the cluster TLS files: {err}") from err + + +def starts_at_boot(storage: Any) -> bool: + """Whether a ``shared_storage`` argument (an instance, or the partial + ``DASH_SHARED_STORAGE`` builds) must start with the process.""" + if isinstance(storage, functools.partial): + return ( + isinstance(storage.func, type) + and issubclass(storage.func, ClusterSharedStorage) + and storage.keywords.get("replicas") is not None + ) + return isinstance(storage, ClusterSharedStorage) and storage.starts_at_boot + + +class _ClusterCoordinator(_Coordinator): # pylint: disable=too-many-instance-attributes + """Elects the owner across replicas with a ClusterLock instead of a local + socket bind. Role and token follow the lock: owner while it holds a term, + client of the current owner otherwise.""" + + client_poll_timeout = _CLIENT_POLL_TIMEOUT + recv_timeout = _RECV_TIMEOUT + failover_window = _FAILOVER_WINDOW + + def __init__( # pylint: disable=too-many-arguments + self, + host: str, + port: int, + secret: bytes, + peers: Callable[[], List[Addr]], + buffer_size: int, + mode: str, + path: Optional[str], + flush_interval: float, + probe_interval: float, + settle_timeout: float, + tls: Optional[TLS] = None, + replicas: Optional[int] = None, + ): + super().__init__( + f"cluster-{host}-{port}", buffer_size, mode, path, flush_interval + ) + self._port = port + self._data_port = port + 1 + self._secret = secret + self._peers = peers + self._probe_interval = probe_interval + self._settle_timeout = settle_timeout + self._cluster: Optional[ClusterLock] = None + self._term: Optional[str] = None + self._closed = False + self._forgotten = False + self._changed = threading.Event() + self._tls = tls + self.client_ssl = tls.client if tls is not None else None + self._probe_timeout = _PROBE_TIMEOUT if tls is None else _TLS_PROBE_TIMEOUT + self._replicas = replicas + if replicas is not None: + self.failover_window = _QUORUM_FAILOVER_WINDOW + + def is_owner(self) -> bool: + self.ensure() + if self._role == "owner" and not self._holds_term(): + with self._lock: + if self._role == "owner" and not self._holds_term(): + self._stop_serving() + self._elect() + return self._role == "owner" + + def connect(self) -> Tuple[socket.socket, str]: + sock, token = super().connect() + sock.settimeout(self.recv_timeout) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + return sock, token + + def needs_election(self) -> bool: + return self._role is None or (self._role == "owner" and not self._holds_term()) + + def _holds_term(self) -> bool: + return self._cluster is not None and self._cluster.is_owner(self._term) + + def on_owner_lost(self) -> None: + with self._lock: + if self._role == "owner" and self._holds_term(): + return + self._stop_serving() + self._role = None + self._elect() + + # --- election ---------------------------------------------------------- + def _elect(self) -> None: + if self._closed: + raise SharedStorageError("shared storage is closed") + deadline = time.monotonic() + self._settle_timeout + while True: + if self._cluster is None: + self._try_hold_lock() + if self._cluster is not None: + state = self._cluster.wait_settled(deadline - time.monotonic()) + if self._apply(state): + return + elif self._follow_local(): + return + if time.monotonic() >= deadline: + raise SharedStorageError( + "no shared-storage cluster owner was elected in " + f"{self._settle_timeout:g}s" + ) + time.sleep(min(0.1, self._probe_interval)) + + def _try_hold_lock(self) -> None: + try: + self._cluster = ClusterLock( + peers=self._peers, + secret=self._secret, + bind=("", self._port), + advert={"data_port": self._data_port}, + on_change=self._on_change, + tls=self._tls, + probe_interval=self._probe_interval, + probe_timeout=self._probe_timeout, + replicas=self._replicas, + ).start() + except OSError as err: + if err.errno in _ADDR_IN_USE: + return # another process of this replica holds the port + raise SharedStorageError( + f"cannot listen on the cluster port {self._port}: {err}" + ) from err + threading.Thread( + target=self._apply_changes, name="dash-cluster-changes", daemon=True + ).start() + atexit.register(self.close) + + def _follow_local(self) -> bool: + """Learn the owner from this replica's lock process.""" + view = probe( + ("127.0.0.1", self._port), + self._secret, + self._probe_timeout, + self.client_ssl, + ) + if view is None: + return False + if view["role"] == ELECTING: + return False + host = "127.0.0.1" if view["role"] == OWNER else view["owner_host"] + return self._follow(host, view.get("advert"), view["term"]) + + def _apply(self, state: LockState) -> bool: + if state.role == OWNER: + # A lapsed lease the lock has not stepped down from yet: serving + # would start an empty store under the same term. + if self._cluster is None or not self._cluster.is_owner(state.term): + return False + return self._serve_or_resign(state.term) + if state.role == FOLLOWER and state.owner_addr is not None: + return self._follow(state.owner_addr[0], state.advert, state.term) + return False + + def _follow(self, host: str, advert, term: Optional[str]) -> bool: + if not isinstance(advert, dict) or not term: + return False + port = advert.get("data_port") + if not isinstance(port, int) or isinstance(port, bool): + return False + self._family = socket.AF_INET6 if ":" in host else socket.AF_INET + self._address = (host, port) + self._token = term + self._role = "client" + return True + + def _serve(self, term: Optional[str]) -> None: + assert term is not None + if self._role == "owner" and self._term == term: + return + self._stop_serving() + sock = self._listen_data() + engine = None + try: + engine = self._new_engine() + server = OwnerServer( + engine, + sock, + term, + guard=lambda: self._guard(term), + ssl_context=self._tls.server if self._tls is not None else None, + ) + server.start() + except BaseException: + sock.close() + if engine is not None: + engine.close() + raise + self._engine, self._server, self._term = engine, server, term + self._family, self._address = socket.AF_INET, ("127.0.0.1", self._data_port) + self._token = term + self._role = "owner" + + def _serve_or_resign(self, term: str) -> bool: + try: + self._serve(term) + return True + except Exception as err: # pylint: disable=broad-exception-caught + # Followers would keep following an owner that serves nothing. + logger.warning( + "dash cluster: cannot serve the store (data port %s), leaving " + "it to another replica: %r", + self._data_port, + err, + ) + if self._cluster is not None: + self._cluster.resign(term) + return False + + def _guard(self, term: str) -> bool: + return self._cluster is not None and self._cluster.is_owner(term) + + def _listen_data(self) -> socket.socket: + # A server closed a moment ago, ours or a previous process's, can hold + # the port briefly. + for attempt in range(20): + try: + return listen("", self._data_port) + except OSError: + if attempt == 19: + raise + time.sleep(0.1) + raise AssertionError("unreachable") + + def _stop_serving(self) -> None: + server, engine = self._server, self._engine + self._server = self._engine = None + if server is not None: + if engine is not None and not self._holds_term(): + # Deposed: a persistent store must not flush this owner's + # state over the new owner's on a shared volume. + engine.abandon() + # Also closes the engine, flushing a persistent store. + server.close() + self._term = None + + def _on_change(self, _state: LockState) -> None: + # Runs on the probe thread. A request electing under self._lock waits + # for that thread to settle the lock, so it must not wait on the lock. + self._changed.set() + + def _apply_changes(self) -> None: + while True: + self._changed.wait() + self._changed.clear() + try: + if not self._apply_change(): + return + except Exception: # pylint: disable=broad-exception-caught + logger.exception("dash cluster: applying a lock change failed") + + def _apply_change(self) -> bool: + """Apply the lock's current state; False once there is no lock.""" + with self._lock: + cluster = self._cluster + if self._closed or cluster is None: + return False + state = cluster.state + if state.role == OWNER: + # Serve at once: followers start connecting as soon as they + # see this replica as owner. Never serve a lapsed lease, a + # step down follows. + if cluster.is_owner(state.term): + self._serve_or_resign(state.term) + elif self._role == "owner" or ( + self._role == "client" and state.term != self._token + ): + self._stop_serving() + self._role = None + return True + + def forget(self) -> None: + """In a forked child: let go of the parent's sockets without shutting + them down, which would stop them in the parent too. Threads do not + survive a fork, so nothing else here is live.""" + # Its close() would flush the parent's store as of the fork over newer + # data, or hang on a lock some parent thread held. + self._forgotten = True + atexit.unregister(self.close) + server = self._server + for sock in ( + getattr(self._cluster, "_sock", None), + getattr(server, "_sock", None), + *getattr(server, "_conns", ()), + ): + if sock is not None: + try: + sock.close() + except OSError: + pass + + def close(self) -> None: + if self._forgotten: + return + with self._lock: + self._closed = True + self._changed.set() + self._stop_serving() + if self._cluster is not None: + self._cluster.close() + self._cluster = None + self._role = None + + +class ClusterSharedStorage(LocalSharedStorage): + """Shared storage across every replica of an app, with no external service. + + Replicas find each other through ``host``, a name that resolves to all of + them (a Kubernetes headless Service, a podman network alias), and elect one + owner that holds the store. Each replica needs ``port`` (the election) and + ``port + 1`` (the store) reachable from the others. ``peers`` replaces the + DNS lookup with a function returning ``(host, port)`` lock addresses, for a + fixed list of hosts. + + All replicas share ``secret`` (default: ``$DASH_SECRET_KEY``), which they + prove to each other without sending it. Traffic is not encrypted unless + ``tls_cert`` and ``tls_key`` (PEM files) are given: then every connection + between replicas is mutual TLS, each side checking the other's + certificate against ``tls_ca`` (default: ``tls_cert``, so one self-signed + certificate mounted in every replica will do). Replicas reach each other by + IP, so hostnames are not checked. All replicas must agree on TLS. Each + certificate serves as both server and client certificate, so it must allow + client authentication (no extended key usage, or both serverAuth and + clientAuth). The files are read once: restart replicas after rotating them. + + When the owner goes, another replica takes over with an empty store + (``mode="memory"``) or what it recovers from ``path`` (the persistent + modes, which only help when ``path`` is on a volume the replicas share). + Readers get ``SharedStorageGap``. If replicas briefly elect two owners, + say when they all start at once, the one that owned longer wins and + writes made on the other in the meantime are lost. + + ``replicas``, the number of replicas the app runs (3 is the usual choice), + turns on majority mode: no owner without a majority of them in reach, so + a replica that starts alone waits for its peers and an owner cut off in a + minority stops owning before the others elect a new one. The store is + unavailable while no majority is up, failover takes 10 to 20 seconds, and + the store starts with the app process instead of on first use, so every + replica votes. Use an odd number: with 2, losing either one stops the + store. + """ + + def __init__( # pylint: disable=too-many-arguments + self, + host: Optional[str] = None, + port: int = DEFAULT_PORT, + secret: Optional[str] = None, + peers: Optional[Callable[[], List[Addr]]] = None, + buffer_size: int = DEFAULT_BUFFER, + mode: str = "memory", + path: Optional[str] = None, + flush_interval: float = 60.0, + probe_interval: float = _PROBE_INTERVAL, + settle_timeout: Optional[float] = None, + tls_cert: Optional[str] = None, + tls_key: Optional[str] = None, + tls_ca: Optional[str] = None, + replicas: Optional[int] = None, + ): + if host is None and peers is None: + raise SharedStorageError("ClusterSharedStorage needs a host or peers") + if replicas is not None and ( + not isinstance(replicas, int) or isinstance(replicas, bool) or replicas < 1 + ): + raise SharedStorageError("replicas must be a positive integer") + if settle_timeout is None: + settle_timeout = ( + _SETTLE_TIMEOUT if replicas is None else _QUORUM_FAILOVER_WINDOW + ) + secret = secret or os.environ.get(SECRET_ENV) + if not secret: + raise SharedStorageError( + "ClusterSharedStorage needs a secret shared by every replica: " + f"pass secret= or set {SECRET_ENV}" + ) + tls = _load_tls(tls_cert, tls_key, tls_ca) + if peers is None: + name: str = host or "" + peers = lambda: resolve_peers(name, port) # noqa: E731 + self._forked_in = os.getpid() + self._cluster_args: Dict[str, Any] = dict( + host=host or "peers", + port=port, + secret=_derive_secret(secret), + peers=peers, + probe_interval=probe_interval, + settle_timeout=settle_timeout, + tls=tls, + replicas=replicas, + ) + super().__init__( + namespace=f"cluster-{host}-{port}", + buffer_size=buffer_size, + mode=mode, + path=path, + flush_interval=flush_interval, + ) + + @property + def starts_at_boot(self) -> bool: + """In majority mode every replica must take part in the election + before any request reaches it, or the first replica to get one waits + for a majority that never shows up.""" + return self._cluster_args["replicas"] is not None + + def after_fork(self) -> None: + """Start afresh in a forked child (gunicorn ``--preload``). The parent + keeps its lock; the child finds it on loopback like any other worker.""" + if self._forked_in == os.getpid(): + return # one instance shared by several apps + self._forked_in = os.getpid() + coord = self._coord + assert isinstance(coord, _ClusterCoordinator) + coord.forget() + self._coord = self._new_coordinator(*self._coord_args) + self._conn = None + self._conn_token = None + self._conn_lock = threading.Lock() + self._aconns = {} + + def _new_coordinator( # pylint: disable=too-many-arguments + self, namespace, buffer_size, mode, path, flush_interval + ) -> _Coordinator: + self._coord_args = (namespace, buffer_size, mode, path, flush_interval) + return _ClusterCoordinator( + buffer_size=buffer_size, + mode=mode, + path=path, + flush_interval=flush_interval, + **self._cluster_args, + ) diff --git a/dash/_shared_storage/local.py b/dash/_shared_storage/local.py index 859b0660fa..6bdaf0f7f7 100644 --- a/dash/_shared_storage/local.py +++ b/dash/_shared_storage/local.py @@ -32,6 +32,8 @@ from ._transport import ( EOF, OwnerServer, + aabort, + abort, aconnect_to_owner, arecv_frame, asend_frame, @@ -57,6 +59,16 @@ def _default_namespace() -> str: return hashlib.sha1(raw).hexdigest()[:16] +def _file_id(path: str) -> Optional[Tuple[int, int, int]]: + """Which file is at ``path``: a socket file taken over and rebound there + is a different one, even on a reused inode (bind and chmod set ctime).""" + try: + st = os.stat(path) + except OSError: + return None + return st.st_dev, st.st_ino, st.st_ctime_ns + + def _paths(namespace: str): base = os.path.join(tempfile.gettempdir(), f"dash-shared-{namespace}") return base + ".sock", base + ".addr" @@ -173,6 +185,17 @@ def _try_bind(namespace: str, sock_path: str, addr_path: Optional[str] = None): class _Coordinator: """Owns this worker's role (owner or client) and re-elects on owner loss.""" + # Long-poll cycle for remote subscribers, and how long a client waits on + # the owner's answer (None: as long as it takes; a local owner that dies + # closes its sockets). + client_poll_timeout = _CLIENT_POLL_TIMEOUT + recv_timeout: Optional[float] = None + # How long a call keeps retrying while a new owner is found. Locally the + # next owner is a bind away; a cluster needs a few probes to notice. + failover_window = 0.0 + # TLS context for client connections to the owner (cluster only). + client_ssl: Optional[Any] = None + def __init__( self, namespace: str, @@ -194,6 +217,7 @@ def __init__( self._family = None self._address = None self._token: Optional[str] = None + self._sock_id: Optional[Tuple[int, int, int]] = None @property def engine(self) -> Optional[StoreEngine]: @@ -213,38 +237,53 @@ def is_owner(self) -> bool: self.ensure() return self._role == "owner" + def needs_election(self) -> bool: + """Whether the next is_owner() may elect, which can block: asyncio + callers run it in the executor then.""" + return self._role is None + + def _new_engine(self) -> StoreEngine: + engine = StoreEngine(self._buffer_size) + if self._mode != "memory": + assert self._path is not None + persistence = _Persistence( + self._path, self._mode, self._flush_interval, engine + ) + # Recover before serving (so clients see the restored state) and + # before attaching (so restored keys are not re-marked dirty). + persistence.recover() + engine.attach_persistence(persistence) + persistence.start() + return engine + def _elect(self) -> None: bound = _try_bind(self._namespace, self._sock_path, self._addr_path) if bound: listen_sock, family, address = bound token = secrets.token_hex(16) - engine = StoreEngine(self._buffer_size) + engine = None try: _write_advertisement(self._addr_path, family, address, token) - if self._mode != "memory": - assert self._path is not None - persistence = _Persistence( - self._path, self._mode, self._flush_interval, engine - ) - # Recover before serving (so clients see the restored state) - # and before attaching (so restored keys are not re-marked - # dirty). - persistence.recover() - engine.attach_persistence(persistence) - persistence.start() + engine = self._new_engine() server = OwnerServer(engine, listen_sock, token) server.start() except BaseException: # The socket already listens: left open, it would pass for a # live owner that never answers. listen_sock.close() - engine.close() + if engine is not None: + engine.close() for path in (self._sock_path, self._addr_path): with contextlib.suppress(OSError): os.unlink(path) raise self._engine, self._server = engine, server self._family, self._address, self._token = family, address, token + self._sock_id = ( + _file_id(address) + if family == getattr(socket, "AF_UNIX", None) + else None + ) self._role = "owner" # Best-effort cleanup of the socket/advertisement on clean exit; a # crash leaves them stale, which the next election self-heals. @@ -255,14 +294,28 @@ def _elect(self) -> None: ) self._role = "client" - def connect(self) -> socket.socket: - self.ensure() - assert self._family is not None and self._token is not None - return connect_to_owner(self._family, self._address, self._token) + def _target(self): + with self._lock: + self.ensure() + return self._family, self._address, self._token + + def connect(self) -> Tuple[socket.socket, str]: + """A connection to the current owner, and the owner's token: the owner + it belongs to, which may differ from the caller's last one.""" + family, address, token = self._target() + assert family is not None and token is not None + return ( + connect_to_owner(family, address, token, ssl_context=self.client_ssl), + token, + ) async def aconnect(self): - self.ensure() - return await aconnect_to_owner(self._family, self._address, self._token) + """Async :meth:`connect`. Call after an election, never during one.""" + family, address, token = self._target() + streams = await aconnect_to_owner( + family, address, token, ssl_context=self.client_ssl + ) + return streams, token def on_owner_lost(self) -> None: """The owner became unreachable; re-elect (may promote us to owner).""" @@ -279,13 +332,20 @@ def close(self) -> None: if self._engine is not None: # Triggers the persistence final flush (save-on-exit). self._engine.close() - for path in (self._sock_path, self._addr_path): - try: - os.unlink(path) - except OSError: - pass + self._unlink_own_files() self._role = None + def _unlink_own_files(self) -> None: + # Clients see the owner go before the final flush is done, and one may + # have taken over by now: leave its socket and advertisement alone. + with contextlib.suppress(OSError, ValueError, KeyError, TypeError): + with open(self._addr_path, "rb") as f: + if json.loads(f.read().decode("utf-8"))["token"] == self._token: + os.unlink(self._addr_path) + if self._sock_id is not None and _file_id(self._sock_path) == self._sock_id: + with contextlib.suppress(OSError): + os.unlink(self._sock_path) + class _LocalSubscription(Subscription): """A topic view that reads from the owner engine directly (owner role) or @@ -293,11 +353,16 @@ class _LocalSubscription(Subscription): cursor on reconnect so no buffered message is missed. """ - def __init__(self, coord: _Coordinator, topic: str, start_seq: int, call): + def __init__( # pylint: disable=too-many-arguments + self, coord: _Coordinator, topic: str, start_seq: int, call, token + ): self._coord = coord self._topic = topic self._cursor = start_seq self._call = call # the storage's short request/response channel + # The owner this cursor belongs to. Another owner numbers topics from + # scratch, so reading on from this cursor there would be wrong. + self._token = token self._conn: Optional[socket.socket] = None # Async (ASGI) client-role connection: reader/writer + its loop, so # close() from another thread can shut it via the loop. @@ -319,10 +384,18 @@ def close(self) -> None: with contextlib.suppress(RuntimeError): self._aloop.call_soon_threadsafe(writer.close) + def _check_owner(self, token: Optional[str] = None) -> None: + if (token or self._coord.token) != self._token: + raise SharedStorageGap( + "shared-storage owner changed; buffered messages were lost" + ) + def _poll_once(self, timeout: Optional[float] = None) -> PollResult: """One poll cycle. ``timeout`` overrides the role's long-poll default (``0`` never blocks).""" - if self._coord.is_owner(): + is_owner = self._coord.is_owner() + self._check_owner() + if is_owner: engine = self._coord.engine if engine is None or engine.closed: self._closed.set() # owner gone -> end iteration, don't busy-loop @@ -330,16 +403,22 @@ def _poll_once(self, timeout: Optional[float] = None) -> PollResult: if timeout is None: timeout = _OWNER_POLL_TIMEOUT return engine.poll(self._topic, self._cursor, timeout) - return self._client_poll(_CLIENT_POLL_TIMEOUT if timeout is None else timeout) + cycle = self._coord.client_poll_timeout + # Longer waits than a cycle would outlast the client's receive + # timeout; the caller polls again. + return self._client_poll(cycle if timeout is None else min(timeout, cycle)) def _client_poll(self, timeout: float) -> PollResult: for attempt in range(4): if self._closed.is_set(): return PollResult([], self._cursor, False) if self._conn is None: - prev_token = self._coord.token + prev_token = self._token try: - self._conn = self._coord.connect() + self._conn, token = self._coord.connect() + if token != self._token: + self._close_conn() + self._check_owner(token) except OSError as exc: # Owner unreachable: brief retries to the same owner, then # re-elect. A changed owner means its buffer is gone -> gap. @@ -365,14 +444,17 @@ def _client_poll(self, timeout: float) -> PollResult: raise SharedStorageError(val) return PollResult(*val) except (OSError, EOFError, ConnectionError): - if self._conn is not None: - try: - self._conn.close() - except OSError: - pass - self._conn = None # reconnect on the next attempt + self._close_conn() # reconnect on the next attempt return PollResult([], self._cursor, False) + def _close_conn(self) -> None: + conn, self._conn = self._conn, None + if conn is not None: + try: + conn.close() + except OSError: + pass + @staticmethod def _with_seq(res: PollResult): # Poll batches are contiguous, ending at last_seq, so each message's @@ -387,7 +469,9 @@ def poll(self, timeout: float = 0.0): # to the owner, like get/set -- no dedicated socket (and no thread # on the owner) per poll. Blocking polls keep their own connection # so they don't hold the shared one. + self._check_owner() res = PollResult(*self._call(["poll", self._topic, self._cursor, 0.0])) + self._check_owner() else: res = self._poll_once(timeout) if res.gap: @@ -416,13 +500,16 @@ async def _apoll_once(self) -> PollResult: """One long-poll cycle without leaving the event loop: the owner engine's ``apoll`` (owner role) or an asyncio-streams connection to the owner (client role) -- no executor thread per subscription either way.""" - if self._coord.is_owner(): + await _aelect(self._coord) + is_owner = self._coord.is_owner() + self._check_owner() + if is_owner: engine = self._coord.engine if engine is None or engine.closed: self._closed.set() return PollResult([], self._cursor, False) return await engine.apoll(self._topic, self._cursor, _OWNER_POLL_TIMEOUT) - return await self._aclient_poll(_CLIENT_POLL_TIMEOUT) + return await self._aclient_poll(self._coord.client_poll_timeout) async def _aclient_poll(self, timeout: float) -> PollResult: self._aloop = asyncio.get_running_loop() @@ -431,12 +518,17 @@ async def _aclient_poll(self, timeout: float) -> PollResult: return PollResult([], self._cursor, False) aconn = self._aconn if aconn is None: - prev_token = self._coord.token + prev_token = self._token try: - aconn = await self._coord.aconnect() + await _aelect(self._coord) + aconn, token = await self._coord.aconnect() + if token != self._token: + with contextlib.suppress(Exception): + aconn[1].close() + self._check_owner(token) except (OSError, asyncio.TimeoutError) as exc: if attempt >= 2: - self._coord.on_owner_lost() + await _aowner_lost(self._coord) if self._coord.token != prev_token: raise SharedStorageGap( "shared-storage owner changed; buffered " @@ -448,14 +540,16 @@ async def _aclient_poll(self, timeout: float) -> PollResult: reader, writer = aconn try: await asend_frame(writer, ["poll", self._topic, self._cursor, timeout]) - resp = await arecv_frame(reader) + resp = await asyncio.wait_for( + arecv_frame(reader), self._coord.recv_timeout + ) if resp is EOF: raise ConnectionError("owner closed the connection") status, val = resp if status == "err": raise SharedStorageError(val) return PollResult(*val) - except (OSError, EOFError, ConnectionError): + except (OSError, EOFError, ConnectionError, asyncio.TimeoutError): with contextlib.suppress(Exception): writer.close() self._aconn = None # reconnect on the next attempt @@ -476,6 +570,21 @@ async def _aiter_with_seq(self): self.close() +async def _aelect(coord: _Coordinator) -> None: + """Run an election that may block (a cluster waits on its peers) in the + executor, so it never stalls the event loop.""" + if coord.needs_election(): + await asyncio.get_running_loop().run_in_executor(None, coord.is_owner) + + +async def _aowner_lost(coord: _Coordinator) -> None: + await asyncio.get_running_loop().run_in_executor(None, coord.on_owner_lost) + + +class _OwnerGone(ConnectionError): + """This process stopped owning the store mid-call: retry on the new one.""" + + class _AsyncConn: """A client worker's asyncio-streams request/response channel to the owner, serialized by an asyncio.Lock (one request in flight per connection).""" @@ -483,23 +592,36 @@ class _AsyncConn: def __init__(self, coord: _Coordinator): self._coord = coord self._streams = None + self._token: Optional[str] = None self._lock: Optional[asyncio.Lock] = None async def call(self, req): if self._lock is None: self._lock = asyncio.Lock() async with self._lock: + if self._streams is not None and self._token != self._coord.token: + with contextlib.suppress(Exception): + self._streams[1].close() + self._streams = None if self._streams is None: - self._streams = await self._coord.aconnect() + await _aelect(self._coord) + self._streams, self._token = await self._coord.aconnect() reader, writer = self._streams try: - await asend_frame(writer, req) - resp = await arecv_frame(reader) + # An owner that stops reading would block drain() forever. + await asyncio.wait_for( + asend_frame(writer, req), self._coord.recv_timeout + ) + resp = await asyncio.wait_for( + arecv_frame(reader), self._coord.recv_timeout + ) if resp is EOF: raise ConnectionError("owner closed the connection") - except (OSError, EOFError, ConnectionError, asyncio.TimeoutError): + except BaseException: + # Cancelled included: the request may still be queued, and + # its answer would reach the next call. with contextlib.suppress(Exception): - writer.close() + aabort(writer) self._streams = None raise status, val = resp @@ -554,14 +676,20 @@ def __init__( ns = namespace or _default_namespace() if mode != "memory" and path is None: path = default_store_dir(ns) - self._coord = _Coordinator(ns, buffer_size, mode, path, flush_interval) + self._coord = self._new_coordinator(ns, buffer_size, mode, path, flush_interval) self._conn: Optional[socket.socket] = None + self._conn_token: Optional[str] = None self._conn_lock = threading.Lock() # Client role, asyncio callers: one asyncio-streams connection per # event loop (with its own asyncio.Lock), so a loop never blocks on the # sync connection or contends with request threads for it. self._aconns: "dict[asyncio.AbstractEventLoop, _AsyncConn]" = {} + def _new_coordinator( # pylint: disable=too-many-arguments + self, namespace, buffer_size, mode, path, flush_interval + ) -> "_Coordinator": + return _Coordinator(namespace, buffer_size, mode, path, flush_interval) + def start(self) -> None: self._coord.ensure() @@ -578,19 +706,36 @@ def close(self) -> None: # --- key/value + publish (short request/response) ---------------------- def _call(self, req): last_err: Optional[Exception] = None - for _ in range(3): - if self._coord.is_owner(): - return self._local(req) + deadline = time.monotonic() + self._coord.failover_window + attempt = 0 + while True: try: + if self._coord.is_owner(): + return self._local(req) return self._remote(req) except (OSError, EOFError, ConnectionError) as err: last_err = err - self._coord.on_owner_lost() + attempt += 1 + if attempt >= 3 and time.monotonic() >= deadline: + break + self._coord.on_owner_lost() + if attempt >= 3: + time.sleep(0.2) raise SharedStorageError(f"shared-storage owner unreachable: {last_err}") def _local(self, req): engine = self._coord.engine - assert engine is not None + if engine is None or engine.closed: + raise _OwnerGone("this process stopped owning the store") + result = self._apply(engine, req) + if engine.closed: + # Lost ownership while applying it: the write may be lost with the + # old store, so the caller retries on the new owner. + raise _OwnerGone("this process stopped owning the store") + return result + + @staticmethod + def _apply(engine: StoreEngine, req): # pylint: disable=too-many-return-statements op = req[0] if op == "get": return engine.get(req[1], req[2]) @@ -606,18 +751,21 @@ def _local(self, req): def _remote(self, req): with self._conn_lock: + if self._conn is not None and self._conn_token != self._coord.token: + try: + self._conn.close() + except OSError: + pass + self._conn = None if self._conn is None: - self._conn = self._coord.connect() + self._conn, self._conn_token = self._coord.connect() try: send_frame(self._conn, req) resp = recv_frame(self._conn) if resp is EOF: raise ConnectionError("owner closed the connection") - except (OSError, EOFError, ConnectionError): - try: - self._conn.close() - except OSError: - pass + except BaseException: + abort(self._conn) self._conn = None raise status, val = resp @@ -625,22 +773,35 @@ def _remote(self, req): raise SharedStorageError(val) return val - async def _acall(self, req): - if self._coord.is_owner(): - return self._local(req) + def _aconn(self) -> _AsyncConn: loop = asyncio.get_running_loop() conn = self._aconns.get(loop) if conn is None: + # Each asyncio.run() is a new loop: let go of the finished ones. + for old in list(self._aconns): + if old.is_closed(): + self._aconns.pop(old, None) conn = self._aconns[loop] = _AsyncConn(self._coord) + return conn + + async def _acall(self, req): last_err: Optional[Exception] = None - for _ in range(3): + deadline = time.monotonic() + self._coord.failover_window + attempt = 0 + while True: try: - return await conn.call(req) - except (OSError, EOFError, ConnectionError, asyncio.TimeoutError) as err: - last_err = err - self._coord.on_owner_lost() + await _aelect(self._coord) if self._coord.is_owner(): return self._local(req) + return await self._aconn().call(req) + except (OSError, EOFError, ConnectionError, asyncio.TimeoutError) as err: + last_err = err + attempt += 1 + if attempt >= 3 and time.monotonic() >= deadline: + break + await _aowner_lost(self._coord) + if attempt >= 3: + await asyncio.sleep(0.2) raise SharedStorageError(f"shared-storage owner unreachable: {last_err}") async def aget(self, key: str, default: Any = None) -> Any: @@ -676,5 +837,8 @@ def _head(self, topic: str) -> int: def subscribe(self, topic: str, replay_from: Optional[int] = None) -> Subscription: self._coord.ensure() + # Taken before the head: if the owner changes in between, the first + # poll gaps instead of reading the new owner with the old one's cursor. + token = self._coord.token start = replay_from if replay_from is not None else self._head(topic) - return _LocalSubscription(self._coord, topic, start, self._call) + return _LocalSubscription(self._coord, topic, start, self._call, token) diff --git a/dash/dash.py b/dash/dash.py index 01c7c45edb..08562991ba 100644 --- a/dash/dash.py +++ b/dash/dash.py @@ -11,6 +11,7 @@ from importlib import metadata import pkgutil import threading +import weakref from contextvars import ContextVar import re import logging @@ -84,6 +85,7 @@ from ._get_app import with_app_context, with_app_context_factory from ._shared_storage import BaseSharedStorage, SharedStorageError from ._shared_storage._env import storage_from_env +from ._shared_storage.cluster import starts_at_boot from ._grouping import map_grouping, grouping_len, update_args_group from ._obsolete import ObsoleteChecker from ._callback_context import callback_context @@ -760,13 +762,17 @@ def __init__( # pylint: disable=too-many-statements, too-many-branches # Shared storage (state manager + pub/sub). Started lazily on first # access so it costs nothing until used and never binds in a gunicorn # preload master or the Flask reloader parent -- only in the worker that - # actually touches it. + # actually touches it. The exception is a cluster in majority mode, + # which must join the election at boot (_start_shared_storage_at_boot). if shared_storage is _SHARED_STORAGE_DEFAULT: shared_storage = storage_from_env( load_dash_env_vars().get("DASH_SHARED_STORAGE") ) self._shared_storage_arg = shared_storage self._shared_storage_instance: Optional[BaseSharedStorage] = None + # Set while start() runs, so a fork meanwhile (a preload master's + # boot thread electing) still reaches it. + self._shared_storage_starting: Optional[BaseSharedStorage] = None self._shared_storage_lock = threading.Lock() self.logger = logging.getLogger(__name__) @@ -774,6 +780,9 @@ def __init__( # pylint: disable=too-many-statements, too-many-branches if not self.logger.handlers and add_log_handler: self.logger.addHandler(logging.StreamHandler(stream=sys.stdout)) + if starts_at_boot(shared_storage): + self._start_shared_storage_at_boot() + if plugins is not None and isinstance( plugins, patch_collections_abc("Iterable") ): @@ -1041,6 +1050,49 @@ def layout(self, value: Any): _validate.validate_layout(value, layout_value) self.validation_layout = layout_value + def _start_shared_storage_at_boot(self) -> None: + # Unlike the lazy default this binds in a gunicorn preload master too: + # the master then holds the replica's lock and votes, and its workers + # reach it on loopback. A forked child (a worker, or a multiprocessing + # child) drops the parent's objects, whose threads did not survive the + # fork, and starts lazily on first use: the parent already votes. + app_ref = weakref.ref(self) + + def after_fork_in_child(): + app = app_ref() + if app is not None: + app._shared_storage_after_fork() # pylint: disable=protected-access + + if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=after_fork_in_child) + self._boot_shared_storage() + + def _shared_storage_after_fork(self) -> None: + self._shared_storage_lock = threading.Lock() + found = ( + self._shared_storage_instance, + self._shared_storage_starting, + self._shared_storage_arg, + ) + self._shared_storage_instance = self._shared_storage_starting = None + for storage in {id(s): s for s in found}.values(): + if hasattr(storage, "after_fork") and not isinstance(storage, type): + storage.after_fork() + + def _boot_shared_storage(self) -> None: + def run(): + try: + self.shared_storage # pylint: disable=pointless-statement + except Exception: # pylint: disable=broad-exception-caught + self.logger.warning( + "shared storage did not start yet, retrying on first use", + exc_info=True, + ) + + threading.Thread( + target=run, name="dash-shared-storage-boot", daemon=True + ).start() + @property def shared_storage_enabled(self) -> bool: """Whether this app has a shared-storage backend (off by default). @@ -1069,7 +1121,11 @@ def shared_storage(self) -> BaseSharedStorage: storage = self._shared_storage_arg if isinstance(storage, (type, functools.partial)): storage = storage() - storage.start() + self._shared_storage_starting = storage + try: + storage.start() + finally: + self._shared_storage_starting = None self._shared_storage_instance = storage return self._shared_storage_instance diff --git a/tests/cluster_harness/.gitignore b/tests/cluster_harness/.gitignore new file mode 100644 index 0000000000..4ef518543e --- /dev/null +++ b/tests/cluster_harness/.gitignore @@ -0,0 +1,3 @@ +.build/ +.tls/ +.state.json diff --git a/tests/cluster_harness/README.md b/tests/cluster_harness/README.md new file mode 100644 index 0000000000..cffd888c53 --- /dev/null +++ b/tests/cluster_harness/README.md @@ -0,0 +1,50 @@ +# Cluster harness + +Runs `ClusterSharedStorage` replicas as real containers (docker or podman) so +you can scale them, kill, freeze or cut off the owner, and watch what the +cluster does. Each replica runs `gunicorn -w 2` on this checkout's source, +mounted read only, so edits take effect on the next `up` or `scale`. + +## Requirements + +- docker, or podman 4+ (netavark and aardvark-dns, the default since 4.0). + Rootless podman works: the harness reaches replicas with `exec`, never by IP. +- Built components in the checkout (`dash/dcc/_imports_.py` must exist). +- `openssl` for `--tls`. +- The first `up` builds `dash-cluster-harness` from `python:3.12-slim`, so the + engine needs to reach a registry and PyPI once. `HARNESS_IMAGE=` + skips the build and uses an image you already have instead (it needs + python3, gunicorn and the packages in `requirements/install.txt` and + `requirements/shared_storage.txt`; without msgspec the store silently + falls back to JSON). With rootless podman and an image that runs as a + non-root user, the mounts may need `--userns=keep-id`. +- `CLUSTER_ENGINE=podman` picks podman when both are installed. + +## By hand + +``` +python tests/cluster_harness/harness.py up 3 # 3 replicas, started together +python tests/cluster_harness/harness.py up 3 --quorum 3 # majority mode +python tests/cluster_harness/harness.py up 3 --tls --publish # replica i on localhost:8050+i +python tests/cluster_harness/harness.py status # role and token per worker +python tests/cluster_harness/harness.py scale 5 +python tests/cluster_harness/harness.py kill 1 # also: pause, unpause, cut, heal, rm, logs +python tests/cluster_harness/harness.py down +``` + +`cut` takes a replica off the network (a partition), `heal` puts it back +under the shared DNS name. `pause` freezes it like a long GC or a stalled VM. + +## Tests + +They start containers, so they only run when asked: + +``` +DASH_CLUSTER_HARNESS=1 pytest tests/cluster_harness -s +DASH_CLUSTER_HARNESS=1 HARNESS_QUORUM=3 pytest tests/cluster_harness -s +DASH_CLUSTER_HARNESS=1 HARNESS_TLS=1 pytest tests/cluster_harness -s +``` + +`HARNESS_KEEP=1` leaves the cluster running afterwards. Majority mode skips +the scale tests (its replica count is fixed) and the base mode skips the +"cut-off owner refuses writes" test (without a majority it doesn't). diff --git a/tests/cluster_harness/__init__.py b/tests/cluster_harness/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/cluster_harness/app.py b/tests/cluster_harness/app.py new file mode 100644 index 0000000000..ad2481ff3f --- /dev/null +++ b/tests/cluster_harness/app.py @@ -0,0 +1,88 @@ +import os + +from flask import jsonify, request + +from dash import Dash, Input, Output, callback, ctx, html + +POD = os.environ.get("POD", "?") + +app = Dash(__name__) +server = app.server + +app.layout = html.Div( + [ + html.Div(f"pod {POD}", id="pod"), + html.Button("add", id="add"), + html.Div(id="count"), + ] +) + + +@callback(Output("count", "children"), Input("add", "n_clicks")) +def add(n_clicks): + store = ctx.shared_storage + value = store.get("count", 0) + if n_clicks: + value += 1 + store.set("count", value) + return f"count={value}" + + +@server.route("/whoami") +def whoami(): + store = app.shared_storage + try: + # A worker without the lock learns of an owner change on its next call. + store.get("whoami") + except Exception: # pylint: disable=broad-except + pass + coord = store._coord # pylint: disable=protected-access + return jsonify( + pod=POD, + pid=os.getpid(), + role=coord._role, # pylint: disable=protected-access + token=coord.token, + holds_lock=coord._cluster is not None, # pylint: disable=protected-access + address=list(coord._address or ()), # pylint: disable=protected-access + conn_token=store._conn_token, # pylint: disable=protected-access + lock=_lock_view(coord._cluster), # pylint: disable=protected-access + ) + + +def _lock_view(lock): + if lock is None: + return None + state = lock._state # pylint: disable=protected-access + return { + "id": lock.id, + "role": state.role, + "term": state.term, + "owner_id": state.owner_id, + "owner_addr": list(state.owner_addr or ()), + } + + +@server.route("/kv/", methods=["GET", "POST"]) +def kv(key): + store = app.shared_storage + if request.method == "POST": + store.set(key, request.get_json()["value"]) + return jsonify(ok=True, pid=os.getpid()) + return jsonify(value=store.get(key), pid=os.getpid()) + + +@server.route("/pub/", methods=["POST"]) +def pub(topic): + app.shared_storage.publish(topic, request.get_json()["message"]) + return jsonify(ok=True) + + +@server.route("/poll/") +def poll(topic): + sub = app.shared_storage.subscribe(topic, replay_from=int(request.args["from"])) + try: + return jsonify(pairs=sub.poll(timeout=2), pid=os.getpid()) + except Exception as err: # pylint: disable=broad-except + return jsonify(error=type(err).__name__, pid=os.getpid()) + finally: + sub.close() diff --git a/tests/cluster_harness/harness.py b/tests/cluster_harness/harness.py new file mode 100644 index 0000000000..9d10724ee6 --- /dev/null +++ b/tests/cluster_harness/harness.py @@ -0,0 +1,411 @@ +"""Run ClusterSharedStorage replicas as real containers, with docker or podman. + +Every replica is a container on one user network, reachable by the others +under the alias ``dash`` (one DNS name, one A record per replica), running +``gunicorn -w 2`` on the repo source mounted read only. The harness talks to +replicas with ``exec`` on loopback, so it works with rootless podman where +container IPs are not reachable from the host. + + python harness.py up 3 [--quorum] [--tls] [--publish] + python harness.py scale 5 + python harness.py status + python harness.py kill|pause|unpause|cut|heal|logs|rm + python harness.py down + +Environment: CLUSTER_ENGINE=docker|podman (default: whichever is installed), +HARNESS_IMAGE to use an existing image instead of building one. +""" +import argparse +import json +import os +import shutil +import subprocess +import sys +import time +from pathlib import Path + +HERE = Path(__file__).resolve().parent +REPO = HERE.parents[1] +NET = "dash-cluster-harness" +ALIAS = "dash" +LABEL = "dash-cluster-harness" +IMAGE = "dash-cluster-harness:latest" +LOCK_PORT = 7100 +SECRET = "harness-secret" +STATE = HERE / ".state.json" + +DOCKERFILE = """\ +FROM docker.io/library/python:3.12-slim +COPY install.txt shared_storage.txt /tmp/ +RUN pip install --no-cache-dir -r /tmp/install.txt -r /tmp/shared_storage.txt gunicorn +""" + + +class EngineError(RuntimeError): + pass + + +def engine_name(): + name = os.environ.get("CLUSTER_ENGINE") + if name: + return name + for name in ("docker", "podman"): + if shutil.which(name): + return name + raise EngineError("neither docker nor podman is on PATH") + + +class Cluster: + def __init__(self, quorum=None, tls=False, workers=2, publish=False): + self.engine = engine_name() + self.quorum = quorum + self.tls = tls + self.workers = workers + self.publish = publish + self.image = os.environ.get("HARNESS_IMAGE", IMAGE) + + @classmethod + def load(cls): + """The cluster the last ``up`` started, so scaling keeps its options.""" + try: + return cls(**json.loads(STATE.read_text())) + except FileNotFoundError: + return cls() + + def save(self): + STATE.write_text( + json.dumps( + { + "quorum": self.quorum, + "tls": self.tls, + "workers": self.workers, + "publish": self.publish, + } + ) + ) + + # engine plumbing + + def run(self, *args, check=True, timeout=120): + res = subprocess.run( + [self.engine, *args], + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + if check and res.returncode != 0: + raise EngineError( + f"{self.engine} {' '.join(args)} failed:\n{res.stderr.strip()}" + ) + return res.stdout.strip() + + def preflight(self): + built = ("dash/dcc/_imports_.py", "dash/dash-renderer/build") + if not all((REPO / path).exists() for path in built): + raise EngineError( + f"{REPO} has no built components ({', '.join(built)}). " + "Run `npm run build` or copy the built files in first." + ) + self.run("info", timeout=30) + + def build(self): + if "HARNESS_IMAGE" in os.environ: + return + if self.run("images", "-q", self.image, check=False): + return + ctx = HERE / ".build" + ctx.mkdir(exist_ok=True) + (ctx / "Dockerfile").write_text(DOCKERFILE) + for req in ("install.txt", "shared_storage.txt"): + shutil.copy(REPO / "requirements" / req, ctx / req) + print(f"building {self.image} with {self.engine}...", file=sys.stderr) + self.run("build", "-t", self.image, str(ctx), timeout=900) + + def make_tls(self): + out = HERE / ".tls" + if (out / "cert.pem").exists(): + return + out.mkdir(exist_ok=True) + subprocess.run( + [ + "openssl", + "req", + "-x509", + "-newkey", + "ec", + "-pkeyopt", + "ec_paramgen_curve:prime256v1", + "-nodes", + "-days", + "365", + "-subj", + "/CN=dash-cluster", + "-keyout", + str(out / "key.pem"), + "-out", + str(out / "cert.pem"), + ], + check=True, + capture_output=True, + ) + # Containers may run as another uid (rootless podman, other images). + os.chmod(out / "key.pem", 0o644) + + def url(self): + opts = [] + if self.tls: + opts += ["tls_cert=/harness/.tls/cert.pem", "tls_key=/harness/.tls/key.pem"] + if self.quorum: + opts.append(f"replicas={self.quorum}") + query = "?" + "&".join(opts) if opts else "" + return f"cluster://:{SECRET}@{ALIAS}:{LOCK_PORT}{query}" + + # replicas + + def names(self, stopped=False): + """Running (or paused) replicas, and with ``stopped`` killed ones too.""" + out = self.run( + "ps", + *(["-a"] if stopped else []), + "--filter", + f"label={LABEL}", + "--format", + "{{.Names}}", + ) + return sorted(out.split(), key=lambda n: int(n.rsplit("-", 1)[1])) + + @staticmethod + def name(index): + return f"dch-{index}" + + def indexes(self): + return [int(n.rsplit("-", 1)[1]) for n in self.names()] + + def start(self, index): + self.remove(index) # a killed replica keeps its name until removed + args = [ + "run", + "-d", + "--name", + self.name(index), + "--label", + LABEL, + # SELinux hosts would refuse the bind mounts. + "--security-opt", + "label=disable", + "--network", + NET, + "--network-alias", + ALIAS, + "-e", + f"POD={index}", + "-e", + f"DASH_SHARED_STORAGE={self.url()}", + "-e", + "DASH_SECRET_KEY=harness", + "-e", + "PYTHONPATH=/src", + "-e", + "PYTHONUNBUFFERED=1", + "-v", + f"{REPO}:/src:ro", + "-v", + f"{HERE}:/harness:ro", + "-w", + "/harness", + ] + if self.publish: + args += ["-p", f"{8050 + index}:8050"] + args += [ + "--entrypoint", + "python3", + self.image, + "-m", + "gunicorn", + "-w", + str(self.workers), + "-b", + "0.0.0.0:8050", + "--timeout", + "120", + "app:server", + ] + self.run(*args) + + def up(self, count): + """Start ``count`` replicas at once, as when waking from zero.""" + self.preflight() + self.build() + if self.tls: + self.make_tls() + self.run("network", "create", NET, check=False) + self.down(network=False) + self.save() + for index in range(1, count + 1): + self.start(index) + self.wait_up(range(1, count + 1)) + + def scale(self, count): + alive = self.indexes() + if count > len(alive): + start = max(alive, default=0) + 1 + new = range(start, start + count - len(alive)) + for index in new: + self.start(index) + self.wait_up(new) + else: + # Like a scale down: drop the newest replicas first. + for index in sorted(alive, reverse=True)[: len(alive) - count]: + self.remove(index) + + def remove(self, index): + self.run("rm", "-f", self.name(index), check=False) + + def kill(self, index): + self.run("kill", self.name(index)) + + def pause(self, index): + self.run("pause", self.name(index)) + + def unpause(self, index): + self.run("unpause", self.name(index)) + + def cut(self, index): + """Take a replica off the network. ``exec`` still reaches it.""" + self.run("network", "disconnect", NET, self.name(index)) + + def heal(self, index): + self.run("network", "connect", "--alias", ALIAS, NET, self.name(index)) + + def logs(self, index): + return self.run("logs", "--tail", "200", self.name(index), check=False) + + def down(self, network=True): + for name in self.names(stopped=True): + self.run("rm", "-f", name, check=False) + if network: + self.run("network", "rm", NET, check=False) + STATE.unlink(missing_ok=True) + + # talking to the app inside a replica + + def probe(self, index, *args, timeout=60): + out = self.run( + "exec", + self.name(index), + "python3", + "/harness/probe.py", + *args, + timeout=timeout, + ) + return json.loads(out) + + def get(self, index, path): + return self.probe(index, "get", path) + + def post(self, index, path, body, timeout=20): + return self.probe( + index, "post", path, json.dumps(body), str(timeout), timeout=timeout + 30 + ) + + def every_worker(self, index, path, seconds=40): + """One answer per gunicorn worker of a replica, keyed by pid.""" + out = self.probe( + index, + "workers", + path, + str(self.workers), + str(seconds), + timeout=seconds + 30, + ) + if "error" in out or len(out) < self.workers: + raise EngineError(f"replica {index} {path}: {out}") + return out + + def wait_up(self, indexes, timeout=90): + deadline = time.monotonic() + timeout + for index in indexes: + while True: + try: + self.every_worker(index, "/whoami") + break + except (EngineError, subprocess.TimeoutExpired, ValueError): + if time.monotonic() > deadline: + print(self.logs(index), file=sys.stderr) + raise + time.sleep(0.5) + + def roles(self, indexes=None): + """{(replica, pid): whoami} for every worker of the given replicas.""" + out = {} + for index in indexes or self.indexes(): + for pid, res in self.every_worker(index, "/whoami").items(): + out[(index, int(pid))] = res + return out + + def settled(self, indexes=None, timeout=60): + """Wait until the replicas agree on one owner, and return it.""" + deadline = time.monotonic() + timeout + while True: + try: + roles = self.roles(indexes) + tokens = {r["token"] for r in roles.values()} + owners = [k for k, r in roles.items() if r["role"] == "owner"] + if len(tokens) == 1 and None not in tokens and len(owners) == 1: + return owners[0][0], tokens.pop(), roles + except (EngineError, subprocess.TimeoutExpired, ValueError) as err: + roles = f"unreachable: {err}" + if time.monotonic() > deadline: + raise AssertionError(f"no single owner after {timeout}s: {roles}") + time.sleep(0.5) + + +def main(): + parser = argparse.ArgumentParser( + description="ClusterSharedStorage container harness" + ) + parser.add_argument("command") + parser.add_argument("arg", nargs="?", type=int) + parser.add_argument("--quorum", type=int, help="replicas=N (majority mode)") + parser.add_argument("--tls", action="store_true") + parser.add_argument("--publish", action="store_true", help="replica i on 8050+i") + opts = parser.parse_args() + cmd = opts.command + if cmd == "up": + cluster = Cluster(quorum=opts.quorum, tls=opts.tls, publish=opts.publish) + else: + cluster = Cluster.load() + needs_arg = ("scale", "logs", "kill", "pause", "unpause", "cut", "heal", "rm") + if cmd in needs_arg and opts.arg is None: + parser.error(f"{cmd} takes a number") + if cmd == "up": + cluster.up(opts.arg or 3) + cmd = "status" + elif cmd == "scale": + cluster.scale(opts.arg) + cmd = "status" + elif cmd == "down": + cluster.down() + elif cmd == "logs": + print(cluster.logs(opts.arg)) + elif cmd in ("kill", "pause", "unpause", "cut", "heal"): + getattr(cluster, cmd)(opts.arg) + elif cmd == "rm": + cluster.remove(opts.arg) + elif cmd != "status": + parser.error(f"unknown command {cmd}") + if cmd == "status": + print(f"{cluster.engine}, {cluster.url()}") + for index in cluster.indexes(): + try: + for pid, res in cluster.every_worker(index, "/whoami", 5).items(): + print( + f"replica {index} pid {pid}: {res['role']} token {res['token']}" + ) + except (EngineError, subprocess.TimeoutExpired, ValueError) as err: + print(f"replica {index}: {str(err).splitlines()[0]}") + + +if __name__ == "__main__": + main() diff --git a/tests/cluster_harness/probe.py b/tests/cluster_harness/probe.py new file mode 100644 index 0000000000..71bfca029b --- /dev/null +++ b/tests/cluster_harness/probe.py @@ -0,0 +1,57 @@ +"""Runs inside a replica: talks to the app on loopback and prints JSON. + + probe.py get /path one request + probe.py post /path '{json}' [timeout] one request + probe.py workers /path N secs repeat until N gunicorn workers answered +""" +import json +import sys +import time +import urllib.error +import urllib.request + +BASE = "http://127.0.0.1:8050" + + +def call(method, path, body=None, timeout=20): + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request( + BASE + path, + data=data, + method=method, + headers={"Content-Type": "application/json", "Connection": "close"}, + ) + try: + with urllib.request.urlopen(req, timeout=timeout) as res: + return {"status": res.status, "body": json.loads(res.read())} + except urllib.error.HTTPError as err: + return {"status": err.code, "body": None} + except Exception as err: # pylint: disable=broad-except + return {"status": 0, "error": f"{type(err).__name__}: {err}"} + + +def main(): + cmd, path = sys.argv[1], sys.argv[2] + if cmd == "get": + out = call("GET", path) + elif cmd == "post": + timeout = float(sys.argv[4]) if len(sys.argv) > 4 else 20 + out = call("POST", path, json.loads(sys.argv[3]), timeout) + else: + # A worker can be busy for a while (a call to an owner that vanished), + # so keep asking for a time, not a number of requests. + workers, deadline = int(sys.argv[3]), time.monotonic() + float(sys.argv[4]) + out = {} + while time.monotonic() < deadline: + res = call("GET", path) + if res["status"] != 200: + out = {"error": res} + break + out[str(res["body"]["pid"])] = res["body"] + if len(out) >= workers: + break + time.sleep(0.05) + print(json.dumps(out)) + + +main() diff --git a/tests/cluster_harness/test_cluster_harness.py b/tests/cluster_harness/test_cluster_harness.py new file mode 100644 index 0000000000..a5941eb5ee --- /dev/null +++ b/tests/cluster_harness/test_cluster_harness.py @@ -0,0 +1,216 @@ +"""ClusterSharedStorage across real containers: scaling, failover, partitions. + +Opt in, it starts containers: + + DASH_CLUSTER_HARNESS=1 pytest tests/cluster_harness -s + DASH_CLUSTER_HARNESS=1 HARNESS_QUORUM=3 pytest tests/cluster_harness -s + DASH_CLUSTER_HARNESS=1 HARNESS_TLS=1 pytest tests/cluster_harness -s + +Tests run in file order and share one cluster, each leaves it settled. +""" +import os +import time + +import pytest + +from .harness import Cluster + +pytestmark = pytest.mark.skipif( + os.environ.get("DASH_CLUSTER_HARNESS") != "1", + reason="starts containers, set DASH_CLUSTER_HARNESS=1", +) + +QUORUM = int(os.environ.get("HARNESS_QUORUM", "0")) or None +TLS = os.environ.get("HARNESS_TLS") == "1" +SIZE = QUORUM or 3 +majority_only = pytest.mark.skipif(not QUORUM, reason="majority mode only") +no_majority = pytest.mark.skipif( + bool(QUORUM), reason="majority mode needs a fixed replica count" +) + + +@pytest.fixture(scope="module") +def cluster(): + c = Cluster(quorum=QUORUM, tls=TLS) + try: + c.up(SIZE) + yield c + finally: + if os.environ.get("HARNESS_KEEP") != "1": + c.down() + + +def wait_for(what, check, timeout=60): + t0 = time.monotonic() + last = None + while time.monotonic() - t0 < timeout: + try: + last = check() + if last is True: + return time.monotonic() - t0 + except Exception as err: # pylint: disable=broad-except + last = err + time.sleep(0.3) + raise AssertionError(f"{what} after {timeout}s, last: {last!r}") + + +def write(cluster, index, key, value): + # Wait out the backend's own retries: a write the test gave up on would + # still land later and overwrite the next one. + res = cluster.post(index, f"/kv/{key}", {"value": value}, timeout=150) + return res["status"] == 200 + + +def reads(cluster, indexes, key, value): + return all( + res["value"] == value + for index in indexes + for res in cluster.every_worker(index, f"/kv/{key}").values() + ) + + +def test_cold_start_agrees_on_one_owner(cluster): + owner, _token, roles = cluster.settled() + print(f"owner: replica {owner}") + # Each replica holds its own lock once, shared by its workers. + assert sum(r["holds_lock"] for r in roles.values()) == SIZE + + +def test_writes_reach_every_replica_and_worker(cluster): + assert write(cluster, 2, "a", {"from": 2}) + assert reads(cluster, cluster.indexes(), "a", {"from": 2}) + + +def test_pubsub_across_replicas(cluster): + assert cluster.post(1, "/pub/t", {"message": "x"})["status"] == 200 + assert cluster.post(3, "/pub/t", {"message": "y"})["status"] == 200 + res = cluster.get(2, "/poll/t?from=0")["body"] + assert res["pairs"] == [[1, "x"], [2, "y"]], res + + +@no_majority +def test_scale_up_keeps_the_owner_and_the_data(cluster): + owner, token, _ = cluster.settled() + cluster.scale(SIZE + 2) + new_owner, new_token, _ = cluster.settled() + assert (new_owner, new_token) == (owner, token) + assert reads(cluster, cluster.indexes(), "a", {"from": 2}) + + +@no_majority +def test_scale_down_keeps_serving(cluster): + cluster.scale(SIZE) + cluster.settled() + assert write(cluster, cluster.indexes()[0], "b", 1) + assert reads(cluster, cluster.indexes(), "b", 1) + + +def test_killing_the_owner_fails_over(cluster): + owner, token, _ = cluster.settled() + cluster.kill(owner) + cluster.remove(owner) + rest = cluster.indexes() + took = wait_for( + "no failover", + lambda: write(cluster, rest[0], "c", 2) and reads(cluster, rest, "c", 2), + ) + print(f"failover {took:.1f}s after killing replica {owner}") + _owner, new_token, _ = cluster.settled() + assert new_token != token + cluster.scale(SIZE) + cluster.settled() + + +def test_frozen_owner_is_replaced(cluster): + owner, token, _ = cluster.settled() + rest = [i for i in cluster.indexes() if i != owner] + cluster.pause(owner) + try: + took = wait_for( + "no takeover from a frozen owner", + lambda: write(cluster, rest[0], "d", "majority") + and reads(cluster, rest, "d", "majority"), + ) + print(f"took over {took:.1f}s after freezing replica {owner}") + finally: + cluster.unpause(owner) + _owner, new_token, _ = cluster.settled(timeout=90) + if QUORUM: + # The old owner's lease ran out while frozen: nothing it held wins. + assert new_token != token + assert reads(cluster, cluster.indexes(), "d", "majority") + # Without a majority the older owner wins the merge when it wakes up, + # and what the others wrote meanwhile is gone (a SharedStorageGap). + + +@majority_only +def test_cut_off_owner_refuses_writes_and_rejoins(cluster): + owner, _token, _ = cluster.settled() + rest = [i for i in cluster.indexes() if i != owner] + cluster.cut(owner) + took = wait_for( + "the majority never took over", + lambda: write(cluster, rest[0], "e", "majority") + and reads(cluster, rest, "e", "majority"), + ) + print(f"majority took over {took:.1f}s after the cut") + for _ in range(cluster.workers): + t0 = time.monotonic() + res = cluster.post(owner, "/kv/e", {"value": "lost"}, timeout=180) + assert res["status"] == 500, res + print(f"cut-off replica refused a write after {time.monotonic() - t0:.1f}s") + cluster.heal(owner) + took = wait_for( + "the cut-off replica never rejoined", + lambda: reads(cluster, cluster.indexes(), "e", "majority"), + timeout=120, + ) + print(f"rejoined {took:.1f}s after healing") + cluster.settled() + + +@no_majority +def test_cut_off_owner_converges_after_healing(cluster): + # Without a majority both sides own for a while; after healing they + # merge back to one owner, and its store must not change on its own. + owner, token, _ = cluster.settled() + rest = [i for i in cluster.indexes() if i != owner] + assert reads(cluster, [rest[0]], "f", None) # connects both workers + cluster.cut(owner) + # The first try goes to the cut-off owner and times out, the retry + # lands on the new one. + assert write(cluster, rest[0], "f", 1) + cluster.heal(owner) + _owner, merged, _ = cluster.settled(timeout=90) + # The older store wins: the cut-off owner's, where "f" was never set. + expected = None if merged == token else 1 + t0 = time.monotonic() + while time.monotonic() - t0 < 45: + # A write the client gave up on, still queued in the kernel, would + # reach the old owner once the network heals and land here late. + assert reads(cluster, cluster.indexes(), "f", expected) + time.sleep(1) + assert write(cluster, owner, "f", 2) + assert reads(cluster, cluster.indexes(), "f", 2) + + +def test_rolling_restart(cluster): + for index in list(cluster.indexes()): + cluster.remove(index) + cluster.scale(SIZE) + cluster.settled(timeout=90) + indexes = cluster.indexes() + assert write(cluster, indexes[0], "g", "after") + assert reads(cluster, indexes, "g", "after") + + +def test_scale_to_zero_and_back(cluster): + cluster.scale(0) + assert not cluster.indexes() + cluster.scale(SIZE) + cluster.settled() + indexes = cluster.indexes() + # Nothing outlives the last replica without path= on a shared volume. + assert reads(cluster, indexes, "g", None) + assert write(cluster, indexes[-1], "h", 1) + assert reads(cluster, indexes, "h", 1) diff --git a/tests/shared_storage/conftest.py b/tests/shared_storage/conftest.py new file mode 100644 index 0000000000..c8b8f0a185 --- /dev/null +++ b/tests/shared_storage/conftest.py @@ -0,0 +1,41 @@ +import shutil +import subprocess + +import pytest + + +@pytest.fixture(scope="session") +def make_cert(tmp_path_factory): + """Make a self-signed certificate: returns (cert path, key path).""" + openssl = shutil.which("openssl") + if openssl is None: + pytest.skip("openssl is needed to make test certificates") + folder = tmp_path_factory.mktemp("tls") + + def run(*args): + subprocess.run([str(openssl), *map(str, args)], check=True, capture_output=True) + + def make(name="replica", signed_by=None, extra=()): + """``signed_by``: the (cert, key) of a CA to sign with, instead of + signing it with its own key. ``extra``: more ``openssl req`` options + for a self-signed one.""" + cert, key = folder / f"{name}.pem", folder / f"{name}.key" + if cert.exists(): + return str(cert), str(key) + newkey = ["-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1"] + if "-passout" not in extra: + newkey.append("-nodes") + subject = ["-subj", f"/CN={name}", "-keyout", key] + if signed_by is None: + run("req", "-x509", *newkey, "-days", "2", *subject, *extra, "-out", cert) + else: + csr = folder / f"{name}.csr" + run("req", "-new", *newkey, *subject, "-out", csr) + ca_cert, ca_key = signed_by + run( + "x509", "-req", "-in", csr, "-CA", ca_cert, "-CAkey", ca_key, + "-CAcreateserial", "-days", "2", "-out", cert, + ) # fmt: skip + return str(cert), str(key) + + return make diff --git a/tests/shared_storage/test_cluster_backend.py b/tests/shared_storage/test_cluster_backend.py new file mode 100644 index 0000000000..c303924c53 --- /dev/null +++ b/tests/shared_storage/test_cluster_backend.py @@ -0,0 +1,1026 @@ +"""ClusterSharedStorage across "pods" on loopback. + +Each pod is a ClusterSharedStorage on its own port pair (lock port, data port); +a second instance on the same port plays another worker of that pod, which +finds the owner through the pod's lock process. ``peers`` stands in for DNS. +""" +# pylint: disable=protected-access +import asyncio +import os +import socket +import struct +import threading +import time + +import pytest + +from dash._shared_storage import ( + ClusterSharedStorage, + SharedStorageError, + SharedStorageGap, +) + +FAST = {"probe_interval": 0.05, "settle_timeout": 10.0} + + +def until(predicate, timeout=10.0, message="condition not met"): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if predicate(): + return + time.sleep(0.02) + raise AssertionError(message) + + +def _port_pair(): + """A port whose next one up is free too.""" + for _ in range(50): + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + port = probe.getsockname()[1] + if port >= 65534: + continue + try: + with socket.create_server(("", port)), socket.create_server(("", port + 1)): + return port + except OSError: + continue + raise RuntimeError("no free port pair") + + +class Pods: + def __init__(self): + self.ports = [] + self.views = {} + self.stores = [] + self._mutex = threading.Lock() + + def add_pod(self): + self.ports.append(_port_pair()) + return len(self.ports) - 1 + + def worker(self, pod, secret="s3cret", **kw): + def peers(): + with self._mutex: + allowed = self.views.get(pod) + ports = list(enumerate(self.ports)) + return [ + ("127.0.0.1", p) for i, p in ports if allowed is None or i in allowed + ] + + store = ClusterSharedStorage( + port=self.ports[pod], secret=secret, peers=peers, **{**FAST, **kw} + ) + self.stores.append(store) + return store + + def isolate(self, *groups): + with self._mutex: + for group in groups: + for pod in group: + self.views[pod] = set(group) + + def join(self): + with self._mutex: + self.views.clear() + + def close(self): + for store in self.stores: + store.close() + + +@pytest.fixture +def pods(): + p = Pods() + yield p + p.close() + + +def _owner_of(store): + store.start() + return store._coord._cluster + + +def test_pods_share_kv_and_pubsub(pods): + a, b = pods.add_pod(), pods.add_pod() + a1 = pods.worker(a) + a1.start() + b1 = pods.worker(b) + a2 = pods.worker(a) # another worker of pod a: no lock of its own + for store in (a1, b1, a2): + store.start() + assert a2._coord._cluster is None + assert a1._coord.is_owner() + assert not b1._coord.is_owner() and not a2._coord.is_owner() + + b1.set("k", {"from": "b"}) + assert a1.get("k") == {"from": "b"} + assert a2.get("k") == {"from": "b"} + + sub = a2.subscribe("t") + b1.publish("t", 1) + a1.publish("t", 2) + assert sub.poll(timeout=5) == [(1, 1), (2, 2)] + + +def test_owner_loss_gaps_readers_and_a_survivor_takes_over(pods): + a, b = pods.add_pod(), pods.add_pod() + owner = pods.worker(a) + owner.start() + other = pods.worker(b) + other.start() + other.set("k", 1) + sub = other.subscribe("t") + owner.publish("t", "before") + assert sub.poll(timeout=5) == [(1, "before")] + + owner.close() + with pytest.raises(SharedStorageGap): + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + sub.poll(timeout=0.2) + assert other._coord.is_owner() + assert other.get("k") is None # memory mode: the new owner starts empty + other.set("k", 2) + assert other.get("k") == 2 + + +def test_blocked_reader_on_a_dead_owner_gaps(pods): + a, b = pods.add_pod(), pods.add_pod() + owner = pods.worker(a) + owner.start() + reader = pods.worker(b) + reader.start() + sub = reader.subscribe("t") + errors = [] + + def read(): + try: + for _msg in sub: + pass + except SharedStorageGap as err: + errors.append(err) + + thread = threading.Thread(target=read, daemon=True) + thread.start() + time.sleep(0.3) + owner.close() + thread.join(15) + assert not thread.is_alive() and errors + + +def test_split_owners_merge_and_the_loser_stops_taking_writes(pods): + a, b = pods.add_pod(), pods.add_pod() + pods.isolate([a], [b]) + first = pods.worker(a) + first.start() + time.sleep(0.2) + second = pods.worker(b) + second.start() + assert first._coord.is_owner() and second._coord.is_owner() + first.set("k", "first") + second.set("k", "second") + sub = second.subscribe("t") + + pods.join() + until(lambda: not second._coord._cluster.is_owner(second._coord._term)) + # The writes go to the owner that held on, never the deposed one's engine. + second.set("after", 1) + assert first.get("after") == 1 + assert second.get("k") == "first" + with pytest.raises(SharedStorageGap): + sub.poll() + + +def test_worker_follows_the_owner_change_through_its_pods_lock(pods): + a, b = pods.add_pod(), pods.add_pod() + owner = pods.worker(a) + owner.start() + holder = pods.worker(b) + holder.start() + worker = pods.worker(b) + worker.start() + worker.set("k", 1) + assert owner.get("k") == 1 + + owner.close() + until(lambda: holder._coord._cluster.state.role == "owner") + deadline = time.monotonic() + 10 + while True: + try: + worker.set("k", 2) + break + except SharedStorageError: + if time.monotonic() > deadline: + raise + time.sleep(0.1) + assert holder.get("k") == 2 + + +def test_wrong_secret_never_joins(pods): + a, b = pods.add_pod(), pods.add_pod() + good = pods.worker(a) + good.start() + rogue = pods.worker(b, secret="other") + rogue.start() + good.set("k", "good") + rogue.set("k", "rogue") + assert good.get("k") == "good" + assert good._coord.is_owner() and rogue._coord.is_owner() + + +def test_data_port_rejects_a_wrong_token(pods): + from dash._shared_storage._transport import connect_to_owner + + a = pods.add_pod() + store = pods.worker(a) + store.start() + with pytest.raises((ConnectionError, OSError)): + connect_to_owner(socket.AF_INET, ("127.0.0.1", pods.ports[a] + 1), "guess") + + +def test_async_paths(pods): + a, b = pods.add_pod(), pods.add_pod() + owner = pods.worker(a) + owner.start() + client = pods.worker(b) + client.start() + + async def run(): + await client.aset("k", [1, 2]) + assert await client.aget("k") == [1, 2] + sub = client.subscribe("t") + await client.apublish("t", "x") + owner.publish("t", "y") + got = [] + async for pair in sub.aiter_with_seq(): + got.append(pair) + if len(got) == 2: + break + return got + + assert asyncio.run(run()) == [(1, "x"), (2, "y")] + + +def test_no_owner_in_time_raises(pods): + a = pods.add_pod() + # Another process holds the lock port but never answers as a lock. + squatter = socket.create_server(("", pods.ports[a])) + try: + store = pods.worker(a, settle_timeout=0.5) + with pytest.raises(SharedStorageError, match="no shared-storage cluster owner"): + store.start() + finally: + squatter.close() + + +def test_needs_a_secret(monkeypatch): + monkeypatch.delenv("DASH_SECRET_KEY", raising=False) + with pytest.raises(SharedStorageError, match="secret"): + ClusterSharedStorage(host="peers") + monkeypatch.setenv("DASH_SECRET_KEY", "x") + ClusterSharedStorage(host="peers").close() + + +def test_readers_never_get_a_new_owners_data_with_an_old_cursor(pods): + a, b, c = pods.add_pod(), pods.add_pod(), pods.add_pod() + owner = pods.worker(a) + owner.start() + readers = [pods.worker(b), pods.worker(c)] + for store in readers: + store.start() + owner.publish("t", "before") + events = {0: [], 1: []} + + def read(idx, store): + sub = store.subscribe("t", replay_from=0) + try: + for seq, msg in sub.iter_with_seq(): + events[idx].append(("data", seq, msg)) + except SharedStorageGap: + events[idx].append(("gap",)) + except SharedStorageError as err: + events[idx].append(("error", str(err))) + + threads = [ + threading.Thread(target=read, args=(i, s), daemon=True) + for i, s in enumerate(readers) + ] + for thread in threads: + thread.start() + until(lambda: all(events[i] for i in events), message="readers saw nothing") + owner.close() + + # Publish on the survivors until the new owner takes it: its topic starts + # over, so an old cursor reading it would see these as fresh data. + deadline = time.monotonic() + 15 + published = 0 + while published < 3 and time.monotonic() < deadline: + try: + readers[0].publish("t", f"after-{published}") + published += 1 + except SharedStorageError: + time.sleep(0.1) + assert published == 3 + for thread in threads: + thread.join(15) + for idx in events: + assert events[idx][0] == ("data", 1, "before") + assert events[idx][1:] == [("gap",)], events[idx] + + +def test_async_connect_times_out_on_a_silent_owner(): + from dash._shared_storage._transport import aconnect_to_owner + + silent = socket.create_server(("127.0.0.1", 0)) + try: + + async def run(): + started = time.monotonic() + with pytest.raises(asyncio.TimeoutError): + await aconnect_to_owner( + socket.AF_INET, silent.getsockname(), "token", timeout=0.5 + ) + return time.monotonic() - started + + assert asyncio.run(run()) < 2 + finally: + silent.close() + + +class _SilentOwner: + """Takes the handshake and the first request, never answers, and records + how the client let go. Loopback cannot drop packets, so a reset (instead + of a clean close) stands in for "the queued request was thrown away".""" + + def __init__(self): + self._server = socket.create_server(("127.0.0.1", 0)) + self._server.settimeout(5) + self.addr = self._server.getsockname() + self.closed_by = None + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + def _serve(self): + from dash._shared_storage._transport import OK, recv_frame, send_frame + + conn, _ = self._server.accept() + conn.settimeout(5) + with conn: + recv_frame(conn) + send_frame(conn, OK) + recv_frame(conn) + try: + self.closed_by = "close" if conn.recv(1) == b"" else "data" + except ConnectionResetError: + self.closed_by = "reset" + + def wait(self): + self._thread.join(10) + return self.closed_by + + def close(self): + self._server.close() + self._thread.join(10) + + +class _SilentCoord: + token = "t" + recv_timeout = 0.3 + + def __init__(self, addr): + self.addr = addr + + def needs_election(self): + return False + + def close(self): + pass + + def connect(self): + from dash._shared_storage._transport import connect_to_owner + + sock = connect_to_owner(socket.AF_INET, self.addr, self.token) + sock.settimeout(self.recv_timeout) + return sock, self.token + + async def aconnect(self): + from dash._shared_storage._transport import aconnect_to_owner + + streams = await aconnect_to_owner(socket.AF_INET, self.addr, self.token) + return streams, self.token + + +def test_a_timed_out_request_is_dropped_not_left_queued(): + # Across a partition a plain close keeps retransmitting the request, and + # the old owner applies it once the network heals, after the caller + # retried it on the new owner. + owner = _SilentOwner() + try: + store = ClusterSharedStorage(host="peers", secret="s", port=_port_pair()) + store._coord.close() # pylint: disable=protected-access + store._coord = _SilentCoord(owner.addr) # pylint: disable=protected-access + with pytest.raises(OSError): + store._remote(["set", "k", 1]) # pylint: disable=protected-access + store.close() + assert owner.wait() == "reset" + finally: + owner.close() + + +def test_a_timed_out_async_request_is_dropped_not_left_queued(): + from dash._shared_storage.local import _AsyncConn + + owner = _SilentOwner() + try: + conn = _AsyncConn(_SilentCoord(owner.addr)) + with pytest.raises(asyncio.TimeoutError): + asyncio.run(conn.call(["set", "k", 1])) + assert owner.wait() == "reset" + finally: + owner.close() + + +def test_a_cancelled_async_request_is_dropped_too(): + from dash._shared_storage.local import _AsyncConn + + owner = _SilentOwner() + try: + coord = _SilentCoord(owner.addr) + coord.recv_timeout = 30 + conn = _AsyncConn(coord) + + async def run(): + task = asyncio.ensure_future(conn.call(["set", "k", 1])) + await asyncio.sleep(0.3) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + asyncio.run(run()) + assert owner.wait() == "reset" + assert conn._streams is None # pylint: disable=protected-access + finally: + owner.close() + + +def test_long_client_poll_returns_within_a_cycle(pods): + a, b = pods.add_pod(), pods.add_pod() + pods.worker(a).start() + client = pods.worker(b) + client.start() + client._coord.client_poll_timeout = 0.5 + sub = client.subscribe("t") + started = time.monotonic() + assert sub.poll(timeout=60) == [] + assert time.monotonic() - started < 3 + + +def test_deposed_persistent_owner_does_not_overwrite_the_store(pods, tmp_path): + from dash._shared_storage import LocalSharedStorage + + path = str(tmp_path / "shared") + a, b = pods.add_pod(), pods.add_pod() + pods.isolate([a], [b]) + first = pods.worker(a, mode="persist-reset", path=path, flush_interval=3600) + first.start() + time.sleep(0.2) + second = pods.worker(b, mode="persist-reset", path=path, flush_interval=3600) + second.start() + assert first._coord.is_owner() and second._coord.is_owner() + second.set("k", "second") + first.set("k", "first") + first._coord.engine._persistence._flush(["k"]) + + pods.join() + until(lambda: not second._coord._cluster.is_owner(second._coord._term)) + until(lambda: second._coord.engine is None or second._coord._role != "owner") + reader = LocalSharedStorage(namespace="deposed-check", mode="persist", path=path) + try: + assert reader.get("k") == "first" + finally: + reader.close() + + +def test_bind_errors_other_than_in_use_are_reported(pods, monkeypatch): + import errno + + from dash._shared_storage import cluster + + def refuse(*_args, **_kwargs): + raise OSError(errno.EACCES, "permission denied") + + monkeypatch.setattr(cluster, "ClusterLock", refuse) + store = pods.worker(pods.add_pod()) + with pytest.raises(SharedStorageError, match="cannot listen on the cluster port"): + store.start() + + +def test_tls_pods_share_kv_and_pubsub_encrypted(pods, make_cert): + import ssl + + cert, key = make_cert() + a, b = pods.add_pod(), pods.add_pod() + tls = {"tls_cert": cert, "tls_key": key} + owner = pods.worker(a, **tls) + owner.start() + other = pods.worker(b, **tls) + worker = pods.worker(a, **tls) # finds the owner through its pod's lock + other.start() + worker.start() + + other.set("k", "v") + assert owner.get("k") == "v" and worker.get("k") == "v" + assert isinstance(other._conn, ssl.SSLSocket) + sub = worker.subscribe("t") + other.publish("t", 1) + assert sub.poll(timeout=5) == [(1, 1)] + + async def run(): + await other.aset("a", 2) + return await worker.aget("a") + + assert asyncio.run(run()) == 2 + + +def test_tls_data_port_refuses_plaintext(pods, make_cert): + from dash._shared_storage._transport import connect_to_owner + + cert, key = make_cert() + a = pods.add_pod() + store = pods.worker(a, tls_cert=cert, tls_key=key) + store.start() + token = store._coord.token + data = ("127.0.0.1", pods.ports[a] + 1) + socket.create_connection(data, timeout=2).close() # it is listening + # The server drops a client that does not open with a TLS handshake: a + # reset or a closed connection, never an answer. + with pytest.raises(ConnectionError) as err: + connect_to_owner(socket.AF_INET, data, token) + assert not isinstance(err.value, ConnectionRefusedError) + assert isinstance(err.value, ConnectionResetError) or "rejected" in str(err.value) + + +def test_tls_needs_cert_and_key(make_cert): + cert, _key = make_cert() + with pytest.raises(SharedStorageError, match="both tls_cert and tls_key"): + ClusterSharedStorage(host="peers", secret="s", tls_cert=cert) + with pytest.raises(SharedStorageError, match="cannot load the cluster TLS"): + ClusterSharedStorage( + host="peers", secret="s", tls_cert=cert, tls_key="/does/not/exist" + ) + + +def test_tls_with_a_ca_and_a_certificate_per_pod(pods, make_cert): + ca = make_cert("cluster-ca") + a, b = pods.add_pod(), pods.add_pod() + stores = [] + for pod in (a, b): + cert, key = make_cert(f"pod-{pod}", signed_by=ca) + stores.append(pods.worker(pod, tls_cert=cert, tls_key=key, tls_ca=ca[0])) + for store in stores: + store.start() + stores[1].set("k", "signed") + assert stores[0].get("k") == "signed" + + # Signed by another CA: it never joins. + stranger_ca = make_cert("stranger-ca") + cert, key = make_cert("stranger", signed_by=stranger_ca) + c = pods.add_pod() + stranger = pods.worker(c, tls_cert=cert, tls_key=key, tls_ca=stranger_ca[0]) + stranger.start() + stranger.set("k", "stranger") + assert stores[0].get("k") == "signed" + + +def test_tls_server_only_certificate_is_refused_and_logged(pods, make_cert, caplog): + from dash._shared_storage import _cluster_lock + + cert, key = make_cert( + "server-only", extra=("-addext", "extendedKeyUsage=serverAuth") + ) + _cluster_lock._tls_failed.clear() + a, b = pods.add_pod(), pods.add_pod() + first = pods.worker(a, tls_cert=cert, tls_key=key) + first.start() + second = pods.worker(b, tls_cert=cert, tls_key=key) + second.start() + assert first._coord.is_owner() and second._coord.is_owner() + assert any("TLS handshake" in r.getMessage() for r in caplog.records) + + +def test_tls_options_fail_loudly(make_cert): + cert, key = make_cert() + with pytest.raises(SharedStorageError, match="both tls_cert and tls_key"): + ClusterSharedStorage(host="peers", secret="s", tls_cert="", tls_key="") + locked, locked_key = make_cert("locked", extra=("-passout", "pass:pw")) + started = time.monotonic() + with pytest.raises(SharedStorageError, match="cannot load the cluster TLS"): + ClusterSharedStorage( + host="peers", secret="s", tls_cert=locked, tls_key=locked_key + ) + assert time.monotonic() - started < 5 + ClusterSharedStorage(host="peers", secret="s", tls_cert=cert, tls_key=key).close() + + +QUORUM = {"replicas": 3, "settle_timeout": 30.0} + + +def test_replicas_must_be_a_positive_integer(): + for bad in (0, "3", True): + with pytest.raises(SharedStorageError, match="replicas"): + ClusterSharedStorage(host="peers", secret="s", replicas=bad) + + +def test_quorum_pods_need_a_majority_and_fence_a_cut_off_owner(pods): + a, b, c = pods.add_pod(), pods.add_pod(), pods.add_pod() + alone = pods.worker(a, replicas=3, settle_timeout=1.0) + with pytest.raises(SharedStorageError, match="no shared-storage cluster owner"): + alone.start() + stores = {pod: pods.worker(pod, **QUORUM) for pod in (a, b, c)} + # Each start waits for a majority, so they must start together. + starts = [threading.Thread(target=store.start) for store in stores.values()] + for thread in starts: + thread.start() + for thread in starts: + thread.join(30) + stores[b].set("k", 1) + assert all(store.get("k") == 1 for store in stores.values()) + + # The pod a lock is the first worker's, which failed to start alone. + locks = {a: alone._coord._cluster, b: stores[b]._coord._cluster} + locks[c] = stores[c]._coord._cluster + cut = next(pod for pod, lock in locks.items() if lock.state.role == "owner") + rest = [pod for pod in (a, b, c) if pod != cut] + term = locks[cut].state.term + pods.isolate([cut], rest) + + # The cut-off owner stops owning, and the majority carries on. + until(lambda: not locks[cut].is_owner(term), timeout=20) + deadline = time.monotonic() + 30 + while True: + try: + stores[rest[0]].set("k", 2) + break + except SharedStorageError: + assert time.monotonic() < deadline + time.sleep(0.2) + assert stores[rest[1]].get("k") == 2 + stores[cut]._coord.failover_window = 1.0 + with pytest.raises(SharedStorageError): + stores[cut].set("k", "lost") + + +def test_starts_at_boot_only_in_majority_mode(): + import functools + + from dash._shared_storage.cluster import starts_at_boot + + assert starts_at_boot(functools.partial(ClusterSharedStorage, replicas=3)) + assert not starts_at_boot(functools.partial(ClusterSharedStorage, host="x")) + assert not starts_at_boot(ClusterSharedStorage) + assert not starts_at_boot(None) + store = ClusterSharedStorage(host="peers", secret="s", replicas=3) + assert starts_at_boot(store) + store.close() + store = ClusterSharedStorage(host="peers", secret="s") + assert not starts_at_boot(store) + store.close() + + +def test_majority_mode_joins_the_election_before_any_request(pods): + # Only one app is ever used; the others must still vote, or it waits for + # a majority that never comes. + from dash import Dash + + a, b, c = pods.add_pod(), pods.add_pod(), pods.add_pod() + apps = [Dash(shared_storage=pods.worker(pod, **QUORUM)) for pod in (a, b, c)] + until(lambda: apps[0]._shared_storage_instance is not None, timeout=30) + apps[0].shared_storage.set("k", 1) + assert apps[0].shared_storage.get("k") == 1 + + +FORK_SCRIPT = """ +import os, socket, sys, time +from dash import Dash +from dash._shared_storage import ClusterSharedStorage + +port = int(sys.argv[1]) +store = ClusterSharedStorage( + port=port, secret="s", peers=lambda: [("127.0.0.1", port)], + replicas=1, probe_interval=0.05, +) +app = Dash(shared_storage=store) +other = Dash(shared_storage=store) # one instance, two fork handlers +deadline = time.monotonic() + 20 +while app._shared_storage_instance is None: + assert time.monotonic() < deadline, "parent never started" + time.sleep(0.05) +pid = os.fork() +if pid == 0: + try: + time.sleep(0.5) + # No boot in a child: the parent already votes for this replica. + assert app._shared_storage_instance is None + assert store._coord._cluster is None + app.shared_storage.set("from-child", os.getpid()) + assert other.shared_storage.get("from-child") == os.getpid() + os._exit(0) + except BaseException as err: + print("child:", repr(err), flush=True) + os._exit(1) +_, status = os.waitpid(pid, 0) +assert status == 0, status +assert app.shared_storage.get("from-child") == pid +print("ok") +""" + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") +def test_majority_mode_survives_a_preload_fork(pods, tmp_path): + import subprocess + import sys + + script = tmp_path / "fork_app.py" + script.write_text(FORK_SCRIPT) + port = _port_pair() + import dash + + root = os.path.dirname(os.path.dirname(dash.__file__)) + env = {**os.environ, "PYTHONPATH": root} + out = subprocess.run( + [sys.executable, str(script), str(port)], + env=env, + capture_output=True, text=True, timeout=60, check=False, + ) # fmt: skip + assert out.stdout.strip().endswith("ok"), out.stdout + out.stderr + + +def test_lapsed_lease_never_restarts_the_store_under_the_same_term(pods): + a = pods.add_pod() + store = pods.worker(a, replicas=1) + store.start() + store.set("k", 1) + coord = store._coord + coord._settle_timeout = 1.0 + lock, engine = coord._cluster, coord._engine + stall = threading.Event() + lock._tick = stall.wait # the lease lapses, the lock never steps down + try: + time.sleep(lock.lease + 0.2) + with pytest.raises(SharedStorageError): + coord.is_owner() + assert coord._engine in (None, engine) + finally: + stall.set() + + +def test_an_election_waiting_on_a_lapsed_lease_lets_the_lock_step_down(pods): + # The request elects under the coordinator lock and waits on the probe + # thread; the probe thread must not wait on that lock to step down. + a = pods.add_pod() + store = pods.worker(a, replicas=1) + store.start() + coord = store._coord + lock = coord._cluster + tick = lock._tick + stall = threading.Event() + + def stalled(): + stall.wait() + tick() + + lock._tick = stalled + time.sleep(lock.lease + 0.2) + result = {} + + def elect(): + try: + result["owner"] = coord.is_owner() + except Exception as err: # pylint: disable=broad-exception-caught + result["err"] = err + + thread = threading.Thread(target=elect) + thread.start() + time.sleep(0.3) + stall.set() + thread.join(15) + assert result.get("owner") is True, result + + +def test_a_replica_that_cannot_serve_leaves_ownership_to_another(pods): + a, b = pods.add_pod(), pods.add_pod() + blocker = socket.create_server(("", pods.ports[a] + 1)) + try: + sa = pods.worker(a) + started = {} + + def start_a(): + try: + sa.start() + started["ok"] = True + except Exception as err: # pylint: disable=broad-exception-caught + started["err"] = err + + thread = threading.Thread(target=start_a) + thread.start() + until(lambda: sa._coord._cluster is not None, message="a never ran its lock") + until(lambda: sa._coord._cluster._resigned(), message="a never resigned") + sb = pods.worker(b) + sb.start() + thread.join(15) + assert started == {"ok": True}, started + sa.set("k", "from-a") + assert sb.get("k") == "from-a" + assert sb._coord.is_owner() + finally: + blocker.close() + + +FORGET_SCRIPT = """ +import os, sys +from dash._shared_storage import ClusterSharedStorage +from dash._shared_storage._persistence import ChunkedStore + +port, path = int(sys.argv[1]), sys.argv[2] +store = ClusterSharedStorage( + port=port, secret="s", peers=lambda: [("127.0.0.1", port)], + probe_interval=0.05, mode="persist-reset", path=path, flush_interval=3600, +) +store.start() +store.set("k", "before-fork") +r, w = os.pipe() +pid = os.fork() +if pid == 0: + store.after_fork() + os.read(r, 1) + import atexit + atexit._run_exitfuncs() # what a worker that exits normally runs + os._exit(0) +store.set("k", "after-fork") +store.close() +os.write(w, b"x") +_, status = os.waitpid(pid, 0) +assert status == 0, status +print(ChunkedStore(path).load_all()["k"][0]) +""" + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") +def test_a_forked_child_exiting_never_flushes_the_parents_store(tmp_path): + import subprocess + import sys + + import dash + + script = tmp_path / "forget.py" + script.write_text(FORGET_SCRIPT) + root = os.path.dirname(os.path.dirname(dash.__file__)) + out = subprocess.run( + [sys.executable, str(script), str(_port_pair()), str(tmp_path / "store")], + env={**os.environ, "PYTHONPATH": root}, + capture_output=True, text=True, timeout=60, check=False, + ) # fmt: skip + assert out.stdout.strip() == "after-fork", out.stdout + out.stderr + + +def _owner_server(monkeypatch, timeout=0.3): + from dash._shared_storage import _transport + from dash._shared_storage._engine import StoreEngine + + monkeypatch.setattr(_transport, "_HANDSHAKE_TIMEOUT", timeout) + sock = socket.create_server(("127.0.0.1", 0)) + server = _transport.OwnerServer(StoreEngine(16), sock, "tok") + return server, sock.getsockname() + + +def _closed_by_peer(conn): + try: + return conn.recv(1) == b"" + except ConnectionResetError: + return True + + +def test_owner_drops_a_connection_that_never_shows_its_token(monkeypatch): + server, addr = _owner_server(monkeypatch) + server.start() + try: + with socket.create_connection(addr, timeout=3) as idle: + assert _closed_by_peer(idle) + with socket.create_connection(addr, timeout=3) as huge: + huge.sendall(struct.pack("!I", 1 << 30)) + assert _closed_by_peer(huge) + # A byte at a time, each well within the timeout of a single read. + with socket.create_connection(addr, timeout=3) as drip: + drip.sendall(struct.pack("!I", 200)) + started = time.monotonic() + with pytest.raises(OSError): + while time.monotonic() - started < 3: + drip.sendall(b"x") + time.sleep(0.1) + assert time.monotonic() - started < 1.5 + finally: + server.close() + + +def test_owner_keeps_accepting_after_an_accept_error(monkeypatch): + import errno + + from dash._shared_storage._transport import ( + connect_to_owner, + recv_frame, + send_frame, + ) + + server, addr = _owner_server(monkeypatch) + + class Flaky: + def __init__(self, sock): + self._sock = sock + self.failed = False + + def accept(self): + if not self.failed: + self.failed = True + raise OSError(errno.EMFILE, "Too many open files") + return self._sock.accept() + + def __getattr__(self, name): + return getattr(self._sock, name) + + server._sock = Flaky(server._sock) + server.start() + try: + conn = connect_to_owner(socket.AF_INET, addr, "tok", timeout=3) + with conn: + send_frame(conn, ["set", "k", 1]) + assert recv_frame(conn) == ["ok", None] + assert server._sock.failed + finally: + server.close() + + +class _DeafOwner: + """Takes the handshake, then never reads again.""" + + def __init__(self): + self._server = socket.create_server(("127.0.0.1", 0)) + self.addr = self._server.getsockname() + self._done = threading.Event() + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + def _serve(self): + from dash._shared_storage._transport import OK, recv_frame, send_frame + + conn, _ = self._server.accept() + with conn: + recv_frame(conn) + send_frame(conn, OK) + self._done.wait(30) + + def close(self): + self._done.set() + self._server.close() + self._thread.join(10) + + +def test_an_async_request_to_an_owner_that_stops_reading_times_out(): + from dash._shared_storage.local import _AsyncConn + + owner = _DeafOwner() + try: + conn = _AsyncConn(_SilentCoord(owner.addr)) + started = time.monotonic() + + async def run(): + await asyncio.wait_for(conn.call(["set", "k", "x" * (64 << 20)]), 10) + + with pytest.raises(asyncio.TimeoutError): + asyncio.run(run()) + assert time.monotonic() - started < 5 + assert conn._streams is None + finally: + owner.close() + + +def test_a_failed_lock_change_does_not_stop_later_ones(pods): + a = pods.add_pod() + store = pods.worker(a) + store.start() + coord = store._coord + applied = threading.Event() + calls = [] + + def serve(term): + calls.append(term) + if len(calls) == 1: + raise RuntimeError("boom") + applied.set() + return True + + coord._serve_or_resign = serve + coord._on_change(None) + until(lambda: calls, message="the change was never applied") + coord._on_change(None) + assert applied.wait(5), "the change thread died" diff --git a/tests/shared_storage/test_cluster_lock.py b/tests/shared_storage/test_cluster_lock.py new file mode 100644 index 0000000000..196bceaaa5 --- /dev/null +++ b/tests/shared_storage/test_cluster_lock.py @@ -0,0 +1,759 @@ +"""ClusterLock: owner election among replicas over loopback TCP. + +Each test hands its locks a fake DNS (a function returning peer addresses), so +partial and changing views are easy to set up. +""" +import json +import os +import secrets +import signal +import socket +import struct +import subprocess +import sys +import textwrap +import threading +import time + +import pytest + +from dash._shared_storage._cluster_lock import ( + ELECTING, + FOLLOWER, + OWNER, + ClusterLock, + _mac, + _recv, + _send, + probe, + resolve_peers, +) + +SECRET = b"test-secret" +FAST = {"probe_interval": 0.05, "probe_timeout": 0.5, "miss_limit": 2} + + +def until(predicate, timeout=10.0, message="condition not met"): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if predicate(): + return + time.sleep(0.01) + raise AssertionError(message) + + +class Cluster: + """Locks on loopback that see each other through ``views``: per lock, the + indexes of the locks it can resolve (all of them by default).""" + + def __init__(self): + self.locks = [] + self.views = {} + self.changes = {} + self._mutex = threading.Lock() + + def add(self, secret=SECRET, start=True, peers=None, **kw): + idx = len(self.locks) + changes = self.changes[idx] = [] + kw.setdefault("on_change", changes.append) + lock = ClusterLock( + peers=peers or (lambda: self._peers(idx)), + secret=secret, + bind=("127.0.0.1", 0), + advert={"data_port": 1000 + idx}, + **{**FAST, **kw}, + ) + self.locks.append(lock) + if start: + lock.start() + return lock + + def _peers(self, idx): + with self._mutex: + allowed = self.views.get(idx) + ports = [lock.port for lock in self.locks] + if allowed is not None: + ports = [p for i, p in enumerate(ports) if i in allowed] + return [("127.0.0.1", p) for p in ports] + + def see(self, idx, others): + with self._mutex: + self.views[idx] = set(others) | {idx} + + def see_all(self): + with self._mutex: + self.views.clear() + + def live(self): + return [lock for lock in self.locks if not lock._closed.is_set()] + + def owners(self, locks=None): + return [lock for lock in (locks or self.live()) if lock.state.role == OWNER] + + def settled(self, locks=None): + """One owner, and everyone else following it under its term.""" + locks = locks or self.live() + owners = self.owners(locks) + if len(owners) != 1: + return None + owner = owners[0] + for lock in locks: + if lock is owner: + continue + state = lock.state + if state.role != FOLLOWER or state.owner_id != owner.id: + return None + if state.term != owner.state.term: + return None + return owner + + def wait_settled(self, timeout=10.0, locks=None): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + owner = self.settled(locks) + if owner is not None: + return owner + time.sleep(0.02) + roles = [ + (lock.id, lock.state.role, lock.state.owner_id) for lock in self.live() + ] + raise AssertionError(f"cluster did not settle: {roles}") + + def close(self): + for lock in self.locks: + lock.close() + + +@pytest.fixture +def cluster(): + c = Cluster() + yield c + c.close() + + +def test_single_replica_owns(cluster): + lock = cluster.add() + state = lock.wait_settled(5) + assert state.role == OWNER and state.term + assert lock.is_owner(state.term) + assert not lock.is_owner("other") + assert not lock.is_owner(None) + + +def test_replicas_booting_together_settle_on_one_owner(cluster): + for _ in range(6): + cluster.add(start=False) + for lock in cluster.locks: + lock.start() + owner = cluster.wait_settled() + follower = next(lock for lock in cluster.locks if lock is not owner) + assert follower.state.owner_addr == ("127.0.0.1", owner.port) + idx = cluster.locks.index(owner) + assert follower.state.advert == {"data_port": 1000 + idx} + + +def test_late_joiner_follows_and_never_deposes(cluster): + first = cluster.add() + assert first.wait_settled(5).role == OWNER + cluster.add() + owner = cluster.wait_settled() + assert owner is first + term = owner.state.term + late = cluster.add() + cluster.wait_settled() + assert late.state.role == FOLLOWER + assert owner.state == (OWNER, term, owner.id, None, None) + + +def test_split_views_heal_to_the_longest_owner(cluster): + for _ in range(4): + cluster.add(start=False) + a, b, c, d = cluster.locks + cluster.see(0, [1]) + cluster.see(1, [0]) + cluster.see(2, [3]) + cluster.see(3, [2]) + a.start() + b.start() + first = cluster.wait_settled(locks=[a, b]) + time.sleep(0.1) + c.start() + d.start() + second = cluster.wait_settled(locks=[c, d]) + assert len(cluster.owners()) == 2 + + cluster.see_all() + assert cluster.wait_settled() is first + assert not second.is_owner(second.state.term) + last = cluster.changes[cluster.locks.index(second)][-1] + assert last.role == FOLLOWER and last.owner_id == first.id + + +def test_owners_that_claimed_together_still_merge(cluster): + # Each owner sees its own age now and the other's from a moment ago: with + # claims a round trip apart, both would think they are older. + for _ in range(20): + cluster.add(start=False) + cluster.add(start=False) + i, j = len(cluster.locks) - 2, len(cluster.locks) - 1 + a, b = cluster.locks[i], cluster.locks[j] + for idx in range(len(cluster.locks)): + cluster.see(idx, [idx]) + a.start() + b.start() + assert a.wait_settled(5).role == OWNER and b.wait_settled(5).role == OWNER + for idx in (i, j): + cluster.see(idx, [i, j]) + cluster.wait_settled(timeout=5, locks=[a, b]) + a.close() + b.close() + + +def test_followers_take_over_when_the_owner_goes(cluster): + for _ in range(4): + cluster.add() + owner = cluster.wait_settled() + old_term = owner.state.term + owner.close() + assert not owner.is_owner(old_term) + new_owner = cluster.wait_settled() + assert new_owner is not owner + assert new_owner.state.term != old_term + + +def test_follower_gives_up_after_miss_limit_probes(cluster): + cluster.add() + cluster.wait_settled(5) + probes = [] + hidden = threading.Event() + + def peers(): + if hidden.is_set(): + probes.append(1) + return [] + return cluster._peers(1) + + follower = cluster.add(peers=peers, miss_limit=5) + cluster.wait_settled() + hidden.set() + until(lambda: follower.state.role == OWNER, message="follower never claimed") + # Five misses to give up on the owner, and alone it claims on the fifth. + assert len(probes) >= 5 + + +def test_brief_miss_does_not_flap_to_another_owner(cluster): + a = cluster.add() + assert a.wait_settled(5).role == OWNER + f = cluster.add(miss_limit=1000) + cluster.wait_settled() + b = cluster.add(start=False) + cluster.see(2, []) + b.start() + assert b.wait_settled(5).role == OWNER + time.sleep(0.2) + assert f.state.owner_id == a.id + before = len(cluster.changes[1]) + + cluster.see(1, [2]) + time.sleep(0.3) + assert f.state.owner_id == a.id + assert len(cluster.changes[1]) == before + cluster.see(1, [0, 2]) + time.sleep(0.2) + assert f.state.owner_id == a.id + + +def test_waits_for_a_lower_id_that_is_electing(cluster): + release = threading.Event() + a = cluster.add(start=False) + b = cluster.add(start=False, miss_limit=1000) + if a.id > b.id: + a.id, b.id = b.id, a.id + low, high = a, b + + def slow_peers(): + # The low replica answers probes but has not decided anything yet. + release.wait() + return cluster._peers(0) + + low._peers = slow_peers + low.start() + high.start() + time.sleep(0.4) + assert high.state.role == ELECTING + release.set() + assert cluster.wait_settled() is low + + +def test_wait_on_a_lower_id_is_bounded(cluster): + release = threading.Event() + a = cluster.add(start=False) + b = cluster.add(start=False, miss_limit=3) + if a.id > b.id: + a.id, b.id = b.id, a.id + a._peers = lambda: (release.wait(), cluster._peers(0))[1] + a.start() + b.start() + try: + assert b.wait_settled(5).role == OWNER + finally: + release.set() + assert cluster.wait_settled() is b + + +def test_raising_on_change_does_not_stop_the_lock(cluster): + def boom(_state): + raise RuntimeError("callback bug") + + a = cluster.add(on_change=boom) + assert a.wait_settled(5).role == OWNER + cluster.add(on_change=boom) + cluster.wait_settled() + a.close() + until(lambda: cluster.locks[1].state.role == OWNER) + + +class FakePeer: + """Completes the handshake with the right secret, then answers ``view``.""" + + def __init__(self, view, sent=None): + self.view = view + self.sent = sent + self.sock = socket.create_server(("127.0.0.1", 0)) + self.port = self.sock.getsockname()[1] + threading.Thread(target=self._serve, daemon=True).start() + + def _serve(self): + while True: + try: + conn, _ = self.sock.accept() + except OSError: + return + with conn: + try: + deadline = time.monotonic() + 2 + nonce = _recv(conn, deadline) + challenge = secrets.token_hex(16) + _send(conn, [challenge, _mac(SECRET, b"server", nonce)]) + _recv(conn, deadline) + raw = json.dumps(self.view) + mac = _mac(SECRET, b"view", nonce, raw) + if self.sent is not None: + raw = json.dumps(self.sent) + _send(conn, [raw, mac]) + except Exception: # pylint: disable=broad-exception-caught + pass + + def close(self): + self.sock.close() + + +@pytest.mark.parametrize( + "view", + [ + {"id": "zzz", "role": "owner", "term": "t"}, + {"id": "zzz", "role": "owner", "term": "t", "age": None}, + {"id": "zzz", "role": "owner", "term": "t", "age": "old"}, + {"id": ["x"], "role": "owner", "term": "t", "age": 1.0}, + {"id": "zzz", "role": "king"}, + {"id": "zzz", "role": "owner", "term": "t", "age": 1.0}, + {"id": "zzz", "role": "owner", "term": "t", "age": 1.0, "rivals": [1]}, + ["not", "a", "dict"], + ], +) +def test_malformed_views_are_ignored(cluster, view): + fake = FakePeer(view) + try: + lock = cluster.add( + peers=lambda: [("127.0.0.1", fake.port), ("127.0.0.1", lock.port)] + ) + assert lock.wait_settled(5).role == OWNER + other = cluster.add( + peers=lambda: [("127.0.0.1", fake.port), ("127.0.0.1", lock.port)] + ) + until(lambda: other.state.owner_id == lock.id, message="probe thread died") + finally: + fake.close() + + +def test_forged_view_is_rejected(cluster): + # Signs a harmless view, then sends one claiming the oldest ownership, as + # an on-path attacker rewriting the answer would. + fake = FakePeer( + {"id": "aaa", "role": "electing", "term": None}, + sent={"id": "aaa", "role": "owner", "term": "t", "age": 1e9, "rivals": []}, + ) + try: + lock = cluster.add(peers=lambda: [("127.0.0.1", fake.port)]) + assert lock.wait_settled(5).role == OWNER + time.sleep(0.2) + assert lock.state.role == OWNER + finally: + fake.close() + + +def test_signed_view_is_followed(cluster): + fake = FakePeer( + {"id": "aaa", "role": "owner", "term": "t", "age": 1e9, "rivals": []} + ) + try: + lock = cluster.add(peers=lambda: [("127.0.0.1", fake.port)]) + assert lock.wait_settled(5).owner_id == "aaa" + finally: + fake.close() + + +def test_answers_nothing_to_unauthenticated_clients(cluster): + lock = cluster.add() + lock.wait_settled(5) + with socket.create_connection(("127.0.0.1", lock.port), timeout=2) as conn: + _send(conn, "nonce") + challenge, _proof = _recv(conn, time.monotonic() + 2) + _send(conn, "not-the-proof") + conn.settimeout(2) + assert conn.recv(1) == b"" + assert isinstance(challenge, str) + + +def test_oversized_and_dripped_frames_are_dropped(cluster): + lock = cluster.add(probe_timeout=0.3) + lock.wait_settled(5) + with socket.create_connection(("127.0.0.1", lock.port), timeout=2) as conn: + conn.sendall(struct.pack("!I", 10**9)) + assert conn.recv(1) == b"" + with socket.create_connection(("127.0.0.1", lock.port), timeout=2) as conn: + start = time.monotonic() + conn.sendall(struct.pack("!I", 10)) + try: + for _ in range(10): + conn.sendall(b"x") + time.sleep(0.1) + except OSError: + pass + conn.settimeout(2) + try: + assert conn.recv(1) == b"" + except ConnectionResetError: + pass + assert time.monotonic() - start < 1.5 + + +def test_closed_lock_stops_answering(cluster): + lock = cluster.add() + term = lock.wait_settled(5).term + lock.close() + assert not lock.is_owner(term) + with pytest.raises(OSError): + socket.create_connection(("127.0.0.1", lock.port), timeout=1).close() + for thread in lock._threads: + thread.join(2) + assert not thread.is_alive() + + +def test_wrong_secret_is_never_followed(cluster): + good = cluster.add() + good.wait_settled(5) + rogue = cluster.add(secret=b"wrong") + rogue.wait_settled(5) + time.sleep(0.3) + assert good.state.role == OWNER + assert rogue.state.role == OWNER + assert cluster.changes[0] == [good.state] + + +_NODE = textwrap.dedent( + """ + import sys, time + from dash._shared_storage._cluster_lock import ClusterLock + ports = [int(p) for p in sys.argv[1].split(",")] + lock = ClusterLock( + peers=lambda: [("127.0.0.1", p) for p in ports], + secret=b"test-secret", + bind=("127.0.0.1", int(sys.argv[2])), + probe_interval=0.05, + miss_limit=2, + ).start() + print(lock.id, flush=True) + while True: + time.sleep(1) + """ +) + + +def _free_ports(n): + socks = [socket.create_server(("127.0.0.1", 0)) for _ in range(n)] + ports = [s.getsockname()[1] for s in socks] + for s in socks: + s.close() + return ports + + +@pytest.mark.skipif(sys.platform == "win32", reason="SIGKILL") +def test_killed_owner_process_is_replaced(cluster): + ports = _free_ports(3) + local_port = ports[2] + all_ports = ",".join(str(p) for p in ports) + procs = {} + try: + for port in ports[:2]: + proc = subprocess.Popen( + [sys.executable, "-c", _NODE, all_ports, str(port)], + stdout=subprocess.PIPE, + text=True, + ) + procs[proc.stdout.readline().strip()] = proc + time.sleep(0.5) + # Joins after the processes elected, so it follows one of them. + local = ClusterLock( + peers=lambda: [("127.0.0.1", p) for p in ports], + secret=SECRET, + bind=("127.0.0.1", local_port), + **FAST, + ).start() + cluster.locks.append(local) + state = local.wait_settled(10) + assert state.role == FOLLOWER and state.owner_id in procs + + dead = state.owner_id + os.kill(procs[dead].pid, signal.SIGKILL) + until( + lambda: local.state.role != ELECTING + and local.state.owner_id not in (dead, None) + or local.state.role == OWNER, + message="no new owner after the kill", + ) + finally: + for proc in procs.values(): + proc.kill() + proc.wait() + + +def test_resolve_peers(): + peers = resolve_peers("localhost", 8050) + assert peers and all(port == 8050 for _host, port in peers) + assert resolve_peers("does-not-resolve.invalid", 8050) == [] + + +def _tls(make_cert, name="replica"): + from dash._shared_storage._cluster_lock import tls_contexts + + return tls_contexts(*make_cert(name)) + + +def test_tls_replicas_settle(cluster, make_cert): + tls = _tls(make_cert) + for _ in range(3): + cluster.add(tls=tls) + owner = cluster.wait_settled() + view = probe(("127.0.0.1", owner.port), SECRET, 1.0, tls.client) + assert view["role"] == OWNER and view["id"] == owner.id + + +def test_tls_lock_answers_no_plaintext_probe(cluster, make_cert): + lock = cluster.add(tls=_tls(make_cert)) + lock.wait_settled(5) + assert probe(("127.0.0.1", lock.port), SECRET, 1.0) is None + + +def test_tls_rejects_a_certificate_from_another_ca(cluster, make_cert): + good = cluster.add(tls=_tls(make_cert)) + good.wait_settled(5) + other = _tls(make_cert, "other") + assert probe(("127.0.0.1", good.port), SECRET, 1.0, other.client) is None + rogue = cluster.add(tls=other) + rogue.wait_settled(5) + time.sleep(0.3) + assert good.state.role == OWNER and rogue.state.role == OWNER + + +def test_plaintext_and_tls_replicas_do_not_mix(cluster, make_cert): + tls_lock = cluster.add(tls=_tls(make_cert)) + tls_lock.wait_settled(5) + plain = cluster.add() + plain.wait_settled(5) + time.sleep(0.3) + assert tls_lock.state.role == OWNER and plain.state.role == OWNER + + +QUORUM = {"replicas": 3, "probe_timeout": 0.2} + + +def _owning(locks): + return [lock for lock in locks if lock.is_owner(lock.state.term)] + + +def test_replicas_must_be_a_positive_integer(cluster): + for bad in (0, -1, 2.0, True, "3"): + with pytest.raises(ValueError, match="replicas"): + cluster.add(replicas=bad) + + +def test_quorum_lone_replica_waits_for_a_majority(cluster): + lone = cluster.add(**QUORUM) + time.sleep(lone.lease * 2) + assert lone.state.role == ELECTING + cluster.add(**QUORUM) + owner = cluster.wait_settled() + assert owner.is_owner(owner.state.term) + + +def test_quorum_minority_owner_stops_before_the_majority_claims(cluster): + for _ in range(3): + cluster.add(**QUORUM) + old = cluster.wait_settled() + i = cluster.locks.index(old) + rest = [j for j in range(3) if j != i] + cluster.see(i, []) + for j in rest: + cluster.see(j, rest) + + majority = [cluster.locks[j] for j in rest] + deadline = time.monotonic() + 20 + while time.monotonic() < deadline: + owning = _owning(cluster.locks) + assert len(owning) <= 1, "two owners at once" + if owning and owning[0] is not old: + break + time.sleep(0.002) + else: + raise AssertionError("the majority never elected an owner") + new = cluster.wait_settled(locks=majority) + assert old.state.role == ELECTING + + time.sleep(old.lease) + assert old.state.role == ELECTING # alone, it never claims back + cluster.see_all() + assert cluster.wait_settled() is new + + +def test_quorum_no_claim_while_a_peer_follows_a_live_owner(cluster): + # B cannot reach the owner but reaches C, which follows it. B and C are a + # majority by count, yet C is the owner's: B must not claim. + for _ in range(3): + cluster.add(**QUORUM) + owner = cluster.wait_settled() + i = cluster.locks.index(owner) + b, c = [j for j in range(3) if j != i] + cluster.see(b, [c]) + cluster.see(i, [c]) + deadline = time.monotonic() + owner.lease * 3 + while time.monotonic() < deadline: + assert _owning(cluster.locks) == [owner] + time.sleep(0.01) + assert cluster.locks[c].state.owner_id == owner.id + + +def test_quorum_owner_is_fenced_even_with_a_stalled_probe_thread(cluster): + for _ in range(3): + cluster.add(**QUORUM) + owner = cluster.wait_settled() + term = owner.state.term + stall = threading.Event() + owner._tick = stall.wait # the probe thread stops renewing + time.sleep(owner.lease + 0.2) + assert owner.state.role == OWNER + assert not owner.is_owner(term) + stall.set() + + +def test_quorum_owner_survives_while_followed(cluster): + for _ in range(3): + cluster.add(**QUORUM) + owner = cluster.wait_settled() + term = owner.state.term + deadline = time.monotonic() + owner.lease * 3 + while time.monotonic() < deadline: + assert owner.is_owner(term) + time.sleep(0.01) + + +def test_quorum_one_way_loss_never_gives_two_owners(cluster): + # C drops out first; then B stops reaching the owner while the owner still + # reaches B, so B still counts toward its lease while it gives up on it. + for _ in range(3): + cluster.add(**QUORUM) + owner = cluster.wait_settled() + i = cluster.locks.index(owner) + b, c = sorted((j for j in range(3) if j != i), key=lambda j: cluster.locks[j].id) + cluster.see(c, [b]) + cluster.see(i, [b]) + until(lambda: cluster.locks[c].state.role == ELECTING) + time.sleep(owner.lease * 2) + assert owner.is_owner(owner.state.term) + cluster.see(b, [c]) + deadline = time.monotonic() + owner.lease * 3 + while time.monotonic() < deadline: + assert len(_owning(cluster.locks)) <= 1, "two owners at once" + time.sleep(0.002) + + +def test_quorum_passes_over_a_candidate_that_cannot_claim(cluster): + for _ in range(3): + cluster.add(start=False, **QUORUM) + low = min(range(3), key=lambda j: cluster.locks[j].id) + cluster.see(low, []) # the others see it, it sees no one + for lock in cluster.locks: + lock.start() + others = [lock for j, lock in enumerate(cluster.locks) if j != low] + owner = cluster.wait_settled(timeout=30, locks=others) + assert owner is not cluster.locks[low] + assert cluster.locks[low].state.role == ELECTING + + +def test_a_claim_counts_backing_only_up_to_the_round_start(): + # The lease runs from the round start: backing seen in that round but + # counted after a stall must not stretch past it, or a voter that went back + # to the old owner meanwhile sits in two majorities. + lock = ClusterLock(peers=list, secret=SECRET, bind=("127.0.0.1", 0), replicas=3) + try: + now = time.monotonic() + lock._ballot = (lock.id, 1) + lock._ballot_since = now - 2 * lock.lease + lock._backers = {"peer": (1, now - lock.lease - 0.5)} + assert not lock._may_claim(now - 1.0) + assert lock._may_claim(now) + finally: + lock.close() + + +def test_a_round_judges_the_claim_at_its_start(): + def slow_peers(): + time.sleep(0.3) + return [] + + lock = ClusterLock( + peers=slow_peers, secret=SECRET, bind=("127.0.0.1", 0), replicas=3 + ) + seen = [] + lock._may_claim = lambda started: seen.append(started) or False + try: + before = time.monotonic() + lock._tick() + assert seen and seen[0] - before < 0.2 + finally: + lock.close() + + +def test_lock_messages_are_json_whatever_the_store_codec(): + # A replica with msgspec and one without must still understand each other. + lock = ClusterLock(peers=list, secret=SECRET, bind=("127.0.0.1", 0)).start() + try: + with socket.create_connection(("127.0.0.1", lock.port), timeout=5) as conn: + body = json.dumps("nonce").encode() + conn.sendall(struct.pack("!I", len(body)) + body) + (length,) = struct.unpack("!I", conn.recv(4, socket.MSG_WAITALL)) + challenge, proof = json.loads(conn.recv(length, socket.MSG_WAITALL)) + assert proof == _mac(SECRET, b"server", "nonce") + assert isinstance(challenge, str) + finally: + lock.close() + + +def test_a_resigned_owner_leaves_the_election_to_the_others(cluster): + a = cluster.add() + until(lambda: a.state.role == OWNER, message="a never claimed") + b = cluster.add() + until(lambda: b.state.role == FOLLOWER, message="b never followed a") + a.resign(a.state.term) + until(lambda: b.state.role == OWNER, message="b never took over") + until(lambda: a.state.role == FOLLOWER, message="a never followed b") diff --git a/tests/shared_storage/test_dash_integration.py b/tests/shared_storage/test_dash_integration.py index 2f07dbbf50..50eb1e8a1a 100644 --- a/tests/shared_storage/test_dash_integration.py +++ b/tests/shared_storage/test_dash_integration.py @@ -14,6 +14,7 @@ from dash import Dash, Input, Output, ctx, html from dash.testing.wait import until from dash._shared_storage import ( + ClusterSharedStorage, DiskcacheSharedStorage, LocalSharedStorage, RedisSharedStorage, @@ -109,6 +110,49 @@ def test_counter_shared_across_callbacks_local_persist(dash_duo, tmp_path): assert (tmp_path / "ss" / "index.msgpack").exists() +def _port_pair(): + """A port whose next one up is free too: ClusterSharedStorage uses both.""" + import socket # pylint: disable=import-outside-toplevel + + for _ in range(50): + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + port = probe.getsockname()[1] + try: + with socket.create_server(("", port)), socket.create_server(("", port + 1)): + return port + except OSError: + continue + raise RuntimeError("no free port pair") + + +def test_counter_shared_across_pods_cluster(dash_duo): + # The app is one pod; a second pod in this process shares its store. + ports = [_port_pair(), _port_pair()] + + def peers(): + return [("127.0.0.1", port) for port in ports] + + def pod(port): + return ClusterSharedStorage( + port=port, secret="s3cret", peers=peers, probe_interval=0.05 + ) + + other = pod(ports[1]) + try: + other.start() + other.set("count", 10) + dash_duo.start_server(_counter_app(pod(ports[0]))) + dash_duo.find_element("#bump").click() + dash_duo.wait_for_text_to_equal("#count", "11") + assert other.get("count") == 11 + other.set("count", 20) + dash_duo.find_element("#read").click() + dash_duo.wait_for_text_to_equal("#readout", "count=20") + finally: + other.close() + + def test_counter_shared_across_callbacks_diskcache(dash_duo, tmp_path): dash_duo.start_server( _counter_app(DiskcacheSharedStorage(directory=str(tmp_path / "ss"))) @@ -162,3 +206,33 @@ def cb(_n): with pytest.raises(SharedStorageError): app.shared_storage # noqa: B018 + + +def test_a_fork_while_shared_storage_starts_reaches_it(): + # A preload master's boot thread may still be electing when gunicorn + # forks: the child must drop that half-started backend's sockets too. + import functools + import threading + + starting, release = threading.Event(), threading.Event() + forked = [] + + class Slow: + def start(self): + starting.set() + release.wait(10) + + def after_fork(self): + forked.append(self) + + app = Dash(shared_storage=functools.partial(Slow)) + thread = threading.Thread(target=lambda: app.shared_storage, daemon=True) + thread.start() + try: + assert starting.wait(10) + app._shared_storage_after_fork() + assert len(forked) == 1 and isinstance(forked[0], Slow) + assert app._shared_storage_starting is None + finally: + release.set() + thread.join(10) diff --git a/tests/shared_storage/test_env_config.py b/tests/shared_storage/test_env_config.py index aca7dc66fc..0790093046 100644 --- a/tests/shared_storage/test_env_config.py +++ b/tests/shared_storage/test_env_config.py @@ -6,6 +6,7 @@ from dash import Dash from dash._shared_storage import ( + ClusterSharedStorage, DiskcacheSharedStorage, LocalSharedStorage, RedisSharedStorage, @@ -74,9 +75,84 @@ def test_redis(monkeypatch, url): storage.close() -def test_cluster_is_reserved(monkeypatch): - with pytest.raises(InvalidConfig, match="not supported in this version"): - _app(monkeypatch, "cluster://nodes") +def _cluster(storage): + coord = storage._coord + return coord, coord._port, coord._data_port + + +def test_cluster_from_url(monkeypatch): + monkeypatch.delenv("DASH_SECRET_KEY", raising=False) + storage = _built(_app(monkeypatch, "cluster://:s%40cret@app-peers:7200")) + assert isinstance(storage, ClusterSharedStorage) + coord, port, data_port = _cluster(storage) + assert (port, data_port) == (7200, 7201) + assert coord._role is None # nothing bound or probed yet + storage.close() + + +def test_cluster_tls_files_from_url(monkeypatch, make_cert): + cert, key = make_cert() + url = f"cluster://:pw@app-peers?tls_cert={cert}&tls_key={key}&tls_ca={cert}" + storage = _built(_app(monkeypatch, url)) + coord, _port, _data_port = _cluster(storage) + assert coord.client_ssl is not None and coord._tls is not None + storage.close() + + +def test_cluster_tls_path_keeps_plus(monkeypatch, make_cert, tmp_path): + import shutil + + cert, key = make_cert() + odd = tmp_path / "a+b" + odd.mkdir() + shutil.copy(cert, odd / "cert.pem") + shutil.copy(key, odd / "key.pem") + url = f"cluster://:pw@app-peers?tls_cert={odd}/cert.pem&tls_key={odd}/key.pem" + storage = _built(_app(monkeypatch, url)) + assert storage._coord._tls is not None + storage.close() + + +def test_cluster_replicas_from_url(monkeypatch): + # Majority mode starts at boot; this test only reads the URL. + monkeypatch.setattr(Dash, "_start_shared_storage_at_boot", lambda self: None) + storage = _built(_app(monkeypatch, "cluster://:pw@app-peers?replicas=3")) + coord = storage._coord + assert coord._replicas == 3 + assert coord.failover_window > 10 + storage.close() + + +def test_cluster_secret_from_env_and_default_port(monkeypatch): + monkeypatch.setenv("DASH_SECRET_KEY", "from-env") + storage = _built(_app(monkeypatch, "cluster://app-peers")) + _coord, port, _data_port = _cluster(storage) + assert port == 7100 + storage.close() + + +@pytest.mark.parametrize( + "value, reason", + [ + ("cluster://app-peers", "needs a secret"), + ("cluster://:pw@", "needs a host"), + ("cluster://:pw@app-peers:notaport", "valid port"), + ("cluster://:pw@app-peers:65535", "below 65535"), + ("cluster://:pw@app-peers/path", "only a host"), + ("cluster://:pw@app-peers?mode=persist", "only tls_cert"), + ("cluster://:pw@app-peers?replicas=0", "positive integer"), + ("cluster://:pw@app-peers?replicas=three", "positive integer"), + ("cluster://:pw@app-peers?replicas=3&replicas=5", "once each"), + ("cluster://:pw@app-peers?tls_cert=/a", "both tls_cert and tls_key"), + ("cluster://:pw@app-peers?tls_cert=/a&tls_key=/b&tls_cert=/c", "once each"), + ("cluster://:pw@app-peers:0", "valid port"), + ("cluster://pw@app-peers", "after a colon"), + ], +) +def test_cluster_rejects(monkeypatch, value, reason): + monkeypatch.delenv("DASH_SECRET_KEY", raising=False) + with pytest.raises(InvalidConfig, match=reason): + _app(monkeypatch, value) @pytest.mark.parametrize("value", ["memcached://x", "redis", "/tmp/cache", "true"]) @@ -90,7 +166,7 @@ def test_garbage_names_the_variable(monkeypatch, value): [ "valkey://:hunter2@host:6379", "valkey://default:Zx9/Qm+4kP@cache.internal:6379/0", - "cluster://admin:hunter2@nodes", + "cluster://admin:hunter2@nodes:99999", "diskcache://user:hunter2@host/path", "redis://:hunter2@[::1/0", ], diff --git a/tests/shared_storage/test_local_cross_process.py b/tests/shared_storage/test_local_cross_process.py index 9f02e31cf1..fde2932e34 100644 --- a/tests/shared_storage/test_local_cross_process.py +++ b/tests/shared_storage/test_local_cross_process.py @@ -432,3 +432,52 @@ async def scenario(): asyncio.run(scenario()) assert client.get("k7") == 7 # landed in the owner, visible over the sync path client.close() + + +@pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="needs AF_UNIX") +def test_closing_owner_leaves_a_successors_files_alone(): + # Clients see the owner go before its final flush ends; one may have + # taken over by the time it cleans up. + from dash._shared_storage.local import _write_advertisement + + store = LocalSharedStorage(namespace=f"succ-{uuid.uuid4().hex[:8]}") + store.start() + coord = store._coord + assert coord.is_owner() + successor = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + os.unlink(coord._sock_path) + successor.bind(coord._sock_path) + _write_advertisement( + coord._addr_path, socket.AF_UNIX, coord._sock_path, "successor" + ) + store.close() + assert os.path.exists(coord._sock_path) + assert os.path.exists(coord._addr_path) + finally: + successor.close() + for path in (coord._sock_path, coord._addr_path): + if os.path.exists(path): + os.unlink(path) + + +def test_async_calls_keep_no_connection_per_finished_loop(): + # Under Flask every async callback runs on a new event loop. + import asyncio + + ns = f"loops-{uuid.uuid4().hex[:8]}" + owner = LocalSharedStorage(namespace=ns) + owner.start() + client = LocalSharedStorage(namespace=ns) + client.start() + try: + assert owner._coord.is_owner() and not client._coord.is_owner() + for i in range(3): + asyncio.run(owner.aset("k", i)) + asyncio.run(client.aset("k", i)) + assert client.get("k") == 2 + assert not owner._aconns + assert len(client._aconns) <= 1 + finally: + client.close() + owner.close()