queue-chaos 1.1.0__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.
- chaos.py +772 -0
- qadvice.py +54 -0
- qcheck.py +249 -0
- queue_chaos-1.1.0.dist-info/METADATA +251 -0
- queue_chaos-1.1.0.dist-info/RECORD +17 -0
- queue_chaos-1.1.0.dist-info/WHEEL +5 -0
- queue_chaos-1.1.0.dist-info/entry_points.txt +2 -0
- queue_chaos-1.1.0.dist-info/licenses/LICENSE-APACHE +190 -0
- queue_chaos-1.1.0.dist-info/licenses/LICENSE-MIT +21 -0
- queue_chaos-1.1.0.dist-info/top_level.txt +4 -0
- queue_chaos_presets/__init__.py +0 -0
- queue_chaos_presets/_common.py +33 -0
- queue_chaos_presets/celery/adapter +7 -0
- queue_chaos_presets/celery/adapter.py +64 -0
- queue_chaos_presets/rq/adapter +5 -0
- queue_chaos_presets/rq/adapter.py +75 -0
- queue_chaos_presets/rq/chaosjob.py +18 -0
chaos.py
ADDED
|
@@ -0,0 +1,772 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""queue-chaos: fault-injection checker for background job queues.
|
|
3
|
+
|
|
4
|
+
Runs worker processes of a queue adapter, injects faults (worker crash, worker
|
|
5
|
+
pause, graceful shutdown/cancellation, broker restart), and checks every job's execution history:
|
|
6
|
+
|
|
7
|
+
lost job never completed
|
|
8
|
+
dup_complete job completed more than once
|
|
9
|
+
concurrent two executions of the same job overlapped in time while both
|
|
10
|
+
workers were alive and responsive (implementation bug)
|
|
11
|
+
lease_overlap overlap caused by the first worker being paused longer than the
|
|
12
|
+
lease/stuck timeout; inherent to lease-based queues, reported
|
|
13
|
+
separately so it is never counted as a bug
|
|
14
|
+
redelivered job restarted after its worker was killed (expected under
|
|
15
|
+
at-least-once; reported, not a failure)
|
|
16
|
+
dup_unexplained subset of dup_complete where nothing happened to the earlier
|
|
17
|
+
execution's worker (kill/exit/pause) and no broker restart
|
|
18
|
+
occurred between its END and the next START -> investigate
|
|
19
|
+
|
|
20
|
+
Standard library only. See README.md for the adapter protocol.
|
|
21
|
+
"""
|
|
22
|
+
import socket, argparse, json, os, random, re, signal, subprocess, sys, threading, time
|
|
23
|
+
from collections import defaultdict
|
|
24
|
+
|
|
25
|
+
BACKENDS = {
|
|
26
|
+
"redis": dict(image="redis:7.2", port=6390, inner=6379, env={},
|
|
27
|
+
url="redis://127.0.0.1:6390"),
|
|
28
|
+
"postgres": dict(image="postgres:16", port=5440, inner=5432,
|
|
29
|
+
env={"POSTGRES_PASSWORD": "chaos", "POSTGRES_DB": "chaos"},
|
|
30
|
+
url="postgres://postgres:chaos@127.0.0.1:5440/chaos"),
|
|
31
|
+
"mongo": dict(image="mongo:7.0", port=27440, inner=27017, env={},
|
|
32
|
+
url="mongodb://127.0.0.1:27440/chaos",
|
|
33
|
+
probe=["mongosh", "--quiet", "--eval", "db.runCommand({ping: 1}).ok"]),
|
|
34
|
+
# Faktory is itself the job server (no client tools in the image): readiness = TCP connect from the host
|
|
35
|
+
"faktory": dict(image="contribsys/faktory:1.10.0", port=7440, inner=7419, env={},
|
|
36
|
+
url="tcp://127.0.0.1:7440", probe=None),
|
|
37
|
+
# RabbitMQ (AMQP). Slow to boot, so it gets a longer readiness wait.
|
|
38
|
+
"rabbitmq": dict(image="rabbitmq:3.13", port=5690, inner=5672, env={},
|
|
39
|
+
url="amqp://guest:guest@127.0.0.1:5690//",
|
|
40
|
+
probe="amqp", tries=240),
|
|
41
|
+
}
|
|
42
|
+
CHECKER_VERSION = "0.6"
|
|
43
|
+
LATE_MS = 30_000 # a job whose first START comes this long after the last fault ended counts as a late start # bump whenever classification logic changes; report.py never pools versions
|
|
44
|
+
now_ms = lambda: int(time.time() * 1000)
|
|
45
|
+
|
|
46
|
+
# Network partitions go through Toxiproxy: workers -> proxy -> broker; the producer talks to the broker directly.
|
|
47
|
+
TOXIPROXY_IMAGE = "ghcr.io/shopify/toxiproxy:2.9.0"
|
|
48
|
+
TOXI_API = "http://127.0.0.1:8475"
|
|
49
|
+
PROXY_PORT = {"redis": 6395, "postgres": 5445, "mongo": 27445, "faktory": 7445, "rabbitmq": 5695}
|
|
50
|
+
NET = "queue-chaos-net"
|
|
51
|
+
# Process groups of every worker ever spawned. A crashed run must never leave workers behind:
|
|
52
|
+
# orphans keep consuming jobs from later runs on the same ports and silently corrupt results.
|
|
53
|
+
# Parallel instances (QC_INSTANCE=N, default 0 = the original names/ports): every port +100*N, every docker name and
|
|
54
|
+
# the worker pidfile get an "-iN" suffix, so N harness copies never share a container, port, proxy or worker.
|
|
55
|
+
INSTANCE = int(os.environ.get("QC_INSTANCE", "0"))
|
|
56
|
+
_OFF, SUFFIX = 100 * INSTANCE, (f"-i{INSTANCE}" if INSTANCE else "")
|
|
57
|
+
for _b in BACKENDS.values():
|
|
58
|
+
_b["url"] = _b["url"].replace(f":{_b['port']}", f":{_b['port'] + _OFF}")
|
|
59
|
+
_b["port"] += _OFF
|
|
60
|
+
TOXI_API = f"http://127.0.0.1:{8475 + _OFF}"
|
|
61
|
+
PROXY_PORT = {k: v + _OFF for k, v in PROXY_PORT.items()}
|
|
62
|
+
NET = "queue-chaos-net" + SUFFIX
|
|
63
|
+
TOXI_NAME = "queue-chaos-toxiproxy" + SUFFIX
|
|
64
|
+
PIDFILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), f".chaos-workers{SUFFIX}.pids")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def kill_leftover_workers():
|
|
68
|
+
try:
|
|
69
|
+
pids = [int(x) for x in open(PIDFILE).read().split()]
|
|
70
|
+
except (OSError, ValueError):
|
|
71
|
+
pids = []
|
|
72
|
+
for pid in pids:
|
|
73
|
+
try:
|
|
74
|
+
os.killpg(pid, signal.SIGCONT); os.killpg(pid, signal.SIGKILL)
|
|
75
|
+
except (ProcessLookupError, PermissionError):
|
|
76
|
+
pass
|
|
77
|
+
open(PIDFILE, "w").close()
|
|
78
|
+
return len(pids)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def toxi(method, path, body=None):
|
|
82
|
+
import urllib.request
|
|
83
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
84
|
+
req = urllib.request.Request(TOXI_API + path, data=data, method=method,
|
|
85
|
+
headers={"Content-Type": "application/json"})
|
|
86
|
+
with urllib.request.urlopen(req, timeout=5) as resp:
|
|
87
|
+
return resp.read()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def sh(*cmd, check=True):
|
|
91
|
+
return subprocess.run(cmd, check=check, capture_output=True, text=True)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
DISK_MB = 0 # --disk-mb: postgres data dir on a size-limited tmpfs (0 = off)
|
|
95
|
+
SKEW = False # --skew: broker runs from a libfaketime image (docker/faketime/) so its clock can be shifted
|
|
96
|
+
FAKETIME_IMAGE = {"redis": "qc-redis-faketime:7", "postgres": "qc-postgres-faketime:16"}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def start_backend(name, proxied=False):
|
|
100
|
+
"""Start the broker. With proxied=True also start Toxiproxy in front of it; returns
|
|
101
|
+
(container, direct_url, worker_url)."""
|
|
102
|
+
b = BACKENDS[name]
|
|
103
|
+
cname = f"queue-chaos-{name}{SUFFIX}"
|
|
104
|
+
sh("docker", "rm", "-f", cname, TOXI_NAME, check=False)
|
|
105
|
+
envs = sum([["-e", f"{k}={v}"] for k, v in b["env"].items()], [])
|
|
106
|
+
net = []
|
|
107
|
+
if proxied:
|
|
108
|
+
sh("docker", "network", "rm", NET, check=False)
|
|
109
|
+
sh("docker", "network", "create", NET)
|
|
110
|
+
net = ["--network", NET]
|
|
111
|
+
disk = ["--tmpfs", f"/var/lib/postgresql/data:rw,size={DISK_MB}m"] if (DISK_MB > 0 and name == "postgres") else []
|
|
112
|
+
image = b["image"]
|
|
113
|
+
if SKEW:
|
|
114
|
+
if name not in FAKETIME_IMAGE:
|
|
115
|
+
raise SystemExit("--skew supports only redis and postgres")
|
|
116
|
+
image = FAKETIME_IMAGE[name]
|
|
117
|
+
sh("docker", "run", "-d", "--name", cname, *net, *disk, "-p", f"{b['port']}:{b['inner']}", *envs, image)
|
|
118
|
+
if SKEW: # file did not exist at process start; libfaketime re-reads it on every call (FAKETIME_NO_CACHE=1)
|
|
119
|
+
sh("docker", "exec", "-u", "0", cname, "sh", "-c", "echo '+0' > /qc/faketime")
|
|
120
|
+
probe = b.get("probe", ["redis-cli", "ping"] if name == "redis" else ["pg_isready", "-U", "postgres"])
|
|
121
|
+
|
|
122
|
+
def ready():
|
|
123
|
+
if probe == "amqp":
|
|
124
|
+
# AMQP protocol header; a booted broker answers with connection.start. (Running rabbitmq-diagnostics
|
|
125
|
+
# in the container while it boots can crash it, so no docker exec here.)
|
|
126
|
+
try:
|
|
127
|
+
with socket.create_connection(("127.0.0.1", b["port"]), timeout=2) as c:
|
|
128
|
+
c.sendall(b"AMQP\x00\x00\x09\x01")
|
|
129
|
+
return c.recv(1) == b"\x01"
|
|
130
|
+
except OSError:
|
|
131
|
+
return False
|
|
132
|
+
if probe is None: # host TCP connect
|
|
133
|
+
try:
|
|
134
|
+
socket.create_connection(("127.0.0.1", b["port"]), timeout=1).close()
|
|
135
|
+
return True
|
|
136
|
+
except OSError:
|
|
137
|
+
return False
|
|
138
|
+
return sh("docker", "exec", cname, *probe, check=False).returncode == 0
|
|
139
|
+
for _ in range(b.get("tries", 60)):
|
|
140
|
+
if ready():
|
|
141
|
+
time.sleep(1 if name == "redis" else 2)
|
|
142
|
+
if not proxied:
|
|
143
|
+
return cname, b["url"], b["url"]
|
|
144
|
+
pp = PROXY_PORT[name]
|
|
145
|
+
sh("docker", "run", "-d", "--name", TOXI_NAME, "--network", NET,
|
|
146
|
+
"-p", f"{8475 + _OFF}:8474", "-p", f"{pp}:{pp}", TOXIPROXY_IMAGE)
|
|
147
|
+
for _ in range(40):
|
|
148
|
+
try:
|
|
149
|
+
toxi("POST", "/proxies", {"name": "broker", "listen": f"0.0.0.0:{pp}",
|
|
150
|
+
"upstream": f"{cname}:{b['inner']}"})
|
|
151
|
+
break
|
|
152
|
+
except Exception:
|
|
153
|
+
time.sleep(0.5)
|
|
154
|
+
else:
|
|
155
|
+
sys.exit("toxiproxy did not become ready")
|
|
156
|
+
return cname, b["url"], b["url"].replace(f":{b['port']}", f":{pp}")
|
|
157
|
+
time.sleep(0.5)
|
|
158
|
+
sys.exit(f"{name} did not become ready")
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def sig(p, signum):
|
|
162
|
+
"""Signal the worker's whole process group."""
|
|
163
|
+
try:
|
|
164
|
+
os.killpg(p.pid, signum)
|
|
165
|
+
except (ProcessLookupError, PermissionError, AttributeError, TypeError):
|
|
166
|
+
pass
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class _Exited:
|
|
170
|
+
"""Placeholder for a worker that exited and is not restarted."""
|
|
171
|
+
returncode = 0
|
|
172
|
+
def poll(self): return None # already recorded
|
|
173
|
+
def send_signal(self, _): pass
|
|
174
|
+
def kill(self): pass
|
|
175
|
+
def wait(self): pass
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class Run:
|
|
179
|
+
def __init__(self, a, url, producer_url=None):
|
|
180
|
+
self.a, self.url = a, url
|
|
181
|
+
self.events, self.lock = [], threading.Lock()
|
|
182
|
+
self.broker_lock = threading.Lock() # producer never enqueues during a broker restart
|
|
183
|
+
self.enqueued = a.jobs
|
|
184
|
+
self.producing = False
|
|
185
|
+
self.faults_injected = 0
|
|
186
|
+
self.all_pids = []
|
|
187
|
+
self.paused = set()
|
|
188
|
+
self.phase_wait, self.phase_hit = None, None # --phase: armed trigger and the slot it hit
|
|
189
|
+
self.procs = {} # slot -> (wid, Popen)
|
|
190
|
+
self.exits = [] # (wid, returncode, ms, stderr tail) for workers that exited on their own
|
|
191
|
+
self.incarnation = defaultdict(int)
|
|
192
|
+
self.env = dict(os.environ, CHAOS_BACKEND=a.backend, CHAOS_URL=url,
|
|
193
|
+
CHAOS_STUCK_MS=str(a.stuck_ms), CHAOS_CONCURRENCY=str(a.concurrency),
|
|
194
|
+
CHAOS_GRACE_MS=str(int(a.grace_s * 1000)))
|
|
195
|
+
# the producer bypasses the proxy, so partitions only cut off consumers
|
|
196
|
+
self.penv = dict(self.env, CHAOS_URL=producer_url or url)
|
|
197
|
+
self.partitioned = False
|
|
198
|
+
|
|
199
|
+
def log(self, *ev):
|
|
200
|
+
with self.lock:
|
|
201
|
+
self.events.append(ev)
|
|
202
|
+
|
|
203
|
+
def spawn(self, slot):
|
|
204
|
+
self.incarnation[slot] += 1
|
|
205
|
+
wid = f"w{slot}.{self.incarnation[slot]}"
|
|
206
|
+
os.makedirs(self.a.out, exist_ok=True)
|
|
207
|
+
err = open(f"{self.a.out}/worker-{wid}.stderr", "w")
|
|
208
|
+
# own process group: faults hit the worker and any children (prefork pools),
|
|
209
|
+
# like a container kill would
|
|
210
|
+
p = subprocess.Popen([self.a.adapter, "work", wid], stdout=subprocess.PIPE,
|
|
211
|
+
stderr=err, text=True, env=self.env, start_new_session=True)
|
|
212
|
+
self.procs[slot] = (wid, p)
|
|
213
|
+
self.all_pids.append(p.pid)
|
|
214
|
+
with open(PIDFILE, "a") as f:
|
|
215
|
+
f.write(f"{p.pid}\n")
|
|
216
|
+
threading.Thread(target=self.read, args=(p,), daemon=True).start()
|
|
217
|
+
|
|
218
|
+
def kill_all(self):
|
|
219
|
+
"""Kill every worker this run ever spawned (idempotent; also used on crash)."""
|
|
220
|
+
for pid in self.all_pids:
|
|
221
|
+
try:
|
|
222
|
+
os.killpg(pid, signal.SIGCONT); os.killpg(pid, signal.SIGKILL)
|
|
223
|
+
except (ProcessLookupError, PermissionError):
|
|
224
|
+
pass
|
|
225
|
+
if not getattr(self, "end_ms", None):
|
|
226
|
+
self.end_ms = now_ms()
|
|
227
|
+
open(PIDFILE, "w").close()
|
|
228
|
+
|
|
229
|
+
def read(self, p):
|
|
230
|
+
for line in p.stdout:
|
|
231
|
+
parts = line.split()
|
|
232
|
+
if len(parts) == 4 and parts[0] in ("START", "END", "CANCEL"):
|
|
233
|
+
self.log(parts[0], int(parts[1]), parts[2], int(parts[3]))
|
|
234
|
+
if self.phase_wait is not None and parts[0] == self.a.phase.upper():
|
|
235
|
+
self.phase_trigger(parts[2])
|
|
236
|
+
|
|
237
|
+
def phase_trigger(self, wid):
|
|
238
|
+
# --phase: the first matching START/END from a running, unpaused worker fires the armed fault on it
|
|
239
|
+
with self.lock:
|
|
240
|
+
ev = self.phase_wait
|
|
241
|
+
if ev is None or ev.is_set():
|
|
242
|
+
return
|
|
243
|
+
for slot, (w, _) in self.procs.items():
|
|
244
|
+
if w == wid and slot not in self.paused:
|
|
245
|
+
self.phase_hit = slot
|
|
246
|
+
ev.set()
|
|
247
|
+
return
|
|
248
|
+
|
|
249
|
+
def wait_phase(self):
|
|
250
|
+
"""Arm a phase trigger and wait for it; returns the worker slot that hit it, or None on timeout."""
|
|
251
|
+
ev = threading.Event()
|
|
252
|
+
with self.lock:
|
|
253
|
+
self.phase_wait, self.phase_hit = ev, None
|
|
254
|
+
ev.wait(self.a.phase_timeout_s)
|
|
255
|
+
with self.lock:
|
|
256
|
+
hit, self.phase_wait = self.phase_hit, None
|
|
257
|
+
if hit is None:
|
|
258
|
+
self.log("PHASE_TIMEOUT", -1, "-", now_ms())
|
|
259
|
+
return None
|
|
260
|
+
if self.a.phase_delay_ms:
|
|
261
|
+
time.sleep(self.a.phase_delay_ms / 1000)
|
|
262
|
+
return hit
|
|
263
|
+
|
|
264
|
+
def inject(self, cname):
|
|
265
|
+
free = [i for i in range(self.a.workers) if i not in self.paused] or list(range(self.a.workers))
|
|
266
|
+
slot = random.choice(free)
|
|
267
|
+
wid, p = self.procs[slot]
|
|
268
|
+
f = self.a.fault
|
|
269
|
+
if f == "mix":
|
|
270
|
+
# harsh mode: every injection draws a fault type (seeded); faults overlap in time (pause and
|
|
271
|
+
# partition are timed, so a kill/term/restart can land while they are active). Never two
|
|
272
|
+
# partitions at once (overlapping toxics conflict).
|
|
273
|
+
kinds = [k for k in self.a.mix.split(",") if not (k == "partition" and self.partitioned)]
|
|
274
|
+
f = random.choice(kinds)
|
|
275
|
+
if self.a.phase and f in ("kill", "term", "pause"):
|
|
276
|
+
hit = self.wait_phase()
|
|
277
|
+
if hit is not None:
|
|
278
|
+
slot = hit
|
|
279
|
+
wid, p = self.procs[slot]
|
|
280
|
+
self.log("PHASE_HIT", -1, wid, now_ms())
|
|
281
|
+
if f == "kill":
|
|
282
|
+
sig(p, signal.SIGKILL); p.wait()
|
|
283
|
+
self.log("KILL", -1, wid, now_ms())
|
|
284
|
+
self.spawn(slot)
|
|
285
|
+
elif f == "term":
|
|
286
|
+
# graceful shutdown (deploy/scale-down): SIGTERM, the adapter runs the queue's own
|
|
287
|
+
# shutdown with a CHAOS_GRACE_MS budget; in-flight jobs still running when it expires
|
|
288
|
+
# are cancelled (their futures dropped / tasks aborted). Harness backstop: SIGKILL.
|
|
289
|
+
if self.a.term_scope == "main":
|
|
290
|
+
# only the process we started (docker stop / Kubernetes style); its children are
|
|
291
|
+
# left to the queue's own shutdown. Default "group" = systemd KillMode=control-group.
|
|
292
|
+
try: os.kill(p.pid, signal.SIGTERM)
|
|
293
|
+
except (ProcessLookupError, PermissionError, AttributeError, TypeError): pass
|
|
294
|
+
else:
|
|
295
|
+
sig(p, signal.SIGTERM)
|
|
296
|
+
self.log("TERM", -1, wid, now_ms())
|
|
297
|
+
try:
|
|
298
|
+
p.wait(timeout=self.a.grace_s + 3.0)
|
|
299
|
+
except subprocess.TimeoutExpired:
|
|
300
|
+
sig(p, signal.SIGKILL); p.wait()
|
|
301
|
+
self.log("KILL", -1, wid, now_ms())
|
|
302
|
+
self.log("EXIT", -1, wid, now_ms())
|
|
303
|
+
self.spawn(slot)
|
|
304
|
+
elif f == "pause":
|
|
305
|
+
# non-blocking: other faults and the producer keep going while this worker is frozen
|
|
306
|
+
sig(p, signal.SIGSTOP)
|
|
307
|
+
self.log("PAUSE", -1, wid, now_ms())
|
|
308
|
+
self.paused.add(slot)
|
|
309
|
+
|
|
310
|
+
def resume(p=p, wid=wid, slot=slot):
|
|
311
|
+
sig(p, signal.SIGCONT)
|
|
312
|
+
self.log("RESUME", -1, wid, now_ms())
|
|
313
|
+
self.paused.discard(slot)
|
|
314
|
+
threading.Timer(self.a.pause_s, resume).start()
|
|
315
|
+
elif f == "partition":
|
|
316
|
+
# black-hole traffic both ways (connections hang, no RST), heal after --partition-s
|
|
317
|
+
for stream in ("upstream", "downstream"):
|
|
318
|
+
toxi("POST", "/proxies/broker/toxics", {"name": f"cut_{stream}", "type": "timeout",
|
|
319
|
+
"stream": stream, "attributes": {"timeout": 0}})
|
|
320
|
+
self.partitioned = True
|
|
321
|
+
self.log("PARTITION_START", -1, "-", now_ms())
|
|
322
|
+
|
|
323
|
+
def heal():
|
|
324
|
+
for stream in ("upstream", "downstream"):
|
|
325
|
+
try:
|
|
326
|
+
toxi("DELETE", f"/proxies/broker/toxics/cut_{stream}")
|
|
327
|
+
except Exception:
|
|
328
|
+
pass
|
|
329
|
+
self.log("PARTITION_END", -1, "-", now_ms())
|
|
330
|
+
self.partitioned = False
|
|
331
|
+
threading.Timer(self.a.partition_s, heal).start()
|
|
332
|
+
elif f == "broker-restart":
|
|
333
|
+
with self.broker_lock:
|
|
334
|
+
self.log("BROKER_DOWN", -1, "-", now_ms())
|
|
335
|
+
sh("docker", "restart", cname)
|
|
336
|
+
self.log("BROKER_UP", -1, "-", now_ms())
|
|
337
|
+
elif f in ("clockskew", "clockjump"):
|
|
338
|
+
if not SKEW:
|
|
339
|
+
raise RuntimeError("clockskew/clockjump need --skew")
|
|
340
|
+
def setclock(v):
|
|
341
|
+
sh("docker", "exec", "-u", "0", cname, "sh", "-c", f"echo '{v}' > /qc/faketime")
|
|
342
|
+
offs = [int(x) for x in self.a.skew_s.split(",")]
|
|
343
|
+
if f == "clockskew":
|
|
344
|
+
off = random.choice(offs)
|
|
345
|
+
setclock(f"{off:+d}")
|
|
346
|
+
self.log("CLOCK_SKEW", off, "-", now_ms())
|
|
347
|
+
time.sleep(self.a.skew_hold_s)
|
|
348
|
+
setclock("+0")
|
|
349
|
+
self.log("CLOCK_RESET", -1, "-", now_ms())
|
|
350
|
+
else:
|
|
351
|
+
off = abs(random.choice(offs))
|
|
352
|
+
setclock(f"{off:+d}")
|
|
353
|
+
self.log("CLOCK_JUMP", off, "-", now_ms())
|
|
354
|
+
elif f == "diskfull":
|
|
355
|
+
if not (DISK_MB > 0 and self.a.backend == "postgres"):
|
|
356
|
+
raise RuntimeError("diskfull needs --backend postgres and --disk-mb > 0")
|
|
357
|
+
pgd = "/var/lib/postgresql/data"
|
|
358
|
+
margin = int(self.a.disk_margin_mb * 1024 * 1024)
|
|
359
|
+
fill = (f"free=$(df -P -B1 {pgd} | awk 'NR==2{{print $4}}'); n=$((free-{margin})); "
|
|
360
|
+
f"[ $n -gt 0 ] || exit 0; "
|
|
361
|
+
f"fallocate -l $n {pgd}/qc_fill || dd if=/dev/zero of={pgd}/qc_fill bs=1M count=$((n/1048576)) 2>/dev/null; true")
|
|
362
|
+
sh("docker", "exec", cname, "sh", "-c", fill, check=False)
|
|
363
|
+
self.log("DISK_FULL", -1, "-", now_ms())
|
|
364
|
+
time.sleep(self.a.diskfull_s)
|
|
365
|
+
sh("docker", "exec", cname, "rm", "-f", f"{pgd}/qc_fill", check=False)
|
|
366
|
+
self.log("DISK_FREE", -1, "-", now_ms())
|
|
367
|
+
# Postgres may have crashed/restarted on WAL ENOSPC; wait until it accepts connections again
|
|
368
|
+
ok = False
|
|
369
|
+
for _ in range(120):
|
|
370
|
+
if sh("docker", "exec", cname, "pg_isready", "-U", "postgres", check=False).returncode == 0:
|
|
371
|
+
ok = True; break
|
|
372
|
+
time.sleep(0.5)
|
|
373
|
+
if not ok:
|
|
374
|
+
print("diskfull: postgres not ready 60s after DISK_FREE", file=sys.stderr)
|
|
375
|
+
else:
|
|
376
|
+
st = sh("docker", "inspect", "-f", "{{.RestartCount}} {{.State.StartedAt}}", cname, check=False).stdout.strip()
|
|
377
|
+
print(f"diskfull: postgres ready again ({st})", file=sys.stderr)
|
|
378
|
+
self.faults_injected += 1
|
|
379
|
+
|
|
380
|
+
def safe_inject(self, cname):
|
|
381
|
+
"""A fault that fails to inject is logged, not allowed to crash the run."""
|
|
382
|
+
try:
|
|
383
|
+
self.inject(cname)
|
|
384
|
+
except Exception as e: # noqa: BLE001 - record and keep the run going
|
|
385
|
+
self.log("FAULT_ERROR", -1, "-", now_ms())
|
|
386
|
+
print(f"fault injection failed: {e!r}", file=sys.stderr)
|
|
387
|
+
|
|
388
|
+
def check_exits(self):
|
|
389
|
+
for slot, (wid, p) in list(self.procs.items()):
|
|
390
|
+
if p.poll() is not None:
|
|
391
|
+
self.log("EXIT", -1, wid, now_ms())
|
|
392
|
+
tail = open(f"{self.a.out}/worker-{wid}.stderr").read()[-300:].strip()
|
|
393
|
+
self.exits.append((wid, p.returncode, now_ms(), tail))
|
|
394
|
+
if self.a.supervise:
|
|
395
|
+
self.spawn(slot)
|
|
396
|
+
else:
|
|
397
|
+
self.procs[slot] = (wid, _Exited())
|
|
398
|
+
|
|
399
|
+
def done(self):
|
|
400
|
+
if self.producing:
|
|
401
|
+
return False
|
|
402
|
+
with self.lock:
|
|
403
|
+
return len({e[1] for e in self.events if e[0] == "END"}) >= self.enqueued
|
|
404
|
+
|
|
405
|
+
def produce(self, enq):
|
|
406
|
+
"""Steady arrivals: `rate` jobs per second for the whole fault window."""
|
|
407
|
+
a, nid = self.a, 0
|
|
408
|
+
per = max(1, int(a.rate))
|
|
409
|
+
t_end = time.time() + a.fault_window
|
|
410
|
+
while time.time() < t_end:
|
|
411
|
+
t = time.time()
|
|
412
|
+
with self.broker_lock:
|
|
413
|
+
# --long-every with --rate: the last job of every max(1, long_every // rate)-th batch is long
|
|
414
|
+
if a.long_every and (nid // per) % max(1, a.long_every // per) == 0:
|
|
415
|
+
if per > 1:
|
|
416
|
+
enq(nid, nid + per - 1, a.work_ms)
|
|
417
|
+
enq(nid + per - 1, nid + per, a.long_ms)
|
|
418
|
+
else:
|
|
419
|
+
enq(nid, nid + per, a.work_ms)
|
|
420
|
+
nid += per
|
|
421
|
+
self.enqueued = nid
|
|
422
|
+
time.sleep(max(0.0, 1.0 - (time.time() - t)))
|
|
423
|
+
self.producing = False
|
|
424
|
+
|
|
425
|
+
def fault_times(self, t0):
|
|
426
|
+
"""Exactly --faults faults, one at a jittered point inside each equal slot of the window."""
|
|
427
|
+
n, w = self.a.faults, self.a.fault_window
|
|
428
|
+
return [t0 + (i + random.uniform(0.2, 0.8)) * w / n for i in range(n)]
|
|
429
|
+
|
|
430
|
+
def go(self, cname):
|
|
431
|
+
a = self.a
|
|
432
|
+
n_long = a.jobs // a.long_every if a.long_every else 0
|
|
433
|
+
split = a.jobs - n_long
|
|
434
|
+
def enq(*x):
|
|
435
|
+
# A real producer retries a failed enqueue (e.g. disk full). The failed call may have inserted part of
|
|
436
|
+
# its range, so the retry can create a second copy of those ids: logged as ENQ_RETRY lo hi so the
|
|
437
|
+
# checker treats duplicates of those ids as explained. Without failures this is the old behaviour.
|
|
438
|
+
for attempt in range(120):
|
|
439
|
+
try:
|
|
440
|
+
return subprocess.run([a.adapter, "enqueue", *map(str, x)], env=self.penv, check=True,
|
|
441
|
+
stdout=subprocess.DEVNULL)
|
|
442
|
+
except subprocess.CalledProcessError:
|
|
443
|
+
self.log("ENQ_RETRY", x[0], str(x[1]), now_ms())
|
|
444
|
+
time.sleep(1)
|
|
445
|
+
raise RuntimeError(f"enqueue {x} failed 120 times")
|
|
446
|
+
if a.rate:
|
|
447
|
+
self.enqueued, self.producing = 0, True
|
|
448
|
+
else:
|
|
449
|
+
enq(0, split, a.work_ms)
|
|
450
|
+
if n_long: # long jobs (longer than the stuck timeout) take the last ids
|
|
451
|
+
enq(split, a.jobs, a.long_ms)
|
|
452
|
+
for s in range(a.workers):
|
|
453
|
+
self.spawn(s)
|
|
454
|
+
t0 = time.time()
|
|
455
|
+
if a.rate:
|
|
456
|
+
threading.Thread(target=self.produce, args=(enq,), daemon=True).start()
|
|
457
|
+
planned = self.fault_times(t0) if a.faults else []
|
|
458
|
+
next_fault = t0 + a.fault_every
|
|
459
|
+
while time.time() - t0 < a.fault_window + a.drain:
|
|
460
|
+
self.check_exits()
|
|
461
|
+
if self.done() and not planned and not self.paused and not self.partitioned:
|
|
462
|
+
break
|
|
463
|
+
now = time.time()
|
|
464
|
+
if a.fault not in ("none", "cmdhold"):
|
|
465
|
+
if planned:
|
|
466
|
+
# never start a partition while the previous one is still active (overlapping
|
|
467
|
+
# toxics conflict); it starts as soon as the network heals
|
|
468
|
+
if now >= planned[0] and not (a.fault == "partition" and self.partitioned):
|
|
469
|
+
planned.pop(0)
|
|
470
|
+
self.safe_inject(cname)
|
|
471
|
+
elif not a.faults and now < t0 + a.fault_window and now >= next_fault:
|
|
472
|
+
self.safe_inject(cname)
|
|
473
|
+
# jitter (seeded) so different seeds hit different execution points
|
|
474
|
+
next_fault = time.time() + a.fault_every * random.uniform(0.5, 1.5)
|
|
475
|
+
time.sleep(0.1)
|
|
476
|
+
time.sleep(1.0) # let in-flight END lines arrive
|
|
477
|
+
for _, p in self.procs.values():
|
|
478
|
+
sig(p, signal.SIGCONT); sig(p, signal.SIGKILL)
|
|
479
|
+
self.end_ms = now_ms()
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def recovery_summary(res):
|
|
483
|
+
rec = sorted(res.get("recovery_ms", []))
|
|
484
|
+
out = f" recov_p50_ms={rec[len(rec) // 2]} recov_max_ms={rec[-1]}" if rec else ""
|
|
485
|
+
late = res.get("late_start", [])
|
|
486
|
+
if late:
|
|
487
|
+
out += f" late_starts={len(late)} late_max_s={max(d for _, d in late) / 1000:.0f}"
|
|
488
|
+
return out
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def leftover_keys(broker_state, n=4):
|
|
492
|
+
"""Non-empty queue-looking keys/tables left in the broker (where lost jobs may be stranded)."""
|
|
493
|
+
skip = ("binding", "pidbox", "heartbeat", "stat", "schema", "migration", "lock", "finished", "complete",
|
|
494
|
+
"succeeded", "result", "processed", "worker")
|
|
495
|
+
perjob = re.compile(r"[0-9a-f]{16,}|[0-9a-f]{8}-[0-9a-f]{4}-") # per-job keys (ids, uuids) are noise here
|
|
496
|
+
rows = []
|
|
497
|
+
for line in broker_state:
|
|
498
|
+
parts = line.split("\t")
|
|
499
|
+
if (len(parts) >= 2 and parts[-1].isdigit() and int(parts[-1]) > 0
|
|
500
|
+
and not any(k in parts[0].lower() for k in skip) and not perjob.search(parts[0])):
|
|
501
|
+
rows.append((int(parts[-1]), parts[0]))
|
|
502
|
+
return [f"{k}={c}" for c, k in sorted(rows, reverse=True)[:n]]
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def dump_broker(backend, cname):
|
|
506
|
+
"""Key/table sizes at the end of the run, so leftover jobs can be located."""
|
|
507
|
+
out = []
|
|
508
|
+
if backend == "redis":
|
|
509
|
+
keys = sh("docker", "exec", cname, "redis-cli", "--scan", check=False).stdout.split()
|
|
510
|
+
for k in sorted(keys):
|
|
511
|
+
if ":meta:" in k:
|
|
512
|
+
continue
|
|
513
|
+
t = sh("docker", "exec", cname, "redis-cli", "type", k, check=False).stdout.strip()
|
|
514
|
+
cmd = {"list": "llen", "zset": "zcard", "set": "scard", "hash": "hlen"}.get(t)
|
|
515
|
+
n = sh("docker", "exec", cname, "redis-cli", cmd, k, check=False).stdout.strip() if cmd else "-"
|
|
516
|
+
out.append(f"{k}\t{t}\t{n}")
|
|
517
|
+
# which commands the server actually executed (e.g. to confirm a client code path)
|
|
518
|
+
stats = sh("docker", "exec", cname, "redis-cli", "INFO", "commandstats", check=False).stdout
|
|
519
|
+
out += [l.strip() for l in stats.splitlines()
|
|
520
|
+
if l.startswith(("cmdstat_brpop", "cmdstat_blpop", "cmdstat_evalsha", "cmdstat_eval:",
|
|
521
|
+
"cmdstat_lpop", "cmdstat_rpop", "cmdstat_zadd", "cmdstat_hset"))]
|
|
522
|
+
elif backend == "postgres":
|
|
523
|
+
q = ("SELECT relname, n_live_tup FROM pg_stat_user_tables ORDER BY relname")
|
|
524
|
+
res = sh("docker", "exec", cname, "psql", "-U", "postgres", "-d", "chaos", "-At", "-F", "\t", "-c", q, check=False)
|
|
525
|
+
out = res.stdout.strip().splitlines()
|
|
526
|
+
st = sh("docker", "exec", cname, "psql", "-U", "postgres", "-d", "chaos", "-At", "-F", "\t", "-c",
|
|
527
|
+
"SELECT 'status:' || status, count(*) FROM asyncq_jobs GROUP BY status", check=False)
|
|
528
|
+
out += st.stdout.strip().splitlines() # asyncq-only; harmless for other queues
|
|
529
|
+
gj = sh("docker", "exec", cname, "psql", "-U", "postgres", "-d", "chaos", "-At", "-F", "\t", "-c",
|
|
530
|
+
"SELECT 'good_jobs_unfinished', count(*) FILTER (WHERE finished_at IS NULL), "
|
|
531
|
+
"'claimed', count(*) FILTER (WHERE finished_at IS NULL AND locked_by_id IS NOT NULL) FROM good_jobs",
|
|
532
|
+
check=False)
|
|
533
|
+
out += gj.stdout.strip().splitlines() # good_job-only; harmless for other queues
|
|
534
|
+
return out
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def analyze(events, jobs, end_ms, stuck_ms, contract="at-least-once"):
|
|
538
|
+
# a worker that was killed OR exited on its own stops executing at that moment
|
|
539
|
+
killed = {e[2]: e[3] for e in events if e[0] in ("KILL", "EXIT")}
|
|
540
|
+
pauses = defaultdict(list) # wid -> [(pause_ts, resume_ts)]
|
|
541
|
+
for kind, _, wid, ts in sorted(events, key=lambda e: e[3]):
|
|
542
|
+
if kind == "PAUSE": pauses[wid].append([ts, end_ms])
|
|
543
|
+
elif kind == "RESUME" and pauses[wid]: pauses[wid][-1][1] = ts
|
|
544
|
+
# a network partition cuts every worker off from the broker: for lease purposes it acts like a
|
|
545
|
+
# pause of all workers (they keep running jobs they can no longer renew)
|
|
546
|
+
partitions = []
|
|
547
|
+
for kind, _, _, ts in sorted(events, key=lambda e: e[3]):
|
|
548
|
+
if kind == "PARTITION_START": partitions.append([ts, end_ms])
|
|
549
|
+
elif kind == "PARTITION_END" and partitions: partitions[-1][1] = ts
|
|
550
|
+
|
|
551
|
+
def wpauses(wid):
|
|
552
|
+
return pauses[wid] + partitions
|
|
553
|
+
|
|
554
|
+
def paused_past_lease(x, other_start):
|
|
555
|
+
# x's worker froze for longer than the lease either
|
|
556
|
+
# - after x started and before the other execution began (lease expired mid-run), or
|
|
557
|
+
# - shortly before x started (it claimed the job, froze, then ran a stale claim)
|
|
558
|
+
return any(p1 - p0 > stuck_ms and
|
|
559
|
+
((x[1] <= p0 <= other_start) or (x[1] - stuck_ms <= p1 <= x[1]))
|
|
560
|
+
for p0, p1 in wpauses(x[0]))
|
|
561
|
+
execs = defaultdict(list) # job -> [[wid, start, end]]
|
|
562
|
+
for kind, job, wid, ts in sorted(events, key=lambda e: e[3]):
|
|
563
|
+
if kind == "START":
|
|
564
|
+
execs[job].append([wid, ts, None, None])
|
|
565
|
+
elif kind == "CANCEL": # handler stopped without finishing: ends the interval, not a completion
|
|
566
|
+
for x in reversed(execs[job]):
|
|
567
|
+
if x[0] == wid and x[2] is None and x[3] is None:
|
|
568
|
+
x[3] = ts; break
|
|
569
|
+
elif kind == "END":
|
|
570
|
+
for x in reversed(execs[job]):
|
|
571
|
+
if x[0] == wid and x[2] is None:
|
|
572
|
+
x[2] = ts; break
|
|
573
|
+
res = dict(jobs=jobs, completed_once=0, lost=[], dup_complete=[], dup_unexplained=[], concurrent=[], lease_overlap=[], redelivered=[],
|
|
574
|
+
recovery_ms=[], late_start=[], lost_by_contract=[])
|
|
575
|
+
broker = [e[3] for e in events if e[0] in ("BROKER_DOWN", "BROKER_UP", "PARTITION_START", "PARTITION_END", "DISK_FULL", "DISK_FREE", "CLOCK_SKEW", "CLOCK_RESET", "CLOCK_JUMP")]
|
|
576
|
+
worker_faults = defaultdict(list) # wid -> [ts] of KILL/EXIT/PAUSE
|
|
577
|
+
for e in events:
|
|
578
|
+
if e[0] in ("KILL", "EXIT", "PAUSE"):
|
|
579
|
+
worker_faults[e[2]].append(e[3])
|
|
580
|
+
|
|
581
|
+
def explained(first, second):
|
|
582
|
+
# first/second = [wid, start, end]. A duplicate is explained when
|
|
583
|
+
# - the first worker was hit (kill/exit/pause) or the broker restarted between the
|
|
584
|
+
# first START and the second START (the ack may have been lost), or
|
|
585
|
+
# - the second worker was frozen during the lease window before it started (it ran a
|
|
586
|
+
# stale claim after the job was reaped and completed elsewhere)
|
|
587
|
+
lo, hi = first[1], second[1]
|
|
588
|
+
if any(lo <= t <= hi for t in worker_faults[first[0]]) or any(lo <= t <= hi for t in broker):
|
|
589
|
+
return True
|
|
590
|
+
if any(p0 <= hi and p1 >= lo - stuck_ms for p0, p1 in wpauses(second[0])):
|
|
591
|
+
return True
|
|
592
|
+
# either execution ran a stale claim: its worker froze past the lease just before it started
|
|
593
|
+
return any(p1 - p0 > stuck_ms and x[1] - stuck_ms <= p1 <= x[1]
|
|
594
|
+
for x in (first, second) for p0, p1 in wpauses(x[0]))
|
|
595
|
+
retried = set() # ids whose enqueue was retried after a failure: a second copy is explained
|
|
596
|
+
for e in events:
|
|
597
|
+
if e[0] == "ENQ_RETRY": retried.update(range(int(e[1]), int(e[2])))
|
|
598
|
+
for j in range(jobs):
|
|
599
|
+
xs = execs.get(j, [])
|
|
600
|
+
ends = sum(1 for x in xs if x[2] is not None)
|
|
601
|
+
if ends == 0: res["lost"].append(j)
|
|
602
|
+
elif ends == 1: res["completed_once"] += 1
|
|
603
|
+
else:
|
|
604
|
+
res["dup_complete"].append(j)
|
|
605
|
+
done = sorted((x for x in xs if x[2] is not None), key=lambda x: x[1])
|
|
606
|
+
if j not in retried and not all(explained(done[i], done[i + 1]) for i in range(len(done) - 1)):
|
|
607
|
+
res["dup_unexplained"].append(j)
|
|
608
|
+
if any(x[2] is None and x[0] in killed for x in xs) and len(xs) > 1:
|
|
609
|
+
res["redelivered"].append(j)
|
|
610
|
+
# interval of an execution: until END or CANCEL, else until its worker was killed, else run end
|
|
611
|
+
iv = [(x[1], x[2] or x[3] or killed.get(x[0], end_ms)) for x in xs]
|
|
612
|
+
pairs = [(i, k) for i in range(len(iv)) for k in range(i + 1, len(iv))
|
|
613
|
+
if iv[i][0] < iv[k][1] and iv[k][0] < iv[i][1]]
|
|
614
|
+
bug = [(i, k) for i, k in pairs
|
|
615
|
+
if not (paused_past_lease(xs[i], xs[k][1]) or paused_past_lease(xs[k], xs[i][1]))]
|
|
616
|
+
if bug and j not in retried: res["concurrent"].append(j)
|
|
617
|
+
elif pairs: res["lease_overlap"].append(j)
|
|
618
|
+
# recovery time: worker of an unfinished run died -> next START of the same job
|
|
619
|
+
for a_, b_ in zip(xs, xs[1:]):
|
|
620
|
+
if a_[2] is None and a_[0] in killed and b_[1] >= killed[a_[0]]:
|
|
621
|
+
res["recovery_ms"].append(b_[1] - killed[a_[0]])
|
|
622
|
+
# Documented at-most-once contract: a job that STARTed on a worker that was then killed or exited, and never
|
|
623
|
+
# completed, is lost as the library documents ("lost_by_contract"). Jobs that never started stay "lost".
|
|
624
|
+
if contract == "at-most-once":
|
|
625
|
+
deaths = defaultdict(list)
|
|
626
|
+
for e in events:
|
|
627
|
+
if e[0] in ("KILL", "EXIT"):
|
|
628
|
+
deaths[e[2]].append(e[3])
|
|
629
|
+
keep = []
|
|
630
|
+
for j in res["lost"]:
|
|
631
|
+
xs = execs.get(j, [])
|
|
632
|
+
if xs and any(t >= xs[-1][1] for t in deaths[xs[-1][0]]):
|
|
633
|
+
res["lost_by_contract"].append(j)
|
|
634
|
+
else:
|
|
635
|
+
keep.append(j)
|
|
636
|
+
res["lost"] = keep
|
|
637
|
+
# late starts: first START more than LATE_MS after the last fault ended (stranded, then recovered late)
|
|
638
|
+
marks = [e[3] for e in events if e[0] in ("KILL", "TERM", "PAUSE", "RESUME", "BROKER_UP", "PARTITION_END",
|
|
639
|
+
"DISK_FREE", "CLOCK_RESET", "CLOCK_JUMP")]
|
|
640
|
+
if marks:
|
|
641
|
+
last = max(marks)
|
|
642
|
+
for j in range(jobs):
|
|
643
|
+
xs = execs.get(j, [])
|
|
644
|
+
if xs and xs[0][1] - last > LATE_MS:
|
|
645
|
+
res["late_start"].append([j, xs[0][1] - last])
|
|
646
|
+
return res
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def main():
|
|
650
|
+
if len(sys.argv) > 1 and sys.argv[1] == "check":
|
|
651
|
+
import qcheck
|
|
652
|
+
return qcheck.main(sys.argv[2:])
|
|
653
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
654
|
+
ap.add_argument("--adapter", required=True, help="path to adapter binary")
|
|
655
|
+
ap.add_argument("--contract", choices=["at-least-once", "at-most-once"], default="at-least-once",
|
|
656
|
+
help="the queue's documented delivery guarantee. at-most-once: jobs that started on a worker that "
|
|
657
|
+
"was then killed or exited are reported as lost_by_contract, not lost (see docs/contracts.json)")
|
|
658
|
+
ap.add_argument("--backend", choices=BACKENDS, default="redis")
|
|
659
|
+
ap.add_argument("--fault", choices=["none", "kill", "term", "pause", "broker-restart", "partition", "diskfull", "clockskew", "clockjump", "mix", "cmdhold"], default="none")
|
|
660
|
+
ap.add_argument("--hold", action="append", default=[], help="cmdhold rule CMD[:ARGPAT]:ms[:prob] (repeatable); see tools/resp_hold.py")
|
|
661
|
+
ap.add_argument("--phase", choices=["", "start", "end"], default="",
|
|
662
|
+
help="kill/term/pause fire on the worker that just printed the next START (mid-job) or END "
|
|
663
|
+
"(handler done, ack/finalize not yet written) instead of a random worker")
|
|
664
|
+
ap.add_argument("--phase-delay-ms", type=int, default=0, help="--phase: wait this long after the event before the fault")
|
|
665
|
+
ap.add_argument("--phase-timeout-s", type=float, default=5.0, help="--phase: fall back to a random worker after this")
|
|
666
|
+
ap.add_argument("--discover", action="store_true", help="cmdhold: log per-connection command histogram to <out>/discover-seedN.tsv")
|
|
667
|
+
ap.add_argument("--mix", default="kill,term,pause,broker-restart,partition",
|
|
668
|
+
help="mix fault: comma-separated fault types to draw from (seeded)")
|
|
669
|
+
ap.add_argument("--disk-mb", type=int, default=0,
|
|
670
|
+
help="postgres only: data dir on a tmpfs of this many MB (0 = off); needed for --fault diskfull")
|
|
671
|
+
ap.add_argument("--diskfull-s", type=float, default=5.0, help="how long the disk stays full")
|
|
672
|
+
ap.add_argument("--disk-margin-mb", type=float, default=float(os.environ.get("QC_DISK_MARGIN_MB", 0)),
|
|
673
|
+
help="free space left when filling, so rm still works")
|
|
674
|
+
ap.add_argument("--skew", action="store_true", help="start redis/postgres from the libfaketime image (docker/faketime/)")
|
|
675
|
+
ap.add_argument("--skew-s", default="30,-30,120", help="clockskew/clockjump offsets in seconds, comma list")
|
|
676
|
+
ap.add_argument("--skew-hold-s", type=float, default=10.0, help="how long clockskew holds the offset")
|
|
677
|
+
ap.add_argument("--jobs", type=int, default=200)
|
|
678
|
+
ap.add_argument("--work-ms", type=int, default=300)
|
|
679
|
+
ap.add_argument("--long-every", type=int, default=0, help="every Nth job is long (0 = none)")
|
|
680
|
+
ap.add_argument("--long-ms", type=int, default=6000)
|
|
681
|
+
ap.add_argument("--workers", type=int, default=3)
|
|
682
|
+
ap.add_argument("--concurrency", type=int, default=4)
|
|
683
|
+
ap.add_argument("--stuck-ms", type=int, default=2000, help="queue's stuck/visibility timeout")
|
|
684
|
+
ap.add_argument("--fault-every", type=float, default=3.0)
|
|
685
|
+
ap.add_argument("--pause-s", type=float, default=5.0)
|
|
686
|
+
ap.add_argument("--partition-s", type=float, default=5.0, help="duration of each network partition")
|
|
687
|
+
ap.add_argument("--term-scope", choices=["group", "main"], default="group",
|
|
688
|
+
help="term fault: SIGTERM the worker's process group (default) or only its main process")
|
|
689
|
+
ap.add_argument("--grace-s", type=float, default=1.0,
|
|
690
|
+
help="term fault: graceful-shutdown budget passed to the adapter (CHAOS_GRACE_MS)")
|
|
691
|
+
ap.add_argument("--fault-window", type=float, default=20.0)
|
|
692
|
+
ap.add_argument("--drain", type=float, default=40.0)
|
|
693
|
+
ap.add_argument("--rate", type=float, default=0,
|
|
694
|
+
help="steady arrivals: jobs/s for the whole fault window (0 = enqueue --jobs up front)")
|
|
695
|
+
ap.add_argument("--faults", type=int, default=0,
|
|
696
|
+
help="inject exactly N faults, one per equal slot of the window (0 = every --fault-every s)")
|
|
697
|
+
ap.add_argument("--seed", type=int, default=1)
|
|
698
|
+
ap.add_argument("--supervise", action="store_true",
|
|
699
|
+
help="restart workers that exit on their own (like systemd/k8s would)")
|
|
700
|
+
ap.add_argument("--out", default="results")
|
|
701
|
+
a = ap.parse_args()
|
|
702
|
+
random.seed(a.seed)
|
|
703
|
+
global DISK_MB, SKEW
|
|
704
|
+
SKEW = a.skew
|
|
705
|
+
DISK_MB = a.disk_mb
|
|
706
|
+
left = kill_leftover_workers()
|
|
707
|
+
if left:
|
|
708
|
+
print(f"killed {left} leftover worker process group(s) from an earlier run", file=sys.stderr)
|
|
709
|
+
cname, direct_url, worker_url = start_backend(a.backend, proxied=(a.fault in ("partition", "mix")))
|
|
710
|
+
proxy = None
|
|
711
|
+
if a.fault == "cmdhold":
|
|
712
|
+
if a.backend != "redis":
|
|
713
|
+
sys.exit("cmdhold supports the redis backend only")
|
|
714
|
+
os.makedirs(a.out, exist_ok=True)
|
|
715
|
+
hold_log = f"{a.out}/hold-seed{a.seed}-{int(time.time())}.log"
|
|
716
|
+
pargs = [sys.executable, os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools", "resp_hold.py"),
|
|
717
|
+
"--listen", str(PROXY_PORT["redis"]), "--upstream", f"127.0.0.1:{BACKENDS['redis']['port']}",
|
|
718
|
+
"--log", hold_log, "--seed", str(a.seed)]
|
|
719
|
+
for h in a.hold:
|
|
720
|
+
pargs += ["--hold", h]
|
|
721
|
+
if a.discover:
|
|
722
|
+
pargs += ["--discover", f"{a.out}/discover-seed{a.seed}.tsv"]
|
|
723
|
+
proxy = subprocess.Popen(pargs)
|
|
724
|
+
time.sleep(1.0)
|
|
725
|
+
worker_url = direct_url.replace(f":{BACKENDS['redis']['port']}", f":{PROXY_PORT['redis']}")
|
|
726
|
+
r = Run(a, worker_url, producer_url=direct_url)
|
|
727
|
+
try:
|
|
728
|
+
r.go(cname)
|
|
729
|
+
finally:
|
|
730
|
+
r.kill_all()
|
|
731
|
+
if proxy:
|
|
732
|
+
proxy.terminate(); proxy.wait()
|
|
733
|
+
for line in open(hold_log):
|
|
734
|
+
k, conn, cmd, key, ms, ts = line.rstrip("\n").split("\t")
|
|
735
|
+
r.log("HOLD", f"{cmd} {key} {ms}ms", conn, int(ts))
|
|
736
|
+
broker_state = dump_broker(a.backend, cname)
|
|
737
|
+
sh("docker", "rm", "-f", cname, TOXI_NAME, check=False)
|
|
738
|
+
sh("docker", "network", "rm", NET, check=False)
|
|
739
|
+
res = analyze(r.events, r.enqueued, r.end_ms, a.stuck_ms, a.contract)
|
|
740
|
+
os.makedirs(a.out, exist_ok=True)
|
|
741
|
+
tag = f"{a.backend}-{a.fault}-seed{a.seed}-{int(time.time())}"
|
|
742
|
+
with open(f"{a.out}/{tag}.events.tsv", "w") as f:
|
|
743
|
+
f.writelines("\t".join(map(str, e)) + "\n" for e in sorted(r.events, key=lambda e: e[3]))
|
|
744
|
+
with open(f"{a.out}/{tag}.broker.txt", "w") as f:
|
|
745
|
+
f.write("\n".join(broker_state) + "\n")
|
|
746
|
+
with open(f"{a.out}/{tag}.json", "w") as f:
|
|
747
|
+
json.dump(dict(checker_version=CHECKER_VERSION, mode=os.environ.get("CHAOS_MODE", ""),
|
|
748
|
+
faults_injected=r.faults_injected, jobs_enqueued=r.enqueued, end_ms=r.end_ms,
|
|
749
|
+
config=vars(a), result=res, worker_exits=r.exits), f, indent=1)
|
|
750
|
+
# A run where nothing was enqueued or nothing completed (e.g. workers crashed at startup) proves
|
|
751
|
+
# nothing: report it as INVALID instead of letting "lost=0" look like a clean result.
|
|
752
|
+
invalid = r.enqueued == 0 or res["completed_once"] + len(res["dup_complete"]) == 0
|
|
753
|
+
if invalid:
|
|
754
|
+
print(f"{tag}: INVALID run (enqueued={r.enqueued}, completed=0, worker_exits={len(r.exits)}) — check worker stderr")
|
|
755
|
+
return 2
|
|
756
|
+
print(f"{tag}: jobs={r.enqueued} faults={r.faults_injected} completed_once={res['completed_once']} lost={len(res['lost'])} "
|
|
757
|
+
f"dup_complete={len(res['dup_complete'])} dup_unexplained={len(res['dup_unexplained'])} concurrent={len(res['concurrent'])} "
|
|
758
|
+
f"lease_overlap={len(res['lease_overlap'])} "
|
|
759
|
+
f"redelivered={len(res['redelivered'])} worker_exits={len(r.exits)}"
|
|
760
|
+
+ (f" lost_by_contract={len(res['lost_by_contract'])}" if a.contract == "at-most-once" else "")
|
|
761
|
+
+ recovery_summary(res))
|
|
762
|
+
if res["lost"]:
|
|
763
|
+
left = leftover_keys(broker_state)
|
|
764
|
+
if left:
|
|
765
|
+
print(" broker still holds: " + " ".join(left))
|
|
766
|
+
for wid, rc, _, tail in r.exits[:2]:
|
|
767
|
+
print(f" exit {wid} rc={rc}: {tail.splitlines()[-1] if tail else ''}")
|
|
768
|
+
return 1 if res["lost"] or res["concurrent"] else 0
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
if __name__ == "__main__":
|
|
772
|
+
sys.exit(main())
|