This commit is contained in:
1 parent
b724a21a0d
commit
d73fa2c435
45 files changed
+2733
-226
No files matched your search
@@ -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()
|
||||
Reference in new issue
Block a user