deferd 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- deferd/__init__.py +40 -0
- deferd/__main__.py +8 -0
- deferd/admin.py +194 -0
- deferd/cli.py +177 -0
- deferd/clock.py +32 -0
- deferd/cluster/__init__.py +1 -0
- deferd/cluster/discovery/__init__.py +0 -0
- deferd/cluster/discovery/base.py +38 -0
- deferd/cluster/discovery/kubernetes.py +461 -0
- deferd/cluster/discovery/static.py +41 -0
- deferd/cluster/member.py +47 -0
- deferd/cluster/membership.py +512 -0
- deferd/cluster/network/__init__.py +0 -0
- deferd/cluster/network/base.py +58 -0
- deferd/cluster/network/tcp.py +460 -0
- deferd/cluster/network/wire.py +229 -0
- deferd/config.py +411 -0
- deferd/engine/__init__.py +1 -0
- deferd/engine/engine.py +452 -0
- deferd/engine/executor.py +117 -0
- deferd/engine/handlers.py +53 -0
- deferd/engine/timer.py +64 -0
- deferd/engine/watchdog.py +66 -0
- deferd/errors.py +41 -0
- deferd/jobs/__init__.py +7 -0
- deferd/jobs/durability.py +116 -0
- deferd/jobs/job.py +201 -0
- deferd/jobs/payload.py +53 -0
- deferd/jobs/retry.py +38 -0
- deferd/local.py +444 -0
- deferd/log.py +35 -0
- deferd/metrics.py +86 -0
- deferd/node.py +775 -0
- deferd/persistence.py +357 -0
- deferd/py.typed +0 -0
- deferd/replication/__init__.py +1 -0
- deferd/replication/backup.py +431 -0
- deferd/replication/handoff.py +172 -0
- deferd/replication/messages.py +151 -0
- deferd/replication/owner.py +663 -0
- deferd/replication/placement.py +70 -0
- deferd/replication/replication.py +447 -0
- deferd/scheduler.py +203 -0
- deferd/stores/__init__.py +1 -0
- deferd/stores/base.py +139 -0
- deferd/stores/elasticsearch/__init__.py +1 -0
- deferd/stores/elasticsearch/store.py +468 -0
- deferd/stores/memory.py +133 -0
- deferd/stores/mongo/__init__.py +1 -0
- deferd/stores/mongo/indexes.py +11 -0
- deferd/stores/mongo/store.py +335 -0
- deferd/stores/mysql/__init__.py +1 -0
- deferd/stores/mysql/migrations/.gitkeep +0 -0
- deferd/stores/mysql/migrations/0001_create_jobs.sql +28 -0
- deferd/stores/mysql/migrations/0002_create_apps.sql +11 -0
- deferd/stores/mysql/schema.sql +35 -0
- deferd/stores/mysql/store.py +437 -0
- deferd/stores/redis/__init__.py +1 -0
- deferd/stores/redis/keys.py +36 -0
- deferd/stores/redis/scripts/claim_app.lua +32 -0
- deferd/stores/redis/scripts/claim_owner.lua +63 -0
- deferd/stores/redis/scripts/delete_finished.lua +15 -0
- deferd/stores/redis/scripts/insert_if_absent.lua +35 -0
- deferd/stores/redis/scripts/update_if_version.lua +51 -0
- deferd/stores/redis/store.py +263 -0
- deferd/stores/registry.py +43 -0
- deferd/testing/__init__.py +6 -0
- deferd/testing/conformance/__init__.py +1 -0
- deferd/testing/conformance/discovery.py +116 -0
- deferd/testing/conformance/store.py +435 -0
- deferd/testing/conformance/transport.py +245 -0
- deferd/testing/fake_clock.py +101 -0
- deferd/testing/pytest_plugin.py +120 -0
- deferd/testing/sim/__init__.py +31 -0
- deferd/testing/sim/faults.py +149 -0
- deferd/testing/sim/harness.py +842 -0
- deferd/testing/sim/invariants.py +331 -0
- deferd/testing/sim/network.py +346 -0
- deferd-0.0.1.dist-info/METADATA +348 -0
- deferd-0.0.1.dist-info/RECORD +83 -0
- deferd-0.0.1.dist-info/WHEEL +4 -0
- deferd-0.0.1.dist-info/entry_points.txt +16 -0
- deferd-0.0.1.dist-info/licenses/LICENSE +21 -0
deferd/__init__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""deferd: delayed jobs across Kubernetes pods, with no broker or database.
|
|
2
|
+
|
|
3
|
+
Jobs live in memory on the pod that received them, with a backup copy on another pod
|
|
4
|
+
(preferably on another node). If a pod dies, the backup takes its jobs over.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from deferd.errors import (
|
|
8
|
+
CapacityExceeded,
|
|
9
|
+
ConfigurationError,
|
|
10
|
+
DeferdError,
|
|
11
|
+
DurabilityNotSatisfied,
|
|
12
|
+
PayloadNotSerializable,
|
|
13
|
+
PayloadTooLarge,
|
|
14
|
+
PermanentError,
|
|
15
|
+
SchedulerShuttingDown,
|
|
16
|
+
SchedulerUnavailable,
|
|
17
|
+
UnknownHandler,
|
|
18
|
+
)
|
|
19
|
+
from deferd.jobs import Backoff, Durability, JobContext, Persist
|
|
20
|
+
from deferd.scheduler import Scheduler
|
|
21
|
+
|
|
22
|
+
__version__ = "0.0.1"
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"Backoff",
|
|
26
|
+
"CapacityExceeded",
|
|
27
|
+
"ConfigurationError",
|
|
28
|
+
"DeferdError",
|
|
29
|
+
"Durability",
|
|
30
|
+
"DurabilityNotSatisfied",
|
|
31
|
+
"JobContext",
|
|
32
|
+
"PayloadNotSerializable",
|
|
33
|
+
"PayloadTooLarge",
|
|
34
|
+
"PermanentError",
|
|
35
|
+
"Persist",
|
|
36
|
+
"Scheduler",
|
|
37
|
+
"SchedulerShuttingDown",
|
|
38
|
+
"SchedulerUnavailable",
|
|
39
|
+
"UnknownHandler",
|
|
40
|
+
]
|
deferd/__main__.py
ADDED
deferd/admin.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""The admin HTTP server (default port 9090): /healthz, /readyz, /metrics, /debug/*.
|
|
2
|
+
|
|
3
|
+
It runs on its own thread with its own event loop, so it still answers when the scheduler's
|
|
4
|
+
loop is busy (CPU-heavy handlers, a burst of jobs):
|
|
5
|
+
|
|
6
|
+
- /healthz (liveness) is answered right on the admin thread by `health()`, which must be cheap
|
|
7
|
+
and thread-safe. It fails only when the scheduler's loop is stuck, not when it is slow.
|
|
8
|
+
When the probe was served by a busy loop it timed out, Kubernetes restarted the container,
|
|
9
|
+
and every running job ran again.
|
|
10
|
+
- Every other route calls its function on the scheduler's loop, with a timeout. A starved loop
|
|
11
|
+
fails /readyz with "busy", which sheds traffic without a restart.
|
|
12
|
+
|
|
13
|
+
/healthz must never depend on other pods, or an outage elsewhere restarts healthy pods.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
import threading
|
|
20
|
+
from collections.abc import Callable
|
|
21
|
+
|
|
22
|
+
log = logging.getLogger("deferd.admin")
|
|
23
|
+
|
|
24
|
+
REASONS = {
|
|
25
|
+
200: "OK",
|
|
26
|
+
400: "Bad Request",
|
|
27
|
+
404: "Not Found",
|
|
28
|
+
405: "Method Not Allowed",
|
|
29
|
+
500: "Internal Server Error",
|
|
30
|
+
503: "Service Unavailable",
|
|
31
|
+
}
|
|
32
|
+
READ_TIMEOUT = 5.0
|
|
33
|
+
BUSY = "busy: the scheduler's event loop is slow to respond"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def text(status: int, body: str) -> tuple[int, str, bytes]:
|
|
37
|
+
return status, "text/plain; charset=utf-8", (body + "\n").encode()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def as_json(status: int, obj) -> tuple[int, str, bytes]:
|
|
41
|
+
return status, "application/json", json.dumps(obj, default=str).encode()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class AdminServer:
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
host: str,
|
|
48
|
+
port: int,
|
|
49
|
+
health: Callable[[], bool],
|
|
50
|
+
ready: Callable[[], tuple[bool, str]],
|
|
51
|
+
metrics: Callable[[], bytes],
|
|
52
|
+
members: Callable[[], object],
|
|
53
|
+
jobs: Callable[[str | None], object],
|
|
54
|
+
timeout: float = 3.0,
|
|
55
|
+
) -> None:
|
|
56
|
+
"""`health` runs on the admin thread; the others on the scheduler's loop."""
|
|
57
|
+
self.host = host
|
|
58
|
+
self.requested_port = port
|
|
59
|
+
self.health = health
|
|
60
|
+
self.ready = ready
|
|
61
|
+
self.metrics = metrics
|
|
62
|
+
self.members = members
|
|
63
|
+
self.jobs = jobs
|
|
64
|
+
self.timeout = timeout
|
|
65
|
+
self.main_loop: asyncio.AbstractEventLoop | None = None
|
|
66
|
+
self.loop: asyncio.AbstractEventLoop | None = None
|
|
67
|
+
self.thread: threading.Thread | None = None
|
|
68
|
+
self.server: asyncio.Server | None = None
|
|
69
|
+
self.error: BaseException | None = None
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def port(self) -> int:
|
|
73
|
+
"""The port actually bound (when started with port 0)."""
|
|
74
|
+
if self.server is not None and self.server.sockets:
|
|
75
|
+
return int(self.server.sockets[0].getsockname()[1])
|
|
76
|
+
return self.requested_port
|
|
77
|
+
|
|
78
|
+
async def start(self) -> None:
|
|
79
|
+
"""Bind and serve on a new thread. Raises what binding raised (e.g. port in use)."""
|
|
80
|
+
if self.thread is not None:
|
|
81
|
+
return
|
|
82
|
+
self.main_loop = asyncio.get_running_loop()
|
|
83
|
+
self.error = None
|
|
84
|
+
bound = threading.Event()
|
|
85
|
+
self.thread = threading.Thread(
|
|
86
|
+
target=self._run, args=(bound,), name="deferd-admin", daemon=True
|
|
87
|
+
)
|
|
88
|
+
self.thread.start()
|
|
89
|
+
await asyncio.to_thread(bound.wait)
|
|
90
|
+
if self.error is not None:
|
|
91
|
+
self.thread.join()
|
|
92
|
+
self.thread = None
|
|
93
|
+
raise self.error
|
|
94
|
+
|
|
95
|
+
async def stop(self) -> None:
|
|
96
|
+
loop, thread = self.loop, self.thread
|
|
97
|
+
if loop is None or thread is None:
|
|
98
|
+
return
|
|
99
|
+
loop.call_soon_threadsafe(loop.stop)
|
|
100
|
+
await asyncio.to_thread(thread.join, 10)
|
|
101
|
+
self.loop = self.thread = self.server = None
|
|
102
|
+
|
|
103
|
+
# On the admin thread
|
|
104
|
+
|
|
105
|
+
def _run(self, bound: threading.Event) -> None:
|
|
106
|
+
loop = asyncio.new_event_loop()
|
|
107
|
+
try:
|
|
108
|
+
try:
|
|
109
|
+
server = loop.run_until_complete(
|
|
110
|
+
asyncio.start_server(self._handle, self.host, self.requested_port)
|
|
111
|
+
)
|
|
112
|
+
except BaseException as e: # start() raises it on the caller's loop
|
|
113
|
+
self.error = e
|
|
114
|
+
return
|
|
115
|
+
self.server = server
|
|
116
|
+
self.loop = loop
|
|
117
|
+
bound.set()
|
|
118
|
+
loop.run_forever()
|
|
119
|
+
server.close()
|
|
120
|
+
loop.run_until_complete(server.wait_closed())
|
|
121
|
+
finally:
|
|
122
|
+
bound.set()
|
|
123
|
+
loop.close()
|
|
124
|
+
|
|
125
|
+
async def _on_main(self, fn, *args):
|
|
126
|
+
"""Call fn(*args) on the scheduler's loop. TimeoutError if it doesn't get to it."""
|
|
127
|
+
assert self.main_loop is not None
|
|
128
|
+
|
|
129
|
+
async def call():
|
|
130
|
+
return fn(*args)
|
|
131
|
+
|
|
132
|
+
future = asyncio.run_coroutine_threadsafe(call(), self.main_loop)
|
|
133
|
+
try:
|
|
134
|
+
return await asyncio.wait_for(asyncio.wrap_future(future), self.timeout)
|
|
135
|
+
except TimeoutError:
|
|
136
|
+
future.cancel()
|
|
137
|
+
raise
|
|
138
|
+
|
|
139
|
+
async def _route(self, method: str, path: str) -> tuple[int, str, bytes]:
|
|
140
|
+
if method != "GET":
|
|
141
|
+
return text(405, "method not allowed")
|
|
142
|
+
path = path.split("?", 1)[0]
|
|
143
|
+
try:
|
|
144
|
+
if path == "/healthz":
|
|
145
|
+
return text(200, "ok") if self.health() else text(503, "unhealthy")
|
|
146
|
+
if path == "/readyz":
|
|
147
|
+
ok, reason = await self._on_main(self.ready)
|
|
148
|
+
return text(200 if ok else 503, reason)
|
|
149
|
+
if path == "/metrics":
|
|
150
|
+
return (
|
|
151
|
+
200,
|
|
152
|
+
"text/plain; version=0.0.4; charset=utf-8",
|
|
153
|
+
await self._on_main(self.metrics),
|
|
154
|
+
)
|
|
155
|
+
if path == "/debug/members":
|
|
156
|
+
return as_json(200, await self._on_main(self.members))
|
|
157
|
+
if path in ("/debug/jobs", "/debug/jobs/"):
|
|
158
|
+
return as_json(200, await self._on_main(self.jobs, None))
|
|
159
|
+
if path.startswith("/debug/jobs/"):
|
|
160
|
+
result = await self._on_main(self.jobs, path[len("/debug/jobs/") :])
|
|
161
|
+
return text(404, "no such job") if result is None else as_json(200, result)
|
|
162
|
+
except TimeoutError:
|
|
163
|
+
return text(503, BUSY)
|
|
164
|
+
except Exception:
|
|
165
|
+
log.exception("admin endpoint %s failed", path)
|
|
166
|
+
return text(500, "internal error")
|
|
167
|
+
return text(404, "not found")
|
|
168
|
+
|
|
169
|
+
async def _handle(self, reader, writer) -> None:
|
|
170
|
+
try:
|
|
171
|
+
try:
|
|
172
|
+
raw = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), READ_TIMEOUT)
|
|
173
|
+
except (TimeoutError, asyncio.IncompleteReadError, asyncio.LimitOverrunError):
|
|
174
|
+
return
|
|
175
|
+
parts = raw.split(b"\r\n", 1)[0].decode("latin-1").split(" ")
|
|
176
|
+
if len(parts) == 3:
|
|
177
|
+
status, content_type, body = await self._route(parts[0], parts[1])
|
|
178
|
+
else:
|
|
179
|
+
status, content_type, body = text(400, "bad request")
|
|
180
|
+
head = (
|
|
181
|
+
f"HTTP/1.1 {status} {REASONS.get(status, 'Unknown')}\r\n"
|
|
182
|
+
f"Content-Type: {content_type}\r\nContent-Length: {len(body)}\r\n"
|
|
183
|
+
"Connection: close\r\n\r\n"
|
|
184
|
+
)
|
|
185
|
+
writer.write(head.encode() + body)
|
|
186
|
+
await writer.drain()
|
|
187
|
+
except OSError:
|
|
188
|
+
pass
|
|
189
|
+
finally:
|
|
190
|
+
writer.close()
|
|
191
|
+
try:
|
|
192
|
+
await writer.wait_closed()
|
|
193
|
+
except OSError:
|
|
194
|
+
pass
|
deferd/cli.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""The command line.
|
|
2
|
+
|
|
3
|
+
deferd run app.module:scheduler the dedicated scheduler process; runs until
|
|
4
|
+
SIGTERM/SIGINT, then leaves gracefully
|
|
5
|
+
deferd inspect members a running pod's view of the cluster
|
|
6
|
+
deferd inspect job <id> where a job is and what state it's in
|
|
7
|
+
deferd migrate --store URL create or update the store's schema
|
|
8
|
+
deferd check --store URL the store's health and guarantees; exit 1 if not good
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import asyncio
|
|
13
|
+
import importlib
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
import urllib.error
|
|
18
|
+
import urllib.request
|
|
19
|
+
from typing import Any, TextIO
|
|
20
|
+
|
|
21
|
+
from deferd.errors import ConfigurationError
|
|
22
|
+
from deferd.stores.base import Safety
|
|
23
|
+
from deferd.stores.registry import resolve_store
|
|
24
|
+
|
|
25
|
+
DEFAULT_ADMIN_URL = "http://127.0.0.1:9090"
|
|
26
|
+
ENV_ADMIN_URL = "DEFERD_ADMIN_URL"
|
|
27
|
+
_HTTP_TIMEOUT = 5.0
|
|
28
|
+
|
|
29
|
+
EXIT_OK = 0
|
|
30
|
+
EXIT_ERROR = 1
|
|
31
|
+
EXIT_USAGE = 2
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
35
|
+
parser = argparse.ArgumentParser(prog="deferd", description="Delayed jobs, no broker.")
|
|
36
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
37
|
+
|
|
38
|
+
run = sub.add_parser("run", help="run a dedicated scheduler process")
|
|
39
|
+
run.add_argument("target", help="module:attribute, e.g. myapp.jobs:scheduler")
|
|
40
|
+
|
|
41
|
+
migrate = sub.add_parser("migrate", help="create or update the store's schema")
|
|
42
|
+
migrate.add_argument("--store", required=True)
|
|
43
|
+
|
|
44
|
+
check = sub.add_parser("check", help="report the store's health and guarantees")
|
|
45
|
+
check.add_argument("--store", required=True)
|
|
46
|
+
|
|
47
|
+
inspect = sub.add_parser("inspect", help="inspect a running member")
|
|
48
|
+
inspect.add_argument("what", choices=["members", "job"])
|
|
49
|
+
inspect.add_argument("job_id", nargs="?")
|
|
50
|
+
inspect.add_argument(
|
|
51
|
+
"--admin",
|
|
52
|
+
default=None,
|
|
53
|
+
help=f"admin endpoint base URL (default: ${ENV_ADMIN_URL} or {DEFAULT_ADMIN_URL})",
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
return parser
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def main(argv: list[str] | None = None) -> int:
|
|
60
|
+
parser = build_parser()
|
|
61
|
+
args = parser.parse_args(argv)
|
|
62
|
+
command: str = args.command
|
|
63
|
+
if command == "run":
|
|
64
|
+
return _run(args.target)
|
|
65
|
+
if command == "inspect":
|
|
66
|
+
if args.what == "job" and not args.job_id:
|
|
67
|
+
parser.error("inspect job needs a job id")
|
|
68
|
+
base = args.admin or os.environ.get(ENV_ADMIN_URL) or DEFAULT_ADMIN_URL
|
|
69
|
+
path = "/debug/members" if args.what == "members" else f"/debug/jobs/{args.job_id}"
|
|
70
|
+
return inspect_endpoint(base, path)
|
|
71
|
+
work = migrate_store if command == "migrate" else check_store
|
|
72
|
+
try:
|
|
73
|
+
return asyncio.run(work(args.store))
|
|
74
|
+
except ConfigurationError as e:
|
|
75
|
+
print(f"deferd {command}: {e}", file=sys.stderr)
|
|
76
|
+
return EXIT_USAGE
|
|
77
|
+
except Exception as e:
|
|
78
|
+
print(f"deferd {command}: {type(e).__name__}: {e}", file=sys.stderr)
|
|
79
|
+
return EXIT_ERROR
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# deferd migrate, deferd check
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
async def migrate_store(url: str) -> int:
|
|
86
|
+
store = resolve_store(url)
|
|
87
|
+
# no connect() first: a store may refuse to connect until it is migrated
|
|
88
|
+
await store.migrate()
|
|
89
|
+
print(f"migrated the {url.split('://', 1)[0]} store")
|
|
90
|
+
return EXIT_OK
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
async def check_store(url: str) -> int:
|
|
94
|
+
store = resolve_store(url)
|
|
95
|
+
await store.connect()
|
|
96
|
+
try:
|
|
97
|
+
health = await store.health()
|
|
98
|
+
finally:
|
|
99
|
+
await store.close()
|
|
100
|
+
guarantees = store.guarantees()
|
|
101
|
+
print(f"health: {'ok' if health.ok else 'DOWN'} {health.detail}".rstrip())
|
|
102
|
+
print(f"safety: {guarantees.safety}")
|
|
103
|
+
print(f"survives a store crash: {'yes' if guarantees.survives_store_crash else 'no'}")
|
|
104
|
+
for note in guarantees.notes:
|
|
105
|
+
print(f"note: {note}")
|
|
106
|
+
return EXIT_OK if health.ok and guarantees.safety is not Safety.UNSAFE else EXIT_ERROR
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# deferd run
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def load_target(target: str) -> Any:
|
|
113
|
+
"""Import "module:attribute" (dotted attributes allowed). The working directory is on the
|
|
114
|
+
import path, as with `python -m`."""
|
|
115
|
+
module_name, sep, attr = target.partition(":")
|
|
116
|
+
if not sep or not module_name or not attr:
|
|
117
|
+
raise ConfigurationError(f"target must look like module:attribute, got {target!r}")
|
|
118
|
+
cwd = os.getcwd()
|
|
119
|
+
if cwd not in sys.path:
|
|
120
|
+
sys.path.insert(0, cwd)
|
|
121
|
+
try:
|
|
122
|
+
obj: Any = importlib.import_module(module_name)
|
|
123
|
+
except ImportError as e:
|
|
124
|
+
raise ConfigurationError(f"cannot import {module_name!r}: {e}") from e
|
|
125
|
+
for part in attr.split("."):
|
|
126
|
+
try:
|
|
127
|
+
obj = getattr(obj, part)
|
|
128
|
+
except AttributeError as e:
|
|
129
|
+
raise ConfigurationError(f"{module_name!r} has no attribute {attr!r}") from e
|
|
130
|
+
return obj
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _run(target: str) -> int:
|
|
134
|
+
from deferd.log import configure_logging
|
|
135
|
+
from deferd.scheduler import Scheduler
|
|
136
|
+
|
|
137
|
+
try:
|
|
138
|
+
scheduler = load_target(target)
|
|
139
|
+
if not isinstance(scheduler, Scheduler):
|
|
140
|
+
raise ConfigurationError(
|
|
141
|
+
f"{target} is a {type(scheduler).__name__}, not a deferd.Scheduler"
|
|
142
|
+
)
|
|
143
|
+
settings = scheduler.settings
|
|
144
|
+
configure_logging(settings.log_level.upper(), as_json=settings.log_json)
|
|
145
|
+
asyncio.run(scheduler.serve())
|
|
146
|
+
except ConfigurationError as e:
|
|
147
|
+
print(f"deferd run: configuration error: {e}", file=sys.stderr)
|
|
148
|
+
return EXIT_USAGE
|
|
149
|
+
except KeyboardInterrupt:
|
|
150
|
+
return EXIT_OK
|
|
151
|
+
return EXIT_OK
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# deferd inspect
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def inspect_endpoint(base: str, path: str, out: TextIO | None = None) -> int:
|
|
158
|
+
"""GET base + path and print the JSON body, indented."""
|
|
159
|
+
stream = out if out is not None else sys.stdout
|
|
160
|
+
url = base.rstrip("/") + path
|
|
161
|
+
try:
|
|
162
|
+
with urllib.request.urlopen(url, timeout=_HTTP_TIMEOUT) as response:
|
|
163
|
+
body = response.read()
|
|
164
|
+
except urllib.error.HTTPError as e:
|
|
165
|
+
detail = e.read().decode(errors="replace").strip()
|
|
166
|
+
print(f"deferd inspect: {url}: HTTP {e.code} {detail}", file=sys.stderr)
|
|
167
|
+
return EXIT_ERROR
|
|
168
|
+
except (urllib.error.URLError, OSError) as e:
|
|
169
|
+
print(f"deferd inspect: cannot reach {url}: {e}", file=sys.stderr)
|
|
170
|
+
return EXIT_ERROR
|
|
171
|
+
try:
|
|
172
|
+
parsed = json.loads(body)
|
|
173
|
+
except ValueError:
|
|
174
|
+
stream.write(body.decode(errors="replace"))
|
|
175
|
+
return EXIT_OK
|
|
176
|
+
stream.write(json.dumps(parsed, indent=2, sort_keys=True) + "\n")
|
|
177
|
+
return EXIT_OK
|
deferd/clock.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Time. Everything in deferd asks a Clock for the time instead of calling datetime.now(), so
|
|
2
|
+
tests can swap in deferd.testing.FakeClock and move time forward by hand."""
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import time
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Clock:
|
|
10
|
+
def now(self) -> datetime:
|
|
11
|
+
"""Wall-clock time in UTC. Used for due times, which must mean the same on every pod."""
|
|
12
|
+
return datetime.now(UTC)
|
|
13
|
+
|
|
14
|
+
def monotonic(self) -> float:
|
|
15
|
+
"""Seconds that never jump backwards. Used for measuring durations."""
|
|
16
|
+
return time.monotonic()
|
|
17
|
+
|
|
18
|
+
async def sleep_until(self, t: datetime) -> None:
|
|
19
|
+
"""Wait until t. Callers should check now() again afterwards."""
|
|
20
|
+
await asyncio.sleep(max((t - self.now()).total_seconds(), 0.0))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def sleep_or_wake(clock: Clock, until: datetime, wake: asyncio.Event) -> None:
|
|
24
|
+
"""Sleep until `until`, or until `wake` is set, whichever comes first."""
|
|
25
|
+
sleeper = asyncio.ensure_future(clock.sleep_until(until))
|
|
26
|
+
waker = asyncio.ensure_future(wake.wait())
|
|
27
|
+
try:
|
|
28
|
+
await asyncio.wait({sleeper, waker}, return_when=asyncio.FIRST_COMPLETED)
|
|
29
|
+
finally:
|
|
30
|
+
sleeper.cancel()
|
|
31
|
+
waker.cancel()
|
|
32
|
+
await asyncio.gather(sleeper, waker, return_exceptions=True)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Pods finding each other, talking, and watching each other: membership, discovery, network."""
|
|
File without changes
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""How a pod finds the other pods.
|
|
2
|
+
|
|
3
|
+
A discovery gives the full list of peers every time something changes (never a delta, so a
|
|
4
|
+
missed update is fixed by the next one). The list may include this pod itself.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from collections.abc import AsyncIterator
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True, slots=True)
|
|
12
|
+
class Peer:
|
|
13
|
+
member_id: str
|
|
14
|
+
address: str
|
|
15
|
+
node: str | None = None
|
|
16
|
+
zone: str | None = None
|
|
17
|
+
leaving: bool = False # e.g. a pod with deletionTimestamp set
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Discovery:
|
|
21
|
+
async def self_info(self) -> Peer:
|
|
22
|
+
"""This pod's own entry."""
|
|
23
|
+
raise NotImplementedError
|
|
24
|
+
|
|
25
|
+
async def fingerprint(self) -> str | None:
|
|
26
|
+
"""What tells this application from another one, or None if nothing reliable does.
|
|
27
|
+
|
|
28
|
+
Used to stop two applications from sharing an app_name in one store.
|
|
29
|
+
"""
|
|
30
|
+
return None
|
|
31
|
+
|
|
32
|
+
async def description(self) -> str:
|
|
33
|
+
"""The application in words, for the message when two of them share an app_name."""
|
|
34
|
+
return ""
|
|
35
|
+
|
|
36
|
+
def watch(self) -> AsyncIterator[list[Peer]]:
|
|
37
|
+
"""Yield the full peer list on every change. Recover from errors; never end."""
|
|
38
|
+
raise NotImplementedError
|