Prove per-replica failover and rolling replacement under load
This commit is contained in:
@@ -0,0 +1,239 @@
|
||||
"""Operator checks: topology unittest plus explicit rolling replacement exercise."""
|
||||
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import unittest
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure # noqa: E402
|
||||
from resilience import history # noqa: E402
|
||||
|
||||
|
||||
class TopologyTests(unittest.TestCase):
|
||||
def test_limits_ports_mounts_and_secrets(self):
|
||||
proc = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env.example", "config", "--format", "json"],
|
||||
cwd=ROOT, capture_output=True, text=True, check=True,
|
||||
)
|
||||
services = json.loads(proc.stdout)["services"]
|
||||
self.assertEqual(set(services), {"postgres", "migrate", "api", "lb"})
|
||||
for name, service in services.items():
|
||||
self.assertNotIn("container_name", service, name)
|
||||
self.assertGreater(float(service.get("cpus", 0)), 0, name)
|
||||
self.assertGreater(int(service.get("mem_limit", 0)), 0, name)
|
||||
if name != "lb":
|
||||
self.assertFalse(service.get("ports"), name)
|
||||
self.assertEqual(len(services["lb"]["ports"]), 1)
|
||||
self.assertEqual(services["api"].get("volumes", []), [])
|
||||
self.assertEqual(services["migrate"].get("volumes", []), [])
|
||||
self.assertEqual(services["lb"].get("secrets", []), [])
|
||||
self.assertEqual(len(services["lb"].get("volumes", [])), 1)
|
||||
self.assertTrue(services["lb"]["volumes"][0]["read_only"])
|
||||
self.assertEqual({s["source"] for s in services["api"]["secrets"]}, {"database_url"})
|
||||
self.assertEqual({s["source"] for s in services["migrate"]["secrets"]}, {"database_url"})
|
||||
self.assertEqual({s["source"] for s in services["postgres"]["secrets"]}, {"postgres_password"})
|
||||
|
||||
|
||||
def rolling(base_url):
|
||||
client = Client(base_url, None, timeout=2)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
script = ROOT / "scripts/rolling-update.sh"
|
||||
started = time.monotonic()
|
||||
stop = False
|
||||
|
||||
def writes():
|
||||
local = Client(base_url, None, timeout=2)
|
||||
confirmed, errors = [], 0
|
||||
key, body = uuid4().hex, "rolling-" + uuid4().hex
|
||||
while not stop:
|
||||
try:
|
||||
msg = local.message(alice, chat, body, key=key)["json"]
|
||||
confirmed.append(msg)
|
||||
key, body = uuid4().hex, "rolling-" + uuid4().hex
|
||||
except Failure:
|
||||
errors += 1 # Retry the uncertain write with its original key/body.
|
||||
return confirmed, errors
|
||||
|
||||
def reads():
|
||||
local = Client(base_url, None, timeout=2)
|
||||
successes, errors, instances = 0, 0, set()
|
||||
while not stop:
|
||||
try:
|
||||
result = local.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
successes += 1
|
||||
instances.add(result["headers"]["X-Instance-Id"])
|
||||
except Failure:
|
||||
errors += 1
|
||||
return successes, errors, instances
|
||||
|
||||
def duplicates():
|
||||
local = Client(base_url, None, timeout=2)
|
||||
ids, attempted, errors, cross_replica = [], [], 0, 0
|
||||
with ThreadPoolExecutor(max_workers=2) as pair_pool:
|
||||
while not stop:
|
||||
key, body = uuid4().hex, "duplicate-" + uuid4().hex
|
||||
attempted.append(body)
|
||||
def send(_):
|
||||
return local.message(alice, chat, body, key=key)
|
||||
futures = [pair_pool.submit(send, index) for index in range(2)]
|
||||
pair = []
|
||||
for future in futures:
|
||||
try:
|
||||
pair.append(future.result())
|
||||
except Failure:
|
||||
errors += 1
|
||||
if len(pair) == 2:
|
||||
assert pair[0]["json"]["id"] == pair[1]["json"]["id"]
|
||||
ids.append(pair[0]["json"]["id"])
|
||||
cross_replica += pair[0]["headers"]["X-Instance-Id"] != pair[1]["headers"]["X-Instance-Id"]
|
||||
time.sleep(0.05)
|
||||
return ids, attempted, errors, cross_replica
|
||||
|
||||
with ThreadPoolExecutor(max_workers=3) as pool:
|
||||
write_result = pool.submit(writes)
|
||||
read_result = pool.submit(reads)
|
||||
duplicate_result = pool.submit(duplicates)
|
||||
proc = subprocess.Popen([str(script)], cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
try:
|
||||
stdout, stderr = proc.communicate(timeout=90)
|
||||
if proc.returncode:
|
||||
raise RuntimeError("rolling replacement failed: " + stderr.strip())
|
||||
time.sleep(3) # Include DNS/LB recovery after the last replacement.
|
||||
finally:
|
||||
stop = True
|
||||
if proc.poll() is None:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=5)
|
||||
confirmed, write_errors = write_result.result()
|
||||
read_count, read_errors, instances = read_result.result()
|
||||
duplicate_ids, attempted_duplicates, duplicate_errors, cross_replica = duplicate_result.result()
|
||||
|
||||
elapsed = time.monotonic() - started
|
||||
messages = history(client, bob, chat)
|
||||
seen = {message["id"] for message in messages}
|
||||
assert confirmed and read_count and duplicate_ids, "load did not exercise all operations"
|
||||
assert {message["id"] for message in confirmed}.issubset(seen), "confirmed write missing"
|
||||
assert set(duplicate_ids).issubset(seen), "idempotent write missing"
|
||||
duplicate_counts = {body: 0 for body in attempted_duplicates}
|
||||
for message in messages:
|
||||
if message["text"] in duplicate_counts:
|
||||
duplicate_counts[message["text"]] += 1
|
||||
assert all(count <= 1 for count in duplicate_counts.values()), "uncertain retry duplicated a message"
|
||||
assert len(instances) >= 2 and cross_replica > 0, "rolling test did not cross replicas"
|
||||
print(json.dumps({
|
||||
"action": "same-version sequential API replacement", "elapsed_seconds": round(elapsed, 3),
|
||||
"successful_reads": read_count, "failed_reads": read_errors,
|
||||
"successful_writes": len(confirmed), "failed_write_attempts": write_errors,
|
||||
"successful_idempotent_pairs": len(duplicate_ids), "failed_pair_attempts": duplicate_errors,
|
||||
"cross_replica_pairs": cross_replica,
|
||||
"successful_rps": round((read_count + len(confirmed) + 2 * len(duplicate_ids)) / elapsed, 3),
|
||||
"observed_instance_count": len(instances), "replacement_output": stdout.strip().splitlines(),
|
||||
"confirmed_messages_read_back": True,
|
||||
}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
def failover(base_url, target_index):
|
||||
containers = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "ps", "-q", "api"],
|
||||
cwd=ROOT, capture_output=True, text=True, check=True,
|
||||
).stdout.splitlines()
|
||||
assert len(containers) == 2, "expected two running API replicas"
|
||||
target = containers[target_index - 1]
|
||||
target_name = subprocess.run(
|
||||
["docker", "inspect", "-f", "{{.Name}}", target],
|
||||
capture_output=True, text=True, check=True,
|
||||
).stdout.strip().lstrip("/")
|
||||
alias = subprocess.run(
|
||||
["docker", "exec", target, "python", "-c",
|
||||
"import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8080/health/live').headers['X-Instance-Id'])"],
|
||||
capture_output=True, text=True, check=True,
|
||||
).stdout.strip()
|
||||
client = Client(base_url, None, timeout=2)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
started = time.monotonic()
|
||||
stop = False
|
||||
action_done = False
|
||||
|
||||
def traffic(write):
|
||||
local = Client(base_url, None, timeout=2)
|
||||
confirmed, errors, after_stop = [], 0, None
|
||||
key, body = uuid4().hex, "failover-" + uuid4().hex
|
||||
while not stop:
|
||||
try:
|
||||
if write:
|
||||
result = local.message(alice, chat, body, key=key)
|
||||
confirmed.append(result["json"])
|
||||
key, body = uuid4().hex, "failover-" + uuid4().hex
|
||||
else:
|
||||
local.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
confirmed.append(1)
|
||||
if action_done and after_stop is None:
|
||||
after_stop = time.monotonic() - started
|
||||
except Failure:
|
||||
errors += 1
|
||||
time.sleep(0.05)
|
||||
return confirmed, errors, after_stop
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
writes = pool.submit(traffic, True)
|
||||
reads = pool.submit(traffic, False)
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[str(ROOT / "scripts/stop-one.sh")], cwd=ROOT,
|
||||
env={**os.environ, "TARGET_INSTANCE_ID": alias}, capture_output=True, text=True, timeout=20,
|
||||
)
|
||||
action_done = True
|
||||
stop_elapsed = time.monotonic() - started
|
||||
assert proc.returncode == 0, "stop-one hook failed: " + proc.stderr.strip()
|
||||
time.sleep(max(0, 15 - stop_elapsed))
|
||||
finally:
|
||||
stop = True
|
||||
confirmed, write_errors, first_write = writes.result()
|
||||
read_count, read_errors, first_read = reads.result()
|
||||
|
||||
actual = subprocess.run(
|
||||
["docker", "inspect", "-f", "{{.State.Status}}", target],
|
||||
capture_output=True, text=True, check=True,
|
||||
).stdout.strip()
|
||||
assert actual == "exited", "target container remained running"
|
||||
messages = history(client, bob, chat)
|
||||
seen = {message["id"] for message in messages}
|
||||
assert confirmed and read_count, "traffic did not continue"
|
||||
assert {message["id"] for message in confirmed}.issubset(seen), "confirmed write lost"
|
||||
assert first_write is not None and first_write <= 10, "write recovery exceeded 10 seconds"
|
||||
assert first_read is not None and first_read <= 10, "read recovery exceeded 10 seconds"
|
||||
elapsed = time.monotonic() - started
|
||||
print(json.dumps({
|
||||
"action": "stop one selected API replica", "target_container": target_name,
|
||||
"target_container_id": target, "target_state_after_hook": actual,
|
||||
"elapsed_seconds": round(elapsed, 3), "stop_hook_seconds": round(stop_elapsed, 3),
|
||||
"successful_reads": len(read_count), "failed_reads": read_errors,
|
||||
"successful_writes": len(confirmed), "failed_write_attempts": write_errors,
|
||||
"successful_rps": round((len(read_count) + len(confirmed)) / elapsed, 3),
|
||||
"first_read_after_action_seconds": round(first_read, 3),
|
||||
"first_write_after_action_seconds": round(first_write, 3),
|
||||
"confirmed_messages_read_back": True,
|
||||
}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(add_help=False)
|
||||
parser.add_argument("--rolling", action="store_true")
|
||||
parser.add_argument("--failover-index", type=int, choices=(1, 2))
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:8080")
|
||||
args, remaining = parser.parse_known_args()
|
||||
if args.rolling:
|
||||
rolling(args.base_url)
|
||||
elif args.failover_index:
|
||||
failover(args.base_url, args.failover_index)
|
||||
else:
|
||||
unittest.main(argv=[sys.argv[0], *remaining])
|
||||
Reference in New Issue
Block a user