This commit is contained in:
1 parent
b724a21a0d
commit
d73fa2c435
45 files changed
+2733
-226
No files matched your search
@@ -0,0 +1,201 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from readiness_support import Client, Metrics, check_empty_except_marker, check_owner, read_manifest, request_checked, write_json
|
||||
|
||||
|
||||
class Budget:
|
||||
def __init__(self, duration, max_bytes, max_objects, size, rate):
|
||||
self.deadline = time.monotonic() + duration
|
||||
self.max_objects = min(max_objects, max_bytes // size)
|
||||
self.rate = rate
|
||||
self.started = time.monotonic()
|
||||
self.count = 0
|
||||
self.lock = threading.Lock()
|
||||
self.reason = "duration"
|
||||
|
||||
def next(self):
|
||||
with self.lock:
|
||||
if time.monotonic() >= self.deadline:
|
||||
return None
|
||||
if self.count >= self.max_objects:
|
||||
self.reason = "write_budget"
|
||||
return None
|
||||
index = self.count
|
||||
wait = max(0, self.started + index / self.rate - time.monotonic()) if self.rate else 0
|
||||
if time.monotonic() + wait >= self.deadline:
|
||||
return None
|
||||
self.count += 1
|
||||
if wait:
|
||||
time.sleep(wait)
|
||||
return index
|
||||
|
||||
|
||||
def new_manifest(args):
|
||||
identifier = uuid.uuid4().hex
|
||||
return {"format": 1, "id": identifier, "bucket": "readiness-" + identifier,
|
||||
"endpoint": args.endpoint, "region": args.region, "objects": {},
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"complete": False, "retain_all": args.retain_all}
|
||||
|
||||
|
||||
def run(args):
|
||||
output = Path(args.output)
|
||||
output.mkdir(mode=0o700, parents=True, exist_ok=False)
|
||||
manifest = new_manifest(args)
|
||||
client = Client(args.endpoint, args.region, args.timeout)
|
||||
metrics = Metrics()
|
||||
lock = threading.Lock()
|
||||
started = time.monotonic()
|
||||
try:
|
||||
status, _, _ = client.request("HEAD", manifest["bucket"])
|
||||
if status != 404:
|
||||
raise ValueError("new test bucket was not absent; refusing to proceed")
|
||||
if client.request("PUT", manifest["bucket"])[0] != 200:
|
||||
raise ValueError("could not create a dedicated test bucket")
|
||||
write_json(output / "manifest.json", manifest)
|
||||
marker = manifest["id"].encode()
|
||||
if client.request("PUT", manifest["bucket"], ".readiness-owner", marker)[0] != 200:
|
||||
raise ValueError("could not write the test ownership marker")
|
||||
budget = Budget(args.duration, args.max_write_bytes, args.max_objects, args.size, args.writes_per_second)
|
||||
|
||||
def worker():
|
||||
while (index := budget.next()) is not None:
|
||||
key = f"objects/{index}"
|
||||
body = hashlib.shake_256((manifest["id"] + key).encode()).digest(args.size)
|
||||
digest = hashlib.sha256(body).hexdigest()
|
||||
entry = {"size": args.size, "sha256": digest, "acknowledged": False, "deleted": False}
|
||||
with lock:
|
||||
manifest["objects"][key] = entry
|
||||
if not request_checked(client, metrics, "PUT", manifest["bucket"], key, body, {200}):
|
||||
continue
|
||||
entry["acknowledged"] = True
|
||||
request_checked(client, metrics, "GET", manifest["bucket"], key, b"", {200}, digest)
|
||||
request_checked(client, metrics, "HEAD", manifest["bucket"], key, b"", {200})
|
||||
if not args.retain_all and index % 4 != 0:
|
||||
entry["delete_attempted"] = True
|
||||
entry["deleted"] = request_checked(client, metrics, "DELETE", manifest["bucket"], key, b"", {204})
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
futures = [pool.submit(worker) for _ in range(args.concurrency)]
|
||||
for future in futures:
|
||||
future.result()
|
||||
manifest["complete"] = True
|
||||
duration = time.monotonic() - started
|
||||
report = metrics.report(duration)
|
||||
report.update({"seconds": round(duration, 3), "stop_reason": budget.reason,
|
||||
"bucket": manifest["bucket"], "config": vars(args),
|
||||
"attempted_write_bytes": len(manifest["objects"]) * args.size,
|
||||
"acknowledged_objects_retained": sum(entry["acknowledged"] and not entry.get("delete_attempted")
|
||||
for entry in manifest["objects"].values())})
|
||||
write_json(output / "report.json", report)
|
||||
print(json.dumps(report, indent=2))
|
||||
return 1 if any(value["failed"] for value in report["operations"].values()) else 0
|
||||
finally:
|
||||
write_json(output / "manifest.json", manifest)
|
||||
client.close()
|
||||
|
||||
|
||||
def verify_objects(client, metrics, manifest):
|
||||
if not manifest["complete"]:
|
||||
raise ValueError("workload manifest is incomplete; acknowledged-data verification is unavailable")
|
||||
retained = sum(entry["acknowledged"] and not entry.get("delete_attempted")
|
||||
for entry in manifest["objects"].values())
|
||||
if not retained:
|
||||
raise ValueError("manifest has no retained acknowledged objects to verify")
|
||||
failures = 0
|
||||
for key, entry in manifest["objects"].items():
|
||||
success = True
|
||||
if entry["acknowledged"] and not entry.get("delete_attempted"):
|
||||
success = request_checked(client, metrics, "GET", manifest["bucket"], key, b"", {200}, entry["sha256"])
|
||||
elif entry["deleted"]:
|
||||
success = request_checked(client, metrics, "GET", manifest["bucket"], key, b"", {404})
|
||||
failures += not success
|
||||
if failures >= 10:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def cleanup_objects(client, metrics, manifest):
|
||||
failures = 0
|
||||
for key in manifest["objects"]:
|
||||
failures += not request_checked(client, metrics, "DELETE", manifest["bucket"], key, b"", {204})
|
||||
if failures >= 10:
|
||||
return True
|
||||
if failures:
|
||||
return False
|
||||
check_empty_except_marker(client, manifest)
|
||||
removed = request_checked(client, metrics, "DELETE", manifest["bucket"], ".readiness-owner", b"", {204})
|
||||
if removed and not request_checked(client, metrics, "DELETE", manifest["bucket"], None, b"", {204}):
|
||||
request_checked(client, metrics, "PUT", manifest["bucket"], ".readiness-owner", manifest["id"].encode(), {200})
|
||||
return False
|
||||
|
||||
|
||||
def check_or_cleanup(args):
|
||||
manifest = read_manifest(args.manifest)
|
||||
client = Client(args.endpoint or manifest["endpoint"], manifest["region"], args.timeout)
|
||||
metrics = Metrics()
|
||||
started = time.monotonic()
|
||||
try:
|
||||
check_owner(client, manifest)
|
||||
action = verify_objects if args.command == "verify" else cleanup_objects
|
||||
stopped_early = action(client, metrics, manifest)
|
||||
report = metrics.report(time.monotonic() - started)
|
||||
report.update({"command": args.command, "bucket": manifest["bucket"],
|
||||
"manifest_complete": manifest["complete"], "stopped_after_ten_failures": stopped_early})
|
||||
if args.report:
|
||||
write_json(args.report, report)
|
||||
print(json.dumps(report, indent=2))
|
||||
return 1 if any(value["failed"] for value in report["operations"].values()) else 0
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
def arguments():
|
||||
parser = argparse.ArgumentParser(description="Bounded mixed S3 workload and acknowledged-data verification")
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
workload = subparsers.add_parser("run")
|
||||
workload.add_argument("--endpoint", default="http://127.0.0.1:9000")
|
||||
workload.add_argument("--region", default="us-east-1")
|
||||
workload.add_argument("--output", required=True, help="new directory for reports and the ownership manifest")
|
||||
workload.add_argument("--duration", type=float, default=30)
|
||||
workload.add_argument("--size", type=int, default=4096)
|
||||
workload.add_argument("--concurrency", type=int, default=4)
|
||||
workload.add_argument("--writes-per-second", type=float, default=0, help="global PUT rate; 0 means unpaced")
|
||||
workload.add_argument("--max-write-bytes", type=int, default=64 * 1024 * 1024)
|
||||
workload.add_argument("--max-objects", type=int, default=4096)
|
||||
workload.add_argument("--retain-all", action="store_true", help="skip deletes, for interruption/recovery tests")
|
||||
for command in ("verify", "cleanup"):
|
||||
action = subparsers.add_parser(command)
|
||||
action.add_argument("--manifest", required=True)
|
||||
action.add_argument("--endpoint", help="override only for a separately restored test service")
|
||||
action.add_argument("--report")
|
||||
for subparser in (workload, *[subparsers.choices[name] for name in ("verify", "cleanup")]):
|
||||
subparser.add_argument("--timeout", type=float, default=10)
|
||||
args = parser.parse_args()
|
||||
if not .1 <= args.timeout <= 60:
|
||||
parser.error("timeout must be 0.1–60 seconds")
|
||||
if args.command == "run":
|
||||
if not 1 <= args.duration <= 86400 or not 1 <= args.concurrency <= 32:
|
||||
parser.error("duration must be 1–86400 seconds; concurrency must be 1–32")
|
||||
if not 1 <= args.size <= 1048576 or not args.size <= args.max_write_bytes <= 1073741824:
|
||||
parser.error("size must be 1–1048576 bytes; write budget must be at least size and at most 1 GiB")
|
||||
if not 1 <= args.max_objects <= 100000 or not 0 <= args.writes_per_second <= 10000:
|
||||
parser.error("max objects must be 1–100000; write rate must be 0–10000")
|
||||
return args
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
options = arguments()
|
||||
raise SystemExit(run(options) if options.command == "run" else check_or_cleanup(options))
|
||||
except (OSError, ValueError, KeyError) as error:
|
||||
raise SystemExit(f"Readiness check failed: {error}") from error
|
||||
@@ -0,0 +1,217 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import http.client
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
|
||||
def endpoint_origin(value):
|
||||
endpoint = urlsplit(value)
|
||||
if (endpoint.scheme not in ("http", "https") or not endpoint.hostname
|
||||
or endpoint.username or endpoint.password or endpoint.query or endpoint.fragment
|
||||
or endpoint.path not in ("", "/")):
|
||||
raise ValueError("endpoint must be an HTTP(S) origin without credentials")
|
||||
if endpoint.scheme == "http" and endpoint.hostname not in ("localhost", "127.0.0.1", "::1"):
|
||||
raise ValueError("use HTTPS outside localhost")
|
||||
return endpoint
|
||||
|
||||
|
||||
def signed_headers(method, path, body, host, access, secret, region, query=""):
|
||||
now = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
date = now[:8]
|
||||
digest = hashlib.sha256(body).hexdigest()
|
||||
names = "host;x-amz-content-sha256;x-amz-date"
|
||||
canonical = (f"{method}\n{path}\n{query}\nhost:{host}\nx-amz-content-sha256:{digest}\n"
|
||||
f"x-amz-date:{now}\n\n{names}\n{digest}")
|
||||
scope = f"{date}/{region}/s3/aws4_request"
|
||||
message = f"AWS4-HMAC-SHA256\n{now}\n{scope}\n{hashlib.sha256(canonical.encode()).hexdigest()}"
|
||||
key = ("AWS4" + secret).encode()
|
||||
for part in (date, region, "s3", "aws4_request"):
|
||||
key = hmac.new(key, part.encode(), hashlib.sha256).digest()
|
||||
signature = hmac.new(key, message.encode(), hashlib.sha256).hexdigest()
|
||||
return {
|
||||
"Host": host, "x-amz-content-sha256": digest, "x-amz-date": now,
|
||||
"Authorization": (f"AWS4-HMAC-SHA256 Credential={access}/{scope},"
|
||||
f"SignedHeaders={names},Signature={signature}"),
|
||||
}
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, endpoint, region, timeout=10):
|
||||
self.endpoint = endpoint_origin(endpoint)
|
||||
self.region = region
|
||||
self.timeout = timeout
|
||||
self.access = os.environ["S3_ACCESS_KEY"]
|
||||
self.secret = os.environ["S3_SECRET_KEY"]
|
||||
self.local = threading.local()
|
||||
self.connections = set()
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def request(self, method, bucket, key=None, body=b"", limit=1048576, query=None):
|
||||
path = "/" + quote(bucket, safe="")
|
||||
if key is not None:
|
||||
path += "/" + quote(key, safe="/~")
|
||||
encoded_query = "&".join(quote(name, safe="~") + "=" + quote(value, safe="~")
|
||||
for name, value in sorted((query or {}).items()))
|
||||
connection = self.connection()
|
||||
headers = signed_headers(method, path, body, self.endpoint.netloc,
|
||||
self.access, self.secret, self.region, encoded_query)
|
||||
try:
|
||||
connection.request(method, path + ("?" + encoded_query if encoded_query else ""), body, headers)
|
||||
response = connection.getresponse()
|
||||
data = response.read(limit + 1)
|
||||
if len(data) > limit:
|
||||
raise ValueError("response exceeded the test response limit")
|
||||
return response.status, dict(response.getheaders()), data
|
||||
except Exception:
|
||||
connection.close()
|
||||
self.local.connection = None
|
||||
with self.lock:
|
||||
self.connections.discard(connection)
|
||||
raise
|
||||
|
||||
def connection(self):
|
||||
connection = getattr(self.local, "connection", None)
|
||||
if connection is None:
|
||||
cls = http.client.HTTPSConnection if self.endpoint.scheme == "https" else http.client.HTTPConnection
|
||||
connection = cls(self.endpoint.hostname, self.endpoint.port, timeout=self.timeout)
|
||||
self.local.connection = connection
|
||||
with self.lock:
|
||||
self.connections.add(connection)
|
||||
return connection
|
||||
|
||||
def close(self):
|
||||
for connection in self.connections:
|
||||
connection.close()
|
||||
|
||||
|
||||
class Metrics:
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self.operations = {}
|
||||
self.errors = []
|
||||
|
||||
def record(self, operation, seconds, success, status, sent, received, error=None):
|
||||
with self.lock:
|
||||
stats = self.operations.setdefault(operation, {
|
||||
"attempts": 0, "succeeded": 0, "failed": 0, "seconds": 0,
|
||||
"request_payload_bytes": 0, "response_payload_bytes": 0,
|
||||
"successful_request_payload_bytes": 0, "successful_response_payload_bytes": 0,
|
||||
"status_counts": {}, "histogram": {},
|
||||
})
|
||||
stats["attempts"] += 1
|
||||
stats["succeeded" if success else "failed"] += 1
|
||||
stats["seconds"] += seconds
|
||||
stats["request_payload_bytes"] += sent
|
||||
stats["response_payload_bytes"] += received
|
||||
if success:
|
||||
stats["successful_request_payload_bytes"] += sent
|
||||
stats["successful_response_payload_bytes"] += received
|
||||
code = str(status) if status is not None else "transport"
|
||||
stats["status_counts"][code] = stats["status_counts"].get(code, 0) + 1
|
||||
bucket = math.ceil(math.log(max(seconds * 1000, .001), 1.1))
|
||||
stats["histogram"][bucket] = stats["histogram"].get(bucket, 0) + 1
|
||||
if error and len(self.errors) < 20:
|
||||
self.errors.append({"operation": operation, "error": error})
|
||||
|
||||
def report(self, duration):
|
||||
output = {}
|
||||
for operation, stats in self.operations.items():
|
||||
item = {key: value for key, value in stats.items() if key not in ("histogram", "seconds")}
|
||||
item["successful_requests_per_second"] = round(stats["succeeded"] / max(duration, .001), 3)
|
||||
item["successful_upload_mib_per_second"] = round(stats["successful_request_payload_bytes"] / max(duration, .001) / 1048576, 3)
|
||||
item["successful_download_mib_per_second"] = round(stats["successful_response_payload_bytes"] / max(duration, .001) / 1048576, 3)
|
||||
item["mean_ms"] = round(stats["seconds"] * 1000 / stats["attempts"], 3)
|
||||
for label, fraction in (("p50_ms_upper", .5), ("p95_ms_upper", .95), ("p99_ms_upper", .99)):
|
||||
target = math.ceil(stats["attempts"] * fraction)
|
||||
seen = 0
|
||||
for bucket, count in sorted(stats["histogram"].items()):
|
||||
seen += count
|
||||
if seen >= target:
|
||||
item[label] = round(1.1 ** bucket, 3)
|
||||
break
|
||||
output[operation] = item
|
||||
return {"operations": output, "error_samples": self.errors,
|
||||
"latency_note": "All attempts; percentile histogram upper bounds have at most 10% bin width."}
|
||||
|
||||
|
||||
def request_checked(client, metrics, method, bucket, key, body, expected, digest=None):
|
||||
started = time.perf_counter()
|
||||
status = None
|
||||
received = 0
|
||||
error = None
|
||||
try:
|
||||
status, headers, data = client.request(method, bucket, key, body)
|
||||
received = len(data)
|
||||
if status not in expected:
|
||||
error = f"HTTP {status}"
|
||||
elif digest is not None and hashlib.sha256(data).hexdigest() != digest:
|
||||
error = "response checksum mismatch"
|
||||
return error is None
|
||||
except Exception as failure:
|
||||
error = type(failure).__name__
|
||||
return False
|
||||
finally:
|
||||
metrics.record(method, time.perf_counter() - started, error is None,
|
||||
status, len(body), received, error)
|
||||
|
||||
|
||||
def write_json(path, value):
|
||||
path = Path(path)
|
||||
temporary = path.with_name(path.name + ".tmp")
|
||||
with open(temporary, "w", encoding="utf-8", opener=lambda p, flags: os.open(p, flags, 0o600)) as output:
|
||||
json.dump(value, output, indent=2, sort_keys=True)
|
||||
output.write("\n")
|
||||
output.flush()
|
||||
os.fsync(output.fileno())
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
def read_manifest(path):
|
||||
path = Path(path)
|
||||
if path.stat().st_size > 32 * 1024 * 1024:
|
||||
raise ValueError("manifest is too large")
|
||||
value = json.loads(path.read_text())
|
||||
identifier = value["id"]
|
||||
if (value.get("format") != 1 or len(identifier) != 32
|
||||
or any(char not in "0123456789abcdef" for char in identifier)
|
||||
or value["bucket"] != "readiness-" + identifier):
|
||||
raise ValueError("invalid test ownership manifest")
|
||||
if len(value["objects"]) > 100000:
|
||||
raise ValueError("too many manifest objects")
|
||||
for key, entry in value["objects"].items():
|
||||
if not key.startswith("objects/") or not key[8:].isdigit():
|
||||
raise ValueError("invalid test object key")
|
||||
if not 1 <= entry["size"] <= 1048576:
|
||||
raise ValueError("invalid test object size")
|
||||
if len(entry["sha256"]) != 64:
|
||||
raise ValueError("invalid test object checksum")
|
||||
endpoint_origin(value["endpoint"])
|
||||
return value
|
||||
|
||||
|
||||
def check_owner(client, manifest):
|
||||
status, _, body = client.request("GET", manifest["bucket"], ".readiness-owner")
|
||||
if status != 200 or body != manifest["id"].encode():
|
||||
raise ValueError("test ownership marker mismatch; refusing to access or delete objects")
|
||||
|
||||
|
||||
def check_empty_except_marker(client, manifest):
|
||||
status, _, body = client.request("GET", manifest["bucket"], query={"list-type": "2", "max-keys": "2"})
|
||||
if status != 200:
|
||||
raise ValueError("could not verify test bucket contents before removal")
|
||||
try:
|
||||
root = ET.fromstring(body)
|
||||
except ET.ParseError as error:
|
||||
raise ValueError("invalid bucket listing; refusing to remove marker") from error
|
||||
keys = [element.text for element in root.findall("{*}Contents/{*}Key")]
|
||||
truncated = root.findtext("{*}IsTruncated")
|
||||
if root.tag.rsplit("}", 1)[-1] != "ListBucketResult" or keys != [".readiness-owner"] or truncated != "false":
|
||||
raise ValueError("bucket has unlisted objects; preserving bucket and ownership marker")
|
||||
@@ -0,0 +1,217 @@
|
||||
#!/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()
|
||||
@@ -4,4 +4,8 @@ cd "$(dirname "$0")/.."
|
||||
project="objectstore-metadata-test-$$"
|
||||
compose() { docker compose -p "$project" -f tests/metadata/compose.yaml "$@"; }
|
||||
trap 'compose down -v --remove-orphans >/dev/null 2>&1 || true' EXIT
|
||||
compose up --build --abort-on-container-exit --exit-code-from check check
|
||||
if [ -n "${OBJECTSTORE_TEST_IMAGE:-}" ]; then
|
||||
compose up --no-build --abort-on-container-exit --exit-code-from check check
|
||||
else
|
||||
compose up --build --abort-on-container-exit --exit-code-from check check
|
||||
fi
|
||||
@@ -0,0 +1,208 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import json
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
import xml.etree.ElementTree as ET
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from readiness import Budget, check_or_cleanup, run
|
||||
from readiness_support import Metrics, endpoint_origin, read_manifest
|
||||
|
||||
|
||||
class FakeStore(BaseHTTPRequestHandler):
|
||||
objects = {}
|
||||
bucket = None
|
||||
corrupt = False
|
||||
inject_on_marker_delete = False
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def do_HEAD(self):
|
||||
self.respond(200 if self.path in self.objects or self.path == self.bucket else 404)
|
||||
|
||||
def do_PUT(self):
|
||||
data = self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
if self.path.count("/") == 1:
|
||||
type(self).bucket = self.path
|
||||
else:
|
||||
self.objects[self.path] = data
|
||||
self.respond(200)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.partition("?")[0] == self.bucket:
|
||||
root = ET.Element("ListBucketResult")
|
||||
ET.SubElement(root, "IsTruncated").text = "false"
|
||||
for path in sorted(self.objects):
|
||||
entry = ET.SubElement(root, "Contents")
|
||||
ET.SubElement(entry, "Key").text = path[len(self.bucket) + 1:]
|
||||
self.respond(200, ET.tostring(root))
|
||||
return
|
||||
data = self.objects.get(self.path)
|
||||
if self.corrupt and "/objects/" in self.path and data is not None:
|
||||
data = b"corrupt"
|
||||
self.respond(200 if data is not None else 404, data or b"")
|
||||
|
||||
def do_DELETE(self):
|
||||
if self.path == self.bucket:
|
||||
if self.objects:
|
||||
self.respond(409)
|
||||
return
|
||||
type(self).bucket = None
|
||||
else:
|
||||
self.objects.pop(self.path, None)
|
||||
if self.inject_on_marker_delete and self.path.endswith("/.readiness-owner"):
|
||||
self.objects[self.bucket + "/racing-object"] = b"preserve"
|
||||
type(self).inject_on_marker_delete = False
|
||||
self.respond(204)
|
||||
|
||||
def respond(self, status, body=b""):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
class ReadinessTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
FakeStore.objects = {}
|
||||
FakeStore.bucket = None
|
||||
FakeStore.corrupt = False
|
||||
FakeStore.inject_on_marker_delete = False
|
||||
self.server = ThreadingHTTPServer(("127.0.0.1", 0), FakeStore)
|
||||
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
||||
self.thread.start()
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.output = Path(self.temp.name) / "run"
|
||||
self.endpoint = "http://127.0.0.1:" + str(self.server.server_port)
|
||||
self.credentials = patch.dict("os.environ", {"S3_ACCESS_KEY": "test", "S3_SECRET_KEY": "test-secret"})
|
||||
self.credentials.start()
|
||||
|
||||
def tearDown(self):
|
||||
self.credentials.stop()
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
self.thread.join()
|
||||
self.temp.cleanup()
|
||||
|
||||
def workload(self, retain=False):
|
||||
args = argparse.Namespace(command="run", output=str(self.output), endpoint=self.endpoint,
|
||||
region="us-east-1", timeout=1, duration=2, max_write_bytes=4096,
|
||||
max_objects=100, size=1024, concurrency=2, writes_per_second=0,
|
||||
retain_all=retain)
|
||||
with patch("builtins.print"):
|
||||
return run(args)
|
||||
|
||||
def action(self, command):
|
||||
args = argparse.Namespace(command=command, manifest=str(self.output / "manifest.json"),
|
||||
endpoint=None, timeout=1, report=None)
|
||||
with patch("builtins.print"):
|
||||
return check_or_cleanup(args)
|
||||
|
||||
def test_budget_integrity_and_owned_cleanup(self):
|
||||
self.assertEqual(self.workload(), 0)
|
||||
report = json.loads((self.output / "report.json").read_text())
|
||||
self.assertEqual(report["attempted_write_bytes"], 4096)
|
||||
self.assertEqual(report["operations"]["PUT"]["succeeded"], 4)
|
||||
self.assertEqual(report["operations"]["DELETE"]["succeeded"], 3)
|
||||
self.assertEqual(self.action("verify"), 0)
|
||||
self.assertEqual(self.action("cleanup"), 0)
|
||||
self.assertEqual(FakeStore.objects, {})
|
||||
|
||||
def test_corruption_and_missing_acknowledged_object_fail(self):
|
||||
self.assertEqual(self.workload(retain=True), 0)
|
||||
FakeStore.corrupt = True
|
||||
self.assertEqual(self.action("verify"), 1)
|
||||
FakeStore.corrupt = False
|
||||
key = next(key for key in FakeStore.objects if "/objects/" in key)
|
||||
del FakeStore.objects[key]
|
||||
self.assertEqual(self.action("verify"), 1)
|
||||
|
||||
def test_cleanup_refuses_wrong_marker(self):
|
||||
self.workload()
|
||||
marker = FakeStore.bucket + "/.readiness-owner"
|
||||
FakeStore.objects[marker] = b"someone-else"
|
||||
before = dict(FakeStore.objects)
|
||||
with self.assertRaisesRegex(ValueError, "ownership marker"):
|
||||
self.action("cleanup")
|
||||
self.assertEqual(before, FakeStore.objects)
|
||||
|
||||
def test_cleanup_does_not_delete_unlisted_objects(self):
|
||||
self.workload()
|
||||
unknown = FakeStore.bucket + "/not-created-by-the-test"
|
||||
FakeStore.objects[unknown] = b"preserve"
|
||||
marker = FakeStore.objects[FakeStore.bucket + "/.readiness-owner"]
|
||||
with self.assertRaisesRegex(ValueError, "unlisted objects"):
|
||||
self.action("cleanup")
|
||||
self.assertEqual(FakeStore.objects[unknown], b"preserve")
|
||||
self.assertEqual(FakeStore.objects[FakeStore.bucket + "/.readiness-owner"], marker)
|
||||
del FakeStore.objects[unknown]
|
||||
self.assertEqual(self.action("cleanup"), 0)
|
||||
|
||||
def test_manifest_rejects_arbitrary_bucket(self):
|
||||
self.workload()
|
||||
path = self.output / "manifest.json"
|
||||
manifest = json.loads(path.read_text())
|
||||
manifest["bucket"] = "important-data"
|
||||
path.write_text(json.dumps(manifest))
|
||||
with self.assertRaisesRegex(ValueError, "ownership manifest"):
|
||||
read_manifest(path)
|
||||
|
||||
def test_cleanup_restores_marker_if_bucket_changes(self):
|
||||
self.workload()
|
||||
marker = FakeStore.objects[FakeStore.bucket + "/.readiness-owner"]
|
||||
FakeStore.inject_on_marker_delete = True
|
||||
self.assertEqual(self.action("cleanup"), 1)
|
||||
self.assertEqual(FakeStore.objects[FakeStore.bucket + "/.readiness-owner"], marker)
|
||||
self.assertEqual(FakeStore.objects[FakeStore.bucket + "/racing-object"], b"preserve")
|
||||
del FakeStore.objects[FakeStore.bucket + "/racing-object"]
|
||||
self.assertEqual(self.action("cleanup"), 0)
|
||||
|
||||
def test_incomplete_manifest_cannot_claim_verification(self):
|
||||
self.workload()
|
||||
path = self.output / "manifest.json"
|
||||
manifest = json.loads(path.read_text())
|
||||
manifest["complete"] = False
|
||||
path.write_text(json.dumps(manifest))
|
||||
with self.assertRaisesRegex(ValueError, "incomplete"):
|
||||
self.action("verify")
|
||||
|
||||
def test_maximum_manifest_can_be_reopened(self):
|
||||
self.workload()
|
||||
path = self.output / "manifest.json"
|
||||
manifest = json.loads(path.read_text())
|
||||
entry = next(iter(manifest["objects"].values()))
|
||||
manifest["objects"] = {"objects/" + str(index): entry for index in range(100000)}
|
||||
with path.open("w") as stream:
|
||||
json.dump(manifest, stream, indent=2)
|
||||
self.assertGreater(path.stat().st_size, 16 * 1024 * 1024)
|
||||
self.assertEqual(len(read_manifest(path)["objects"]), 100000)
|
||||
|
||||
def test_transport_policy_and_histogram(self):
|
||||
for endpoint in ("http://example.com", "http://user:pass@localhost", "https://example.com/path"):
|
||||
with self.assertRaises(ValueError):
|
||||
endpoint_origin(endpoint)
|
||||
metrics = Metrics()
|
||||
for _ in range(9):
|
||||
metrics.record("PUT", .01, True, 200, 100, 0)
|
||||
metrics.record("PUT", .1, False, 503, 100, 0, "HTTP 503")
|
||||
report = metrics.report(2)["operations"]["PUT"]
|
||||
self.assertEqual(report["failed"], 1)
|
||||
self.assertEqual(report["successful_requests_per_second"], 4.5)
|
||||
self.assertGreaterEqual(report["p95_ms_upper"], 100)
|
||||
self.assertLess(report["p95_ms_upper"], 110)
|
||||
|
||||
def test_rate_reservation_does_not_consume_an_unstarted_write(self):
|
||||
budget = Budget(1, 2048, 2, 1024, .1)
|
||||
self.assertEqual(budget.next(), 0)
|
||||
self.assertIsNone(budget.next())
|
||||
self.assertEqual(budget.count, 1)
|
||||
self.assertEqual(budget.reason, "duration")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,230 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from readiness_support import write_json
|
||||
|
||||
|
||||
LABEL = "cloud.lunarsky.objectstore.readiness"
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
class Drill:
|
||||
def __init__(self, image, output):
|
||||
self.image = image
|
||||
self.output = output
|
||||
self.identifier = uuid.uuid4().hex
|
||||
self.prefix = "objectstore-recovery-" + self.identifier
|
||||
self.containers = []
|
||||
self.volumes = []
|
||||
self.environment = dict(os.environ, S3_ACCESS_KEY="Readiness" + secrets.token_hex(8),
|
||||
S3_SECRET_KEY=secrets.token_hex(32))
|
||||
|
||||
def docker(self, *args, **kwargs):
|
||||
return subprocess.run(["docker", *args], check=True, env=self.environment,
|
||||
timeout=90, **kwargs)
|
||||
|
||||
def create_volume(self, suffix):
|
||||
volume = self.prefix + "-" + suffix
|
||||
self.docker("volume", "create", "--label", LABEL + "=" + self.identifier,
|
||||
volume, stdout=subprocess.DEVNULL)
|
||||
self.volumes.append(volume)
|
||||
return volume
|
||||
|
||||
def start_service(self, suffix, volume):
|
||||
name = self.prefix + "-" + suffix
|
||||
self.containers.append(name)
|
||||
with socket.socket() as reserved:
|
||||
reserved.bind(("127.0.0.1", 0))
|
||||
port = reserved.getsockname()[1]
|
||||
self.docker("run", "-d", "--name", name, "--label", LABEL + "=" + self.identifier,
|
||||
"--memory", "384m", "--cpus", "2", "--cap-drop", "ALL",
|
||||
"--security-opt", "no-new-privileges:true", "--publish", f"127.0.0.1:{port}:9000",
|
||||
"--mount", f"type=volume,src={volume},dst=/data",
|
||||
"-e", "S3_ACCESS_KEY", "-e", "S3_SECRET_KEY", "-e", "S3_BUCKET=objects",
|
||||
"-e", "MAX_TOTAL_BYTES=67108864", "-e", "MAX_OBJECT_BYTES=1048576",
|
||||
"-e", "JAVA_TOOL_OPTIONS=-XX:+UseSerialGC -Xms32m -Xmx192m", self.image,
|
||||
stdout=subprocess.DEVNULL)
|
||||
endpoint = self.endpoint(name)
|
||||
self.wait_ready(endpoint)
|
||||
return name, endpoint
|
||||
|
||||
def endpoint(self, name):
|
||||
mapping = self.docker("port", name, "9000/tcp", capture_output=True, text=True).stdout.strip()
|
||||
if not mapping.startswith("127.0.0.1:") or "\n" in mapping:
|
||||
raise ValueError("test container port must be loopback-only")
|
||||
return "http://" + mapping
|
||||
|
||||
def wait_ready(self, endpoint):
|
||||
deadline = time.monotonic() + 40
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(endpoint + "/ready", timeout=1) as response:
|
||||
if response.status == 200:
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(.2)
|
||||
raise RuntimeError("test service did not become ready")
|
||||
|
||||
def command(self, *args):
|
||||
return [sys.executable, str(ROOT / "scripts/readiness.py"), *args]
|
||||
|
||||
def verify(self, manifest, endpoint, filename):
|
||||
subprocess.run(self.command("verify", "--manifest", str(manifest), "--endpoint", endpoint,
|
||||
"--report", str(self.output / filename)), env=self.environment,
|
||||
check=True, timeout=120, stdout=subprocess.DEVNULL)
|
||||
|
||||
def baseline(self, endpoint):
|
||||
workload = self.output / "baseline"
|
||||
subprocess.run(self.command("run", "--endpoint", endpoint, "--output", str(workload),
|
||||
"--duration", "3", "--writes-per-second", "20", "--max-write-bytes", "1048576"),
|
||||
env=self.environment, check=True, timeout=30, stdout=subprocess.DEVNULL)
|
||||
manifest = workload / "manifest.json"
|
||||
self.verify(manifest, endpoint, "baseline-verification.json")
|
||||
subprocess.run(self.command("cleanup", "--manifest", str(manifest)), env=self.environment,
|
||||
check=True, timeout=30, stdout=subprocess.DEVNULL)
|
||||
|
||||
def seed_before_crash(self, endpoint):
|
||||
workload = self.output / "before-crash"
|
||||
subprocess.run(self.command("run", "--endpoint", endpoint, "--output", str(workload),
|
||||
"--duration", "10", "--max-objects", "20", "--concurrency", "1",
|
||||
"--max-write-bytes", "81920", "--retain-all"),
|
||||
env=self.environment, check=True, timeout=30, stdout=subprocess.DEVNULL)
|
||||
report = json.loads((workload / "report.json").read_text())
|
||||
if report["acknowledged_objects_retained"] != 20:
|
||||
raise RuntimeError("pre-crash seed did not acknowledge all twenty objects")
|
||||
manifest = workload / "manifest.json"
|
||||
self.verify(manifest, endpoint, "before-crash-verification.json")
|
||||
return manifest
|
||||
|
||||
def workload_and_restart(self, container, endpoint):
|
||||
workload = self.output / "workload"
|
||||
command = self.command("run", "--endpoint", endpoint, "--output", str(workload),
|
||||
"--duration", "10", "--max-write-bytes", "2097152", "--max-objects", "512",
|
||||
"--size", "4096", "--concurrency", "2", "--writes-per-second", "30",
|
||||
"--timeout", "1", "--retain-all")
|
||||
with open(self.output / "workload.log", "w") as log:
|
||||
process = subprocess.Popen(command, env=self.environment, stdout=log, stderr=subprocess.STDOUT)
|
||||
try:
|
||||
deadline = time.monotonic() + 5
|
||||
while not (workload / "manifest.json").exists():
|
||||
if process.poll() is not None or time.monotonic() >= deadline:
|
||||
raise RuntimeError("workload did not initialize")
|
||||
time.sleep(.1)
|
||||
time.sleep(2)
|
||||
self.docker("kill", "--signal", "KILL", container, stdout=subprocess.DEVNULL)
|
||||
time.sleep(1)
|
||||
self.docker("start", container, stdout=subprocess.DEVNULL)
|
||||
if self.endpoint(container) != endpoint:
|
||||
raise RuntimeError("test endpoint changed during restart")
|
||||
self.wait_ready(endpoint)
|
||||
result = process.wait(timeout=40)
|
||||
if result != 1:
|
||||
raise RuntimeError("interrupted workload did not report the expected request failures")
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=10)
|
||||
report = json.loads((workload / "report.json").read_text())
|
||||
if report["acknowledged_objects_retained"] < 10:
|
||||
raise RuntimeError("too few acknowledged objects to validate recovery")
|
||||
self.verify(workload / "manifest.json", endpoint, "restart-verification.json")
|
||||
return workload / "manifest.json"
|
||||
|
||||
def archive_and_restore(self, source, target):
|
||||
archive = self.output / "snapshot.tar"
|
||||
export_name = self.prefix + "-export"
|
||||
restore_name = self.prefix + "-import"
|
||||
self.containers.extend((export_name, restore_name))
|
||||
common = ["run", "--label", LABEL + "=" + self.identifier, "--network", "none", "--read-only",
|
||||
"--security-opt", "no-new-privileges:true", "--user", "0"]
|
||||
with open(archive, "xb") as stream:
|
||||
self.docker(*common, "--name", export_name, "--mount", f"type=volume,src={source},dst=/snapshot,readonly",
|
||||
"--entrypoint", "tar", self.image, "-C", "/snapshot", "-cf", "-", ".", stdout=stream)
|
||||
digest = hashlib.sha256(archive.read_bytes()).hexdigest()
|
||||
with open(archive, "rb") as stream:
|
||||
self.docker(*common, "--name", restore_name, "--interactive", "--mount", f"type=volume,src={target},dst=/snapshot",
|
||||
"--entrypoint", "sh", self.image, "-c",
|
||||
'test -z "$(find /snapshot -mindepth 1 -print -quit)" && tar -C /snapshot -xpf -',
|
||||
stdin=stream, stdout=subprocess.DEVNULL)
|
||||
return {"sha256": digest, "bytes": archive.stat().st_size}
|
||||
|
||||
def cleanup(self):
|
||||
failures = []
|
||||
for kind, names in (("container", self.containers), ("volume", self.volumes)):
|
||||
for name in names:
|
||||
try:
|
||||
info = subprocess.run(["docker", kind, "inspect", name], capture_output=True,
|
||||
text=True, timeout=30)
|
||||
if info.returncode and "No such" in info.stderr:
|
||||
continue
|
||||
info.check_returncode()
|
||||
value = json.loads(info.stdout)[0]
|
||||
labels = value.get("Config", {}).get("Labels", {}) if kind == "container" else value.get("Labels", {})
|
||||
if labels.get(LABEL) != self.identifier:
|
||||
raise ValueError("ownership label mismatch")
|
||||
args = [kind, "rm", "-f", name] if kind == "container" else [kind, "rm", name]
|
||||
self.docker(*args, stdout=subprocess.DEVNULL)
|
||||
except (subprocess.SubprocessError, ValueError) as error:
|
||||
failures.append(name + ": " + str(error))
|
||||
if failures:
|
||||
raise RuntimeError("Test resource cleanup failed: " + "; ".join(failures))
|
||||
|
||||
def run(self):
|
||||
image_id = self.docker("image", "inspect", "--format", "{{.Id}}", self.image,
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
summary = {"image": self.image, "image_id": image_id, "scope": "single-node local disposable Docker",
|
||||
"physical_power_loss_tested": False, "offsite_restore_tested": False, "passed": False}
|
||||
try:
|
||||
source = self.create_volume("source-data")
|
||||
target = self.create_volume("restore-data")
|
||||
container, endpoint = self.start_service("source", source)
|
||||
self.baseline(endpoint)
|
||||
before_crash = self.seed_before_crash(endpoint)
|
||||
manifest = self.workload_and_restart(container, endpoint)
|
||||
self.verify(before_crash, endpoint, "pre-crash-restart-verification.json")
|
||||
summary["pre_crash_acknowledged_objects_verified"] = 20
|
||||
self.docker("stop", "--time", "15", container, stdout=subprocess.DEVNULL)
|
||||
summary["snapshot"] = self.archive_and_restore(source, target)
|
||||
_, restored = self.start_service("restored", target)
|
||||
self.verify(manifest, restored, "restore-verification.json")
|
||||
self.verify(before_crash, restored, "pre-crash-restore-verification.json")
|
||||
summary["passed"] = True
|
||||
finally:
|
||||
try:
|
||||
summary["resources_removed"] = False
|
||||
self.cleanup()
|
||||
summary["resources_removed"] = True
|
||||
finally:
|
||||
summary["passed"] = summary["passed"] and summary["resources_removed"]
|
||||
write_json(self.output / "summary.json", summary)
|
||||
print(json.dumps(summary, indent=2))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Disposable container crash and cold-restore integrity drill")
|
||||
parser.add_argument("--image", required=True, help="already-built local ObjectStore image")
|
||||
parser.add_argument("--output", required=True, help="new directory; retained reports and snapshot use at most about 8 MiB")
|
||||
args = parser.parse_args()
|
||||
output = Path(args.output).resolve()
|
||||
output.mkdir(mode=0o700, parents=True, exist_ok=False)
|
||||
Drill(args.image, output).run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -7,6 +7,7 @@ mkdir -p out/classes
|
||||
javac --release 21 --add-modules jdk.httpserver,java.net.http -cp lib/hash4j-0.30.0.jar -d out/classes \
|
||||
src/cloud/lunarsky/store/*.java test/cloud/lunarsky/store/*.java
|
||||
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.StoreTest
|
||||
java -Xmx32m --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.LargeObjectTest
|
||||
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.DiskBucketNamesTest
|
||||
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ConditionalEditTest
|
||||
java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ClusterRepairCliTest
|
||||
|
||||
Reference in new issue
Block a user