218 lines
9.0 KiB
Python
218 lines
9.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Disposable Patroni failover test; never attaches to an existing cluster."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import http.client
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
|
|
from readiness_support import signed_headers
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
DATABASES = ("db-a", "db-b", "db-c")
|
|
ETCD = ("etcd-a", "etcd-b", "etcd-c")
|
|
ACCESS = "HaTestAccessKey0001"
|
|
SECRET = "ha-test-s3-secret-01234567890123456789"
|
|
|
|
|
|
def wait_for(check, description, timeout=150):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
result = check()
|
|
if result:
|
|
return result
|
|
time.sleep(1)
|
|
raise RuntimeError(f"Timed out waiting for {description}")
|
|
|
|
|
|
class Drill:
|
|
def __init__(self, image):
|
|
self.project = "objectstore-ha-" + uuid.uuid4().hex[:12]
|
|
self.image = image or self.project + ":local"
|
|
self.environment = dict(os.environ, OBJECTSTORE_HA_IMAGE=self.image, COMPOSE_PARALLEL_LIMIT="1")
|
|
self.host = None
|
|
self.writes = {}
|
|
|
|
def compose(self, *arguments, check=True):
|
|
return subprocess.run(
|
|
["docker", "compose", "--env-file", "/dev/null", "-p", self.project, "-f", "tests/ha/compose.yaml", *arguments],
|
|
cwd=ROOT, env=self.environment, capture_output=True, text=True, check=check,
|
|
timeout=15 if arguments[0] == "exec" else 600 if arguments[0] == "build" or "--build" in arguments else 90,
|
|
)
|
|
|
|
def cluster(self, observer):
|
|
program = ("import json,urllib.request; "
|
|
"print(urllib.request.urlopen('http://127.0.0.1:8008/cluster',timeout=3).read().decode())")
|
|
try:
|
|
result = self.compose("exec", "-T", observer, "python3", "-c", program, check=False)
|
|
except subprocess.TimeoutExpired:
|
|
return []
|
|
if result.returncode:
|
|
return []
|
|
try:
|
|
return json.loads(result.stdout).get("members", [])
|
|
except ValueError:
|
|
return []
|
|
|
|
def primary(self, observer, excluded=None, count=3):
|
|
members = self.cluster(observer)
|
|
healthy = [item for item in members if item.get("state") in ("running", "streaming")]
|
|
leaders = [item["name"] for item in healthy if item.get("role") == "leader"]
|
|
synchronous = any(item.get("role") in ("sync_standby", "quorum_standby") for item in healthy)
|
|
if len(healthy) >= count and len(leaders) == 1 and synchronous and leaders[0] != excluded:
|
|
return leaders[0]
|
|
return None
|
|
|
|
def request(self, method, path, body=b"", timeout=12):
|
|
connection = http.client.HTTPConnection(self.host, timeout=timeout)
|
|
try:
|
|
headers = signed_headers(method, path, body, self.host, ACCESS, SECRET, "us-east-1")
|
|
connection.request(method, path, body, headers)
|
|
response = connection.getresponse()
|
|
return response.status, response.read()
|
|
finally:
|
|
connection.close()
|
|
|
|
def ready(self):
|
|
try:
|
|
return self.request("GET", "/ready")[0] == 200
|
|
except (OSError, http.client.HTTPException):
|
|
return False
|
|
|
|
def seed(self, prefix):
|
|
for index in range(12):
|
|
path = f"/ha-test/{prefix}/{index}"
|
|
body = hashlib.shake_256(path.encode()).digest(4096)
|
|
status, _ = self.request("PUT", path, body)
|
|
if status != 200:
|
|
raise AssertionError(f"Write returned {status}: {path}")
|
|
self.writes[path] = hashlib.sha256(body).hexdigest()
|
|
|
|
def verify(self):
|
|
for path, digest in self.writes.items():
|
|
status, body = self.request("GET", path)
|
|
if status != 200 or hashlib.sha256(body).hexdigest() != digest:
|
|
raise AssertionError(f"Acknowledged object changed or disappeared: {path}")
|
|
|
|
def start(self, build):
|
|
if build:
|
|
subprocess.run(["docker", "build", "-t", self.image, "."], cwd=ROOT, check=True)
|
|
print("Starting isolated metadata HA cluster", flush=True)
|
|
self.compose("build", "db-a")
|
|
self.compose("up", "-d", "--no-build", *ETCD, *DATABASES, "node-a", "node-b")
|
|
leader = wait_for(lambda: self.primary("db-c"), "three PostgreSQL members and synchronous standby")
|
|
self.compose("up", "-d", "gateway")
|
|
self.host = self.compose("port", "gateway", "9000").stdout.strip()
|
|
if not self.host.startswith("127.0.0.1:") or "\n" in self.host:
|
|
raise RuntimeError("Gateway port was not published on loopback")
|
|
wait_for(self.ready, "ObjectStore readiness")
|
|
return leader
|
|
|
|
def failover(self, leader):
|
|
observer = next(name for name in DATABASES if name != leader)
|
|
print(f"Killing disposable primary {leader}", flush=True)
|
|
before = time.monotonic()
|
|
self.compose("kill", "-s", "SIGKILL", leader)
|
|
new_leader = wait_for(lambda: self.primary(observer, excluded=leader, count=2), "automatic promotion")
|
|
wait_for(self.ready, "gateway reconnection without restart")
|
|
elapsed = time.monotonic() - before
|
|
self.verify()
|
|
self.seed("after-promotion")
|
|
self.compose("start", leader)
|
|
wait_for(lambda: self.primary(observer), "old primary to rejoin")
|
|
self.verify()
|
|
return new_leader, elapsed
|
|
|
|
def quorum_healthy(self):
|
|
try:
|
|
result = self.compose("exec", "-T", "etcd-a", "etcdctl",
|
|
"--endpoints=http://etcd-a:2379,http://etcd-b:2379,http://etcd-c:2379",
|
|
"--command-timeout=3s", "endpoint", "health", check=False)
|
|
return result.returncode == 0
|
|
except subprocess.TimeoutExpired:
|
|
return False
|
|
|
|
def lose_quorum(self, observer):
|
|
print("Removing disposable DCS majority", flush=True)
|
|
self.compose("stop", "etcd-b", "etcd-c")
|
|
wait_for(lambda: not self.ready(), "gateway to refuse readiness", timeout=70)
|
|
try:
|
|
status, _ = self.request("PUT", "/ha-test/uncertain-during-quorum-loss", b"uncertain")
|
|
if status == 200:
|
|
raise AssertionError("Write was acknowledged after metadata quorum was lost")
|
|
except (OSError, http.client.HTTPException):
|
|
pass
|
|
self.compose("start", "etcd-b", "etcd-c")
|
|
wait_for(self.quorum_healthy, "all coordination members to recover")
|
|
wait_for(lambda: self.primary(observer), "metadata quorum recovery")
|
|
wait_for(self.ready, "gateway recovery")
|
|
self.verify()
|
|
self.seed("after-quorum-recovery")
|
|
|
|
def lose_standbys(self, leader):
|
|
replicas = [name for name in DATABASES if name != leader]
|
|
print("Removing disposable synchronous replicas", flush=True)
|
|
self.compose("kill", "-s", "SIGKILL", *replicas)
|
|
try:
|
|
status, _ = self.request("PUT", "/ha-test/uncertain-without-standby", b"uncertain")
|
|
if status == 200:
|
|
raise AssertionError("Write was acknowledged without a synchronous standby")
|
|
except (OSError, http.client.HTTPException):
|
|
pass
|
|
self.compose("start", *replicas)
|
|
wait_for(lambda: self.primary(leader), "synchronous replicas to return")
|
|
wait_for(self.ready, "gateway recovery after standby loss")
|
|
self.verify()
|
|
|
|
def run(self, build):
|
|
try:
|
|
leader = self.start(build)
|
|
self.seed("before-failover")
|
|
new_leader, elapsed = self.failover(leader)
|
|
self.lose_standbys(new_leader)
|
|
self.lose_quorum(new_leader)
|
|
self.verify()
|
|
return {"passed": True, "acknowledged_objects_verified": len(self.writes),
|
|
"failover_seconds": round(elapsed, 3), "gateway_restarted": False,
|
|
"physical_hosts": 1, "dcs_quorum_recovery": True,
|
|
"no_standby_write_refusal": True}
|
|
except Exception:
|
|
logs = self.compose("logs", "--tail", "35", check=False)
|
|
print(logs.stdout, file=sys.stderr)
|
|
raise
|
|
finally:
|
|
self.compose("down", "-v", "--remove-orphans")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--image", help="Existing ObjectStore image; otherwise build this checkout")
|
|
parser.add_argument("--output", type=Path, help="Write a JSON test report")
|
|
args = parser.parse_args()
|
|
if args.output and args.output.exists():
|
|
parser.error("Report already exists")
|
|
try:
|
|
report = Drill(args.image).run(build=not args.image)
|
|
except Exception as error:
|
|
report = {"passed": False, "error": str(error)}
|
|
if args.output:
|
|
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
args.output.write_text(json.dumps(report, indent=2) + "\n")
|
|
raise
|
|
rendered = json.dumps(report, indent=2) + "\n"
|
|
if args.output:
|
|
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
with args.output.open("x") as output:
|
|
output.write(rendered)
|
|
print(rendered, end="")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|