forked from mtusi2026/mtusi2026lab7
105 lines
3.7 KiB
Python
105 lines
3.7 KiB
Python
import concurrent.futures
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
|
from client import Client, check
|
|
from provision import compose
|
|
from bootstrap import ROOT, write
|
|
from stack_operator import stop_one
|
|
|
|
|
|
def main():
|
|
c = Client(base_url="https://127.0.0.1:8443", ca_file="secrets/public/ca.crt", timeout=3)
|
|
actor, _, _, chat = c.bootstrap()
|
|
instances = {c.call("GET", "/health/ready")["headers"]["X-Instance-Id"] for _ in range(12)}
|
|
check(len(instances) == 2, "Expected two active replicas")
|
|
existing = c.message(actor, chat, "confirmed-before-other-failure")["json"]
|
|
target = next(
|
|
value
|
|
for value in compose("ps", "-q", "api").splitlines()
|
|
if subprocess.check_output(["docker", "inspect", "--format", "{{.Name}}", value])
|
|
.decode()
|
|
.strip()
|
|
.endswith("-api-1")
|
|
)
|
|
alias = (
|
|
subprocess.check_output(["docker", "exec", target, "cat", "/tmp/instance-id"])
|
|
.decode()
|
|
.strip()
|
|
)
|
|
os.environ["TARGET_INSTANCE_ID"] = alias
|
|
started = time.monotonic()
|
|
|
|
def writer(index):
|
|
local = Client(
|
|
base_url="https://127.0.0.1:8443", ca_file="secrets/public/ca.crt", timeout=3
|
|
)
|
|
confirmed = []
|
|
errors = 0
|
|
n = 0
|
|
while time.monotonic() - started < 15:
|
|
key = uuid.uuid4().hex
|
|
text = f"other-{index}-{n}"
|
|
for _ in range(2):
|
|
try:
|
|
confirmed.append(local.message(actor, chat, text, key)["json"])
|
|
break
|
|
except Exception:
|
|
errors += 1
|
|
n += 1
|
|
return confirmed, errors
|
|
|
|
try:
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
|
|
futures = [pool.submit(writer, i) for i in range(4)]
|
|
time.sleep(1)
|
|
stop_one()
|
|
results = [f.result() for f in futures]
|
|
confirmed = [row for rows, _ in results for row in rows]
|
|
check(bool(confirmed), "No successful concurrent writes")
|
|
visible = []
|
|
cursor = None
|
|
while True:
|
|
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
|
if cursor:
|
|
path += "&cursor=" + __import__("urllib.parse", fromlist=["quote"]).quote(cursor)
|
|
page = c.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
|
visible += page["items"]
|
|
cursor = page["next_cursor"]
|
|
if not cursor:
|
|
break
|
|
ids = {row["id"] for row in visible}
|
|
check(all(row["id"] in ids for row in confirmed + [existing]), "Confirmed message lost")
|
|
check(len({row["text"] for row in visible}) == len(visible), "Retry duplicated message")
|
|
check(
|
|
alias
|
|
not in {c.call("GET", "/health/ready")["headers"]["X-Instance-Id"] for _ in range(10)},
|
|
"Stopped process still served requests",
|
|
)
|
|
result = dict(
|
|
status="PASS",
|
|
stopped_replica="api-1",
|
|
concurrency=4,
|
|
duration_seconds=round(time.monotonic() - started, 3),
|
|
confirmed_writes=len(confirmed),
|
|
failed_attempts=sum(n for _, n in results),
|
|
confirmed_preserved=True,
|
|
duplicate_effects=0,
|
|
stopped_alias_absent=True,
|
|
)
|
|
write(ROOT / "evidence/failover-other.json", json.dumps(result, indent=2) + "\n")
|
|
print(json.dumps(result, indent=2))
|
|
finally:
|
|
compose("start", "--wait", "--wait-timeout", "120", "api")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|