Add attended group Standby roll command and failure witnesses
Journal each operator transaction and AWS call under a durable group lock. Prepare and apply through the root maintenance verbs, then return only after current-process admission. Bind defensive return hooks to a separate action journal and retain failed or uncertain members for the operator. Cover crashes, lost responses, rollback, shared outages and all eight required mutations with an offline provider and box. No live account calls were made.
2 files changed,
+1,890
−0
scripts/region-group-roll.py+1,086 −0scripts/region_group_roll_test.py+804 −0
Intent
Human
<task-notification> <task-id>bpy8y5l3u</task-id> <tool-use-id>toolu_01PZswNrCSP27Xz6f7VduF7y</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/bpy8y5l3u.output</output-file> <status>completed</status> <summary>Background command ".superpowers/sdd/2026-11-04-region-ha-p3b-group/run-astra.sh b2bf" completed (exit code 0)</summary> </task-notification>
diff --git a/scripts/region-group-roll.py b/scripts/region-group-roll.py| new file mode 100755 |
| index 000000000..67725d2a5 |
| --- /dev/null |
| +++ b/scripts/region-group-roll.py |
| @@ -0,0 +1,1086 @@ |
| +#!/usr/bin/env python3 |
| +"""Attended, serialized maintenance of one Auto Scaling group member. |
| + |
| +Run as root on the shared operator host. All operators must use the same |
| +state_dir. Keep that directory and its journals when reconnecting. A missing |
| +or damaged record refuses recovery. No service, timer or cron may run this tool. |
| + |
| +The JSON config has exactly these keys: deployment, account, region, group, |
| +group_arn, hook, target_groups (two ARNs), bucket, document, state_dir, profile. |
| +The document must accept a command parameter and run it as root. The command |
| +checks its uid; it never assumes that Session Manager preferences grant root. |
| +Use an approved NonInteractiveCommands document with runAsElevated=true. |
| + |
| +Before the first roll, place a root-owned 0600 provider-observation.json in the |
| +printed group directory. Its exact fields are v=1, group_arn, hook, template |
| +(the described LaunchTemplate object), and documented_no_hook=true. This is |
| +the controller's record of the approved, unchanged-member Standby observation. |
| +It is not made by this command. A provider-divergence.json file blocks further |
| +rolls until the controller resolves the provider contract and removes the file. |
| + |
| +plan reads cloud and root status without preparing artifacts or changing the |
| +group. roll prepares the signed artifact, enters Standby, applies, verifies and |
| +returns. resume reconstructs the transaction from its journal and fresh reads. |
| +rollback restores the recorded old artifact in Standby, using a new rollback |
| +permit in the same transaction. return performs only the return and cleanup |
| +steps. status prints the saved transaction without contacting AWS. |
| + |
| +An uncertain consumed box action stays in Standby for operator investigation. |
| +The command never replays it, restarts a unit by hand, terminates a member, |
| +sends ABANDON, or sets desired capacity. A Standby wait alerts after 15 minutes. |
| +""" |
| +import argparse |
| +import base64 |
| +from contextlib import contextmanager |
| +from datetime import datetime, timezone |
| +import fcntl |
| +import hashlib |
| +import json |
| +import os |
| +from pathlib import Path |
| +import pty |
| +import re |
| +import select |
| +import shlex |
| +import signal |
| +import stat |
| +import subprocess |
| +import sys |
| +import tempfile |
| +import time |
| +import tty |
| +import uuid |
| + |
| + |
| +# All operator copy lives here; the controller owns the final copy pass. |
| +TEXT = { |
| + "help": __doc__, |
| + "config": "Path to the deployment JSON config.", |
| + "attended": "Name the person attending this run when no terminal is attached.", |
| + "member": "Exact instance ID to maintain.", |
| + "sha": "Verified release artifact SHA256 for this architecture.", |
| + "transaction": "Transaction ID from the saved journal.", |
| + "plan": "Read readiness and list refusals. Change no group or box state.", |
| + "roll": "Roll one member to the named artifact.", |
| + "rollback": "Restore this transaction's old artifact while in Standby.", |
| + "resume": "Resume from the durable journal and current provider state.", |
| + "return": "Return an already restarted and admitted member.", |
| + "status": "Read the saved journal without contacting AWS.", |
| + "line": "{phase}: {detail}", |
| + "journal": "Journal: {path}", |
| + "ready": "Ready for attended maintenance.", |
| + "sequence": "Prepare, lower minimum, enter Standby, verify deregistration, permit, apply, verify, return, restore minimum, revoke.", |
| + "refused": "Refused: {reason}", |
| + "alert": "ALERT: {reason}. Keep the member and transaction for the operator.", |
| + "fail": "FAIL: {reason}. Stop further rolls and resolve the provider contract.", |
| + "done": "Member returned and permit revoked.", |
| + "config_invalid": "Invalid deployment config", |
| + "root": "Run on the authorized root operator host", |
| + "attended_required": "A terminal or --attended-by is required", |
| + "unsafe_state": "State storage is missing, unsafe or damaged", |
| + "busy": "Another operator holds the group lock", |
| + "active": "An unfinished transaction already exists", |
| + "record": "The transaction record is missing or corrupt", |
| + "scope": "The configured group, account, region or target groups do not match", |
| + "observation": "A matching approved no-hook provider observation is required", |
| + "blocked": "Provider divergence blocks new rolls", |
| + "shape": "The group must have min=desired=max=N and N must be at least two", |
| + "members": "The member set or capacity changed outside this transaction", |
| + "offline": "A required member is not Online in Session Manager", |
| + "peer": "Every peer must be InService and healthy in both target groups", |
| + "identity": "Root status identity does not match this transaction", |
| + "admission": "Current-process health, admission or role publication is incomplete", |
| + "process": "The expected artifact and a new edge process are required", |
| + "permit": "The permit is not accepted, unconsumed and bound to this action", |
| + "prepare": "Signed artifact preparation or preserved configuration verification failed", |
| + "held": "The member must remain in Standby with both target groups deregistered", |
| + "timeout": "The 15-minute Standby wait expired", |
| + "uncertain_action": "The consumed box action has no verified completion", |
| + "return_intent": "A durable current-process return intent is required", |
| + "return_failed": "Admission or API access was lost during a return hook", |
| + "return_attempts": "The bounded return completion attempts are exhausted", |
| + "return_phase": "The provider has not completed this member's return", |
| + "activity": "The ExitStandby activity cannot be bound to this transaction", |
| + "hook": "The immutable launch hook must have a 900-second ABANDON default", |
| + "remote": "The Session Manager command has no successful framed result", |
| + "api": "An AWS response is unavailable or invalid", |
| + "rollback_refused": "Rollback requires this transaction's completed apply in Standby", |
| + "unsupported": "Unsupported operation", |
| + "divergence": "The provider used a return hook. The member is safe; further rolls are blocked.", |
| +} |
| + |
| +SHA = re.compile(r"[0-9a-f]{64}\Z") |
| +IID = re.compile(r"i-(?:[0-9a-f]{8}|[0-9a-f]{17})\Z") |
| +TX = re.compile(r"[a-zA-Z0-9_-]{1,80}\Z") |
| +WAIT = 900 |
| + |
| + |
| +class Refusal(Exception): |
| + pass |
| + |
| + |
| +class FailedProbe(Refusal): |
| + pass |
| + |
| + |
| +class Uncertain(Exception): |
| + def __init__(self, message, **details): |
| + super().__init__(message) |
| + self.details = details |
| + |
| + |
| +def require(condition, key): |
| + if not condition: |
| + raise Refusal(TEXT[key]) |
| + |
| + |
| +def stamp(seconds): |
| + return datetime.fromtimestamp(seconds, timezone.utc).isoformat().replace("+00:00", "Z") |
| + |
| + |
| +def instant(value): |
| + require(isinstance(value, str) and value.endswith("Z"), "admission") |
| + try: |
| + return datetime.fromisoformat(value[:-1] + "+00:00").timestamp() |
| + except ValueError as exc: |
| + raise Refusal(TEXT["admission"]) from exc |
| + |
| + |
| +def unique_object(pairs): |
| + result = {} |
| + for key, value in pairs: |
| + require(key not in result, "record") |
| + result[key] = value |
| + return result |
| + |
| + |
| +def decode(raw): |
| + try: |
| + return json.loads(raw, object_pairs_hook=unique_object, |
| + parse_constant=lambda _: require(False, "record")) |
| + except (ValueError, UnicodeError) as exc: |
| + raise Refusal(TEXT["record"]) from exc |
| + |
| + |
| +def encoded(value): |
| + return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() |
| + |
| + |
| +def validate_config(c): |
| + keys = {"deployment", "account", "region", "group", "group_arn", "hook", |
| + "target_groups", "bucket", "document", "state_dir", "profile"} |
| + require(isinstance(c, dict) and set(c) == keys, "config_invalid") |
| + for key in keys - {"target_groups"}: |
| + require(isinstance(c[key], str) and 0 < len(c[key]) <= 1024, "config_invalid") |
| + for key in ("deployment", "group", "hook", "profile", "document"): |
| + require(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}", c[key]), "config_invalid") |
| + require(re.fullmatch(r"[0-9]{12}", c["account"]), "config_invalid") |
| + require(re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-[0-9]", c["region"]), "config_invalid") |
| + require(re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", c["bucket"]), "config_invalid") |
| + require(Path(c["state_dir"]).is_absolute() and ".." not in Path(c["state_dir"]).parts, |
| + "config_invalid") |
| + require(c["document"] != "SSM-SessionManagerRunShell" and |
| + (not c["document"].startswith("AWS-") or c["document"] == "AWS-StartNonInteractiveCommand"), |
| + "config_invalid") |
| + region_account = re.escape(c["region"] + ":" + c["account"]) |
| + require(re.fullmatch(r"arn:aws(?:-[a-z]+)*:autoscaling:" + region_account + |
| + r":autoScalingGroup:[A-Za-z0-9-]+:autoScalingGroupName/" + re.escape(c["group"]), |
| + c["group_arn"]), "config_invalid") |
| + require(isinstance(c["target_groups"], list) and len(c["target_groups"]) == 2 and |
| + len(set(c["target_groups"])) == 2, "config_invalid") |
| + partition = c["group_arn"].split(":")[1] |
| + for arn in c["target_groups"]: |
| + require(isinstance(arn, str) and re.fullmatch( |
| + "arn:" + partition + ":elasticloadbalancing:" + region_account + |
| + r":targetgroup/[A-Za-z0-9-]+/[0-9a-f]{16}", arn), "config_invalid") |
| + return c |
| + |
| + |
| +def sync_directory(path): |
| + fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) |
| + try: |
| + os.fsync(fd) |
| + finally: |
| + os.close(fd) |
| + |
| + |
| +def private_file(path, flags, owner): |
| + fd = os.open(path, flags | os.O_NOFOLLOW, 0o600) |
| + s = os.fstat(fd) |
| + if not (stat.S_ISREG(s.st_mode) and s.st_uid == owner and |
| + stat.S_IMODE(s.st_mode) == 0o600 and s.st_nlink == 1): |
| + os.close(fd) |
| + raise Refusal(TEXT["unsafe_state"]) |
| + return fd |
| + |
| + |
| +class Journal: |
| + def __init__(self, path, owner, create=False): |
| + self.path, self.owner = path, owner |
| + self.fd = private_file(path, os.O_RDWR | os.O_APPEND | |
| + (os.O_CREAT | os.O_EXCL if create else 0), owner) |
| + self.events = [] |
| + try: |
| + with os.fdopen(os.dup(self.fd), "rb") as reader: |
| + raw = reader.read(64 * 1024 * 1024 + 1) |
| + require(len(raw) <= 64 * 1024 * 1024 and (not raw or raw.endswith(b"\n")), "record") |
| + previous = "0" * 64 |
| + for line in raw.splitlines(): |
| + row = decode(line) |
| + digest = row.pop("hash") |
| + require(row["seq"] == len(self.events) and row["previous"] == previous and |
| + hashlib.sha256(encoded(row)).hexdigest() == digest, "record") |
| + row["hash"] = digest |
| + self.events.append(row) |
| + previous = digest |
| + require(create or (self.events and self.events[0]["kind"] == "begin"), "record") |
| + except BaseException: |
| + self.close() |
| + raise |
| + |
| + def close(self): |
| + if self.fd is not None: |
| + os.close(self.fd) |
| + self.fd = None |
| + |
| + def add(self, kind, **data): |
| + row = dict(seq=len(self.events), previous=self.events[-1]["hash"] if self.events else "0" * 64, |
| + kind=kind, **data) |
| + row["hash"] = hashlib.sha256(encoded(row)).hexdigest() |
| + raw = encoded(row) + b"\n" |
| + while raw: |
| + raw = raw[os.write(self.fd, raw):] |
| + os.fsync(self.fd) |
| + self.events.append(row) |
| + return row |
| + |
| + def last(self, kind, **fields): |
| + return next((r for r in reversed(self.events) if r["kind"] == kind and |
| + all(r.get(k) == v for k, v in fields.items())), None) |
| + |
| + |
| +class State: |
| + def __init__(self, config, owner=0): |
| + self.owner, self.config = owner, config |
| + root = Path(config["state_dir"]) |
| + # Do not follow even an ancestor symlink. The directory is provisioned |
| + # by the operator; silently recreating a missing state root loses history. |
| + for part in (root, *root.parents): |
| + s = part.lstat() |
| + require(stat.S_ISDIR(s.st_mode) and not stat.S_ISLNK(s.st_mode), "unsafe_state") |
| + if owner == 0: |
| + require(s.st_uid == 0 and not s.st_mode & 0o022, "unsafe_state") |
| + s = root.stat() |
| + require(s.st_uid == owner and stat.S_IMODE(s.st_mode) == 0o700, "unsafe_state") |
| + self.directory = root / hashlib.sha256(config["group_arn"].encode()).hexdigest()[:32] |
| + try: |
| + self.directory.mkdir(mode=0o700) |
| + sync_directory(root) |
| + except FileExistsError: |
| + pass |
| + s = self.directory.lstat() |
| + require(stat.S_ISDIR(s.st_mode) and s.st_uid == owner and |
| + stat.S_IMODE(s.st_mode) == 0o700, "unsafe_state") |
| + self.active = self.directory / "active.json" |
| + self.observation = self.directory / "provider-observation.json" |
| + self.blocked = self.directory / "provider-divergence.json" |
| + self.held = False |
| + |
| + @contextmanager |
| + def lock(self): |
| + fd = private_file(self.directory / "group.lock", os.O_RDWR | os.O_CREAT, self.owner) |
| + try: |
| + try: |
| + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| + except BlockingIOError as exc: |
| + raise Refusal(TEXT["busy"]) from exc |
| + self.held = True |
| + yield |
| + finally: |
| + self.held = False |
| + os.close(fd) |
| + |
| + def read(self, path): |
| + fd = private_file(path, os.O_RDONLY, self.owner) |
| + with os.fdopen(fd, "rb") as reader: |
| + raw = reader.read(65537) |
| + require(len(raw) <= 65536, "record") |
| + return decode(raw) |
| + |
| + def write(self, path, value): |
| + require(self.held, "busy") |
| + temp = self.directory / (".write-" + uuid.uuid4().hex) |
| + try: |
| + fd = private_file(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, self.owner) |
| + with os.fdopen(fd, "wb") as writer: |
| + writer.write(encoded(value) + b"\n") |
| + writer.flush() |
| + os.fsync(writer.fileno()) |
| + os.replace(temp, path) |
| + sync_directory(self.directory) |
| + finally: |
| + if temp.exists(): |
| + temp.unlink() |
| + |
| + def active_id(self): |
| + current = self.read(self.active)["transaction"] if os.path.lexists(self.active) else None |
| + require(current is None or TX.fullmatch(current), "record") |
| + unfinished = [] |
| + for path in self.directory.glob("*.jsonl"): |
| + j = Journal(path, self.owner) |
| + try: |
| + if not j.last("done"): |
| + unfinished.append(path.stem) |
| + finally: |
| + j.close() |
| + require((not unfinished and current is None) or |
| + (current is not None and (unfinished == [current] or not unfinished) and |
| + (self.directory / (current + ".jsonl")).exists()), "record") |
| + return current |
| + |
| + def create(self, header): |
| + require(self.held and self.active_id() is None, "active") |
| + j = Journal(self.directory / (header["transaction"] + ".jsonl"), self.owner, create=True) |
| + j.add("begin", **header) |
| + sync_directory(self.directory) |
| + self.write(self.active, {"transaction": header["transaction"]}) |
| + return j |
| + |
| + def load(self, tx): |
| + require(isinstance(tx, str) and TX.fullmatch(tx), "record") |
| + j = Journal(self.directory / (tx + ".jsonl"), self.owner) |
| + require(j.events[0]["config"] == self.config, "scope") |
| + return j |
| + |
| + def finish(self): |
| + require(self.held, "busy") |
| + self.active.unlink() |
| + sync_directory(self.directory) |
| + |
| + |
| +class AWS: |
| + """Only this adapter executes AWS CLI or Session Manager commands.""" |
| + def __init__(self, config): |
| + self.c = config |
| + self.last_session_id = None |
| + |
| + @staticmethod |
| + def session_output(command, env, timeout): |
| + # The Session Manager plugin can lose buffered output without a terminal. |
| + # A local PTY supplies one without an external unbuffer dependency. |
| + master, slave = pty.openpty() |
| + proc = None |
| + body = bytearray() |
| + try: |
| + tty.setraw(slave) |
| + proc = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=slave, stderr=slave, |
| + env=env, start_new_session=True) |
| + os.close(slave) |
| + slave = None |
| + end = time.monotonic() + timeout |
| + while time.monotonic() < end: |
| + readable, _, _ = select.select([master], [], [], min(0.2, max(0, end - time.monotonic()))) |
| + if readable: |
| + try: |
| + chunk = os.read(master, 65536) |
| + except OSError: |
| + chunk = b"" |
| + if not chunk: |
| + break |
| + body.extend(chunk) |
| + require(len(body) <= 4 * 1024 * 1024, "remote") |
| + if time.monotonic() >= end: |
| + raise Uncertain(TEXT["remote"], timeout=True) |
| + require(proc.wait(timeout=max(0.01, end - time.monotonic())) == 0, "remote") |
| + return bytes(body).decode() |
| + except (subprocess.TimeoutExpired, OSError) as exc: |
| + raise Uncertain(TEXT["remote"]) from exc |
| + finally: |
| + if proc is not None and proc.returncode is None: |
| + # Kill the owned process group before reaping its leader, so |
| + # its PID cannot be reused for another operator's process. |
| + try: |
| + os.killpg(proc.pid, signal.SIGKILL) |
| + except ProcessLookupError: |
| + pass |
| + proc.wait() |
| + os.close(master) |
| + if slave is not None: |
| + os.close(slave) |
| + |
| + def invoke(self, service, verb, args, timeout=15, raw=False, object_body=False): |
| + command = ["aws", "--profile", self.c["profile"], "--region", self.c["region"], |
| + "--output", "json", "--no-cli-pager", "--no-paginate", "--cli-connect-timeout", "2", |
| + "--cli-read-timeout", "2", service, verb, *args] |
| + env = dict(os.environ, AWS_MAX_ATTEMPTS="1", AWS_RETRY_MODE="standard", AWS_PAGER="") |
| + # Do not let ambient endpoint overrides redirect a privileged operator. |
| + for key in list(env): |
| + if key.startswith("AWS_ENDPOINT_URL") or key in { |
| + "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", |
| + "AWS_SECURITY_TOKEN", "AWS_PROFILE", "AWS_DEFAULT_PROFILE"}: |
| + del env[key] |
| + if service == "ssm" and verb == "start-session": |
| + return self.session_output(command, env, timeout) |
| + base = os.environ.get("TMPDIR") or str(Path.home() / ".cache") |
| + with tempfile.TemporaryDirectory(prefix="region-roll-", dir=base) as scratch: |
| + if object_body: |
| + command.append(str(Path(scratch) / "object")) |
| + with open(Path(scratch) / "output", "w+b") as out: |
| + proc = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=out, |
| + stderr=subprocess.DEVNULL, env=env, start_new_session=True) |
| + try: |
| + rc = proc.wait(timeout=timeout) |
| + except BaseException: |
| + os.killpg(proc.pid, signal.SIGKILL) |
| + proc.wait() |
| + raise Uncertain(TEXT["api"], interrupted=True) from None |
| + out.seek(0) |
| + body = out.read(4 * 1024 * 1024 + 1) |
| + if rc != 0 or len(body) > 4 * 1024 * 1024: |
| + raise Uncertain(TEXT["api"], exit_code=rc, output_too_large=len(body) > 4 * 1024 * 1024) |
| + if object_body: |
| + with open(Path(scratch) / "object", "rb") as obj: |
| + body = obj.read(4 * 1024 * 1024 + 1) |
| + require(len(body) <= 4 * 1024 * 1024, "api") |
| + return body.decode() if raw else (decode(body) if body.strip() else {}) |
| + |
| + @staticmethod |
| + def remote_command(a, nonce): |
| + verb = a["verb"] |
| + require(verb in {"status", "prepare", "permit", "revoke", "apply", "rollback"}, "unsupported") |
| + binary = "/opt/carlos/carlos" |
| + command = binary + " system group-maintenance " + verb |
| + if verb == "prepare": |
| + require(SHA.fullmatch(a["sha256"]), "prepare") |
| + command += " --sha256 " + a["sha256"] |
| + elif verb == "permit": |
| + payload = base64.b64encode(encoded(a["permit"])).decode() |
| + command = ("printf %s " + shlex.quote(payload) + " | base64 -d | " + command + |
| + " && " + binary + " system group-maintenance status") |
| + elif verb == "apply": |
| + # hostenv.Render explicitly produces shell-compatible assignments. |
| + # Prepare already checked its root ownership and configuration. Only |
| + # this fixed root path is sourced; nothing supplied by an agent is. |
| + command = ("set -a; . /etc/carlos/host.env; set +a; " |
| + "AWS_MAX_ATTEMPTS=1 " + binary + " system apply") |
| + # NonInteractiveCommands has no stdin. Carry only the permit in base64 |
| + # and frame both output and status, independent of the plugin exit code. |
| + script = ("[ \"$(id -u)\" = 0 ] || exit 77; " |
| + "printf '\\n" + nonce + ":BEGIN\\n'; (" + command + |
| + "); result=$?; printf '\\n" + nonce + ":END:%s\\n' \"$result\"") |
| + return ("/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c " + |
| + shlex.quote(script)) |
| + |
| + def request(self, op, a): |
| + group = ["--auto-scaling-group-name", self.c["group"]] |
| + if op == "group": |
| + r = self.invoke("autoscaling", "describe-auto-scaling-groups", |
| + ["--auto-scaling-group-names", self.c["group"]])["AutoScalingGroups"] |
| + require(len(r) == 1, "scope") |
| + g = r[0] |
| + tags = {t["Key"]: t["Value"] for t in g["Tags"]} |
| + return dict(name=g["AutoScalingGroupName"], arn=g["AutoScalingGroupARN"], |
| + deployment=tags.get("carlos:deployment"), region=self.c["region"], |
| + minimum=g["MinSize"], desired=g["DesiredCapacity"], maximum=g["MaxSize"], |
| + members={i["InstanceId"]: i["LifecycleState"] for i in g["Instances"]}, |
| + healthy={i["InstanceId"]: i["HealthStatus"] == "Healthy" for i in g["Instances"]}, |
| + target_groups=g["TargetGroupARNs"], template=g.get("LaunchTemplate")) |
| + if op == "targets": |
| + r = self.invoke("elbv2", "describe-target-health", ["--target-group-arn", a["arn"]]) |
| + result = {} |
| + for t in r["TargetHealthDescriptions"]: |
| + iid, state = t["Target"]["Id"], t["TargetHealth"]["State"] |
| + # A duplicate registration on another port must not hide draining. |
| + result[iid] = state if iid not in result or result[iid] == state else "unknown" |
| + return result |
| + if op == "online": |
| + r = self.invoke("ssm", "describe-instance-information", ["--filters", json.dumps( |
| + [{"Key": "InstanceIds", "Values": [a["iid"]]}])])["InstanceInformationList"] |
| + return len(r) == 1 and r[0]["InstanceId"] == a["iid"] and r[0]["PingStatus"] == "Online" |
| + if op == "hooks": |
| + r = self.invoke("autoscaling", "describe-lifecycle-hooks", group + |
| + ["--lifecycle-hook-names", self.c["hook"]])["LifecycleHooks"] |
| + require(len(r) == 1, "hook") |
| + h = r[0] |
| + return dict(name=h["LifecycleHookName"], timeout=h["HeartbeatTimeout"], |
| + default=h["DefaultResult"], transition=h["LifecycleTransition"]) |
| + if op == "activities": |
| + rows = self.invoke("autoscaling", "describe-scaling-activities", group)["Activities"] |
| + result = [] |
| + for row in rows: |
| + description = row.get("Description", "") |
| + if re.search(r"\b" + re.escape(a["iid"]) + r"\b", description) and "out of Standby" in description: |
| + dt = datetime.fromisoformat(row["StartTime"].replace("Z", "+00:00")) |
| + result.append(dict(id=row["ActivityId"], iid=a["iid"], time=dt.timestamp())) |
| + return result |
| + if op == "edges": |
| + require(re.fullmatch(r"g-[a-z0-9-]+", a["box_ref"]), "identity") |
| + return self.invoke("s3api", "get-object", ["--bucket", self.c["bucket"], "--key", |
| + "control/edges/" + a["box_ref"] + ".json"], object_body=True) |
| + if op == "minimum": |
| + return self.invoke("autoscaling", "update-auto-scaling-group", group + ["--min-size", str(a["value"])]) |
| + if op == "enter": |
| + require(a["decrement"] is True, "held") |
| + return self.invoke("autoscaling", "enter-standby", group + |
| + ["--instance-ids", a["iid"], "--should-decrement-desired-capacity"]) |
| + if op == "exit": |
| + result = self.invoke("autoscaling", "exit-standby", group + ["--instance-ids", a["iid"]]) |
| + rows = result.get("Activities", []) |
| + require(len(rows) == 1 and rows[0].get("ActivityId"), "activity") |
| + return {"activity": rows[0]["ActivityId"]} |
| + if op == "complete": |
| + require(a["hook"] == self.c["hook"] and a["result"] == "CONTINUE", "hook") |
| + return self.invoke("autoscaling", "complete-lifecycle-action", group + |
| + ["--instance-id", a["iid"], "--lifecycle-hook-name", a["hook"], |
| + "--lifecycle-action-result", "CONTINUE"], timeout=2) |
| + if op == "session": |
| + self.last_session_id = None |
| + nonce = uuid.uuid4().hex |
| + command = self.remote_command(a, nonce) |
| + text = self.invoke("ssm", "start-session", ["--target", a["iid"], |
| + "--document-name", self.c["document"], "--parameters", |
| + json.dumps({"command": [command]})], |
| + timeout=300 if a["verb"] in {"apply", "prepare", "rollback"} else 15, raw=True) |
| + session_ids = re.findall(r"Starting session with SessionId: ([A-Za-z0-9_-]+)", text) |
| + if len(session_ids) == 1: |
| + self.last_session_id = session_ids[0] |
| + match = re.findall(re.escape(nonce) + r":BEGIN\r?\n(.*?)\r?\n" + |
| + re.escape(nonce) + r":END:([0-9]+)(?:\r?\n|$)", text, re.S) |
| + require(len(match) == 1 and match[0][1] == "0", "remote") |
| + if a["verb"] in {"status", "prepare", "permit"}: |
| + require(len(match[0][0].encode()) <= 8192, "remote") |
| + return decode(match[0][0]) |
| + return {} |
| + raise Refusal(TEXT["unsupported"]) |
| + |
| + |
| +class Operator: |
| + def __init__(self, config, adapter, state, journal=None, clock=time.time, |
| + sleep=time.sleep, output=sys.stdout, attended_by="terminal"): |
| + self.c, self.api, self.state, self.j = config, adapter, state, journal |
| + self.clock, self.sleep, self.output, self.attended = clock, sleep, output, attended_by |
| + self.header = journal.events[0] if journal else None |
| + |
| + def say(self, phase, detail): |
| + try: |
| + print(TEXT["line"].format(phase=phase, detail=detail), file=self.output, flush=True) |
| + except (BrokenPipeError, OSError): |
| + pass |
| + |
| + def event(self, kind, **data): |
| + if self.j: |
| + if kind == "phase": |
| + self.say(data["phase"], self.header["iid"]) |
| + return self.j.add(kind, at=self.clock(), **data) |
| + |
| + def call(self, op, **args): |
| + session = sum(r.get("op") == "session" and r["kind"] == "intent" for r in self.j.events) + 1 if self.j else 1 |
| + intent = self.event("intent", op=op, args=args, session=session if op == "session" else None) |
| + try: |
| + result = self.api.request(op, args) |
| + except Exception as exc: |
| + self.event("error", intent=intent["seq"] if intent else None, op=op, error=type(exc).__name__, |
| + reason=str(exc), details=getattr(exc, "details", {}), |
| + session_id=getattr(self.api, "last_session_id", None) if op == "session" else None) |
| + raise |
| + self.event("response", intent=intent["seq"] if intent else None, op=op, result=result, |
| + session_id=getattr(self.api, "last_session_id", None) if op == "session" else None) |
| + return result |
| + |
| + def box(self, iid, verb="status", **args): |
| + return self.call("session", iid=iid, verb=verb, **args) |
| + |
| + def snapshot(self): |
| + g = self.call("group") |
| + require(g["name"] == self.c["group"] and g["arn"] == self.c["group_arn"] and |
| + g["deployment"] == self.c["deployment"] and g["region"] == self.c["region"] and |
| + set(g["target_groups"]) == set(self.c["target_groups"]), "scope") |
| + require(isinstance(g.get("template"), dict) and |
| + re.fullmatch(r"[1-9][0-9]*", g["template"].get("Version", "")), "scope") |
| + g["targets"] = [self.call("targets", arn=arn) for arn in self.c["target_groups"]] |
| + self.event("snapshot", group=g) |
| + return g |
| + |
| + def identity(self, s, iid): |
| + require(s.get("v") == 1 and s.get("iid") == iid and s.get("account") == self.c["account"] and |
| + s.get("region") == self.c["region"] and s.get("group") == self.c["group"] and |
| + isinstance(s.get("boot_id"), str) and s["boot_id"] and |
| + isinstance(s.get("config_digest"), str) and SHA.fullmatch(s["config_digest"]) and |
| + isinstance(s.get("binary_sha256"), str) and SHA.fullmatch(s["binary_sha256"]), "identity") |
| + if self.header and self.header.get("identity") and iid == self.header["iid"]: |
| + require(all(s.get(k) == v for k, v in self.header["identity"].items()), "identity") |
| + |
| + def readiness(self, iid, maintenance=False): |
| + observed = self.clock() |
| + s = self.box(iid) |
| + self.identity(s, iid) |
| + e = self.call("edges", box_ref=s["box_ref"]) |
| + after = self.box(iid) |
| + self.identity(after, iid) |
| + require(s.get("edge", {}).get("identity") and s["edge"] == after["edge"] and |
| + s["binary_sha256"] == after["binary_sha256"] and |
| + all(x.get("health", {}).get("state") == "healthy" and |
| + x["health"].get("code") == 200 and x["edge"].get("state") == "known" for x in (s, after)) and |
| + e.get("v") == 1 and e.get("box") == s["box_ref"] and |
| + e.get("admitted") is True and e.get("box_role") == "serve" and |
| + instant(e.get("generation")) > instant(s["edge"].get("started_at")) and |
| + 0 <= self.clock() - observed <= 5, "admission") |
| + if maintenance: |
| + action = self.action() |
| + expected = self.header["old"] if action == "rollback" else self.header["new"] |
| + require(s["binary_sha256"] == expected and |
| + s["edge"]["identity"] != self.before_process(), "process") |
| + p = s["permit"] |
| + require(p.get("transaction") == self.header["transaction"] and |
| + p.get("action") == action and p.get("consumed") is True, "permit") |
| + observation = dict(observed=observed, status=s, generation=e["generation"]) |
| + self.event("readiness", iid=iid, **observation) |
| + return observation |
| + |
| + def preflight(self, iid, digest): |
| + require(IID.fullmatch(iid) and SHA.fullmatch(digest), "config_invalid") |
| + require(not self.state.blocked.exists(), "blocked") |
| + g = self.snapshot() |
| + n = g["desired"] |
| + require(type(n) is int and n >= 2 and g["minimum"] == g["maximum"] == n and |
| + len(g["members"]) == n and iid in g["members"], "shape") |
| + hook = self.call("hooks") |
| + require(hook == dict(name=self.c["hook"], timeout=900, default="ABANDON", |
| + transition="autoscaling:EC2_INSTANCE_LAUNCHING"), "hook") |
| + try: |
| + obs = self.state.read(self.state.observation) |
| + except (FileNotFoundError, Refusal): |
| + raise Refusal(TEXT["observation"]) from None |
| + require(obs == dict(v=1, group_arn=self.c["group_arn"], hook=self.c["hook"], |
| + template=g["template"], documented_no_hook=True), "observation") |
| + for member in sorted(g["members"]): |
| + require(self.call("online", iid=member) is True, "offline") |
| + require(g["members"][member] == "InService" and g["healthy"].get(member) is True and |
| + all(t.get(member) == "healthy" for t in g["targets"]), "peer") |
| + self.readiness(member) |
| + s = self.box(iid) |
| + self.identity(s, iid) |
| + require(s["permit"].get("state") == "absent", "permit") |
| + require(s["binary_sha256"] != digest, "process") |
| + return g, s |
| + |
| + def plan(self, iid, digest): |
| + require(self.state.held, "busy") |
| + inspection = self.state.directory / ("plan-" + uuid.uuid4().hex + ".log") |
| + self.j = Journal(inspection, self.state.owner, create=True) |
| + self.event("begin", config=self.c, attended_by=self.attended, command="plan") |
| + refusals = [] |
| + |
| + def check(function): |
| + try: |
| + return function() |
| + except (Refusal, Uncertain, OSError, KeyError, TypeError, ValueError) as exc: |
| + reason = str(exc) if isinstance(exc, (Refusal, Uncertain)) else TEXT["record"] |
| + refusals.append(reason) |
| + return None |
| + |
| + self.say("state", str(self.state.directory)) |
| + check(lambda: require(IID.fullmatch(iid) and SHA.fullmatch(digest), "config_invalid")) |
| + check(lambda: require(self.state.active_id() is None, "active")) |
| + check(lambda: require(not self.state.blocked.exists(), "blocked")) |
| + g = check(self.snapshot) |
| + h = check(lambda: self.call("hooks")) |
| + check(lambda: require(h == dict(name=self.c["hook"], timeout=900, default="ABANDON", |
| + transition="autoscaling:EC2_INSTANCE_LAUNCHING"), "hook")) |
| + if g: |
| + n = g["desired"] |
| + check(lambda: require(type(n) is int and n >= 2 and g["minimum"] == g["maximum"] == n and |
| + len(g["members"]) == n and iid in g["members"], "shape")) |
| + check(lambda: require(self.state.read(self.state.observation) == dict( |
| + v=1, group_arn=self.c["group_arn"], hook=self.c["hook"], template=g["template"], |
| + documented_no_hook=True), "observation")) |
| + for member in sorted(g["members"]): |
| + online = check(lambda: self.call("online", iid=member)) |
| + check(lambda: require(online is True, "offline")) |
| + check(lambda: require(g["members"][member] == "InService" and g["healthy"].get(member) is True and |
| + all(t.get(member) == "healthy" for t in g["targets"]), "peer")) |
| + if online: |
| + ready = check(lambda: self.readiness(member)) |
| + if member == iid and ready: |
| + check(lambda: require(ready["status"]["permit"].get("state") == "absent", "permit")) |
| + check(lambda: require(ready["status"]["binary_sha256"] != digest, "process")) |
| + self.event("done", outcome="plan", refusals=refusals) |
| + for reason in dict.fromkeys(refusals): |
| + self.say("refused", reason) |
| + self.say("plan", TEXT["sequence"]) |
| + self.say("journal", str(inspection)) |
| + return not refusals |
| + |
| + def roll(self, iid, digest): |
| + require(self.state.held and self.state.active_id() is None, "active") |
| + # Journal even preflight sessions; a failed preflight has no AWS group |
| + # writes, but its session count and evidence must still survive. |
| + tx = uuid.uuid4().hex |
| + self.j = self.state.create(dict(transaction=tx, config=self.c, iid=iid, new=digest, |
| + attended_by=self.attended)) |
| + self.header = self.j.events[0] |
| + self.say("journal", str(self.j.path)) |
| + try: |
| + g, s = self.preflight(iid, digest) |
| + except Exception: |
| + self.event("done", outcome="preflight-refused") |
| + self.state.finish() |
| + raise |
| + details = dict(old=s["binary_sha256"], n=g["desired"], members=sorted(g["members"]), |
| + identity={k: s[k] for k in ("iid", "boot_id", "account", "region", "group", "config_digest", "box_ref")}, |
| + original_process=s["edge"]["identity"], template=g["template"]) |
| + self.event("validated", **details) |
| + self.header = dict(self.header, **details) |
| + return self.resume() |
| + |
| + def saved_status(self): |
| + header = self.j.events[0] |
| + valid = self.j.last("validated") or {} |
| + phase = self.j.last("phase") or {} |
| + observed = self.j.last("snapshot") or {} |
| + return dict(transaction=header["transaction"], iid=header["iid"], |
| + old_sha256=valid.get("old"), new_sha256=header["new"], |
| + phase=phase.get("phase", "preflight"), done=self.j.last("done"), |
| + last_observed_at=observed.get("at"), last_observed_group=observed.get("group"), |
| + sessions=sum(r["kind"] == "intent" and r.get("op") == "session" for r in self.j.events), |
| + last_event=self.j.events[-1], journal=str(self.j.path)) |
| + |
| + def restore_header(self): |
| + require(self.j and self.state.held and self.state.active_id() == self.j.path.stem, "record") |
| + self.header = dict(self.j.events[0]) |
| + valid = self.j.last("validated") |
| + if valid: |
| + self.header.update({k: v for k, v in valid.items() if k not in {"seq", "previous", "hash", "kind", "at"}}) |
| + require(valid is not None, "record") |
| + |
| + def action(self): |
| + return "rollback" if self.j.last("rollback-requested") else "apply" |
| + |
| + def before_process(self): |
| + rollback = self.j.last("rollback-requested") |
| + return rollback["process"] if rollback else self.header["original_process"] |
| + |
| + def invariant(self, g): |
| + h = self.header |
| + require(sorted(g["members"]) == h["members"] and g["maximum"] == h["n"] and |
| + g["template"] == h["template"], "members") |
| + |
| + def standby(self, g, deregistered=True): |
| + self.invariant(g) |
| + require(g["members"][self.header["iid"]] == "Standby" and |
| + g["minimum"] == g["desired"] == self.header["n"] - 1, "held") |
| + if deregistered: |
| + require(all(t.get(self.header["iid"], "unused") == "unused" for t in g["targets"]), "held") |
| + |
| + def alert(self, key, failed=False): |
| + intent = self.j.last("exit-intent") |
| + self.event("failed-probe" if failed else "alert", reason=TEXT[key], |
| + iid=self.header["iid"], hook=self.c["hook"], transaction=self.header["transaction"], |
| + deadline=intent["at"] + 900 if failed and intent else None) |
| + self.say("FAIL" if failed else "ALERT", TEXT[key]) |
| + if failed: |
| + self.state.write(self.state.blocked, dict(transaction=self.header["transaction"], reason=TEXT[key])) |
| + raise FailedProbe(TEXT[key]) |
| + raise Refusal(TEXT[key]) |
| + |
| + def wait_standby(self, check): |
| + end = self.clock() + WAIT |
| + while True: |
| + try: |
| + g = self.snapshot() |
| + self.standby(g, deregistered=False) |
| + result = check(g) |
| + return result |
| + except (Refusal, Uncertain): |
| + if self.clock() >= end: |
| + self.alert("timeout") |
| + self.sleep(min(5, end - self.clock())) |
| + |
| + def prepare(self): |
| + if self.j.last("prepared"): |
| + return |
| + h = self.header |
| + self.event("phase", phase="prepare") |
| + p = self.box(h["iid"], "prepare", sha256=h["new"]) |
| + require(p.get("v") == 1 and p.get("artifact_sha256") == h["new"] and |
| + p.get("old_binary_sha256") == h["old"] and p.get("cache_state") == "verified" and |
| + p.get("request_written") is True and p.get("config_check") == "valid", "prepare") |
| + self.event("prepared", result=p) |
| + |
| + def mutation(self): |
| + h, action = self.header, self.action() |
| + g = self.snapshot() |
| + self.standby(g) |
| + for member in h["members"]: |
| + if member != h["iid"]: |
| + require(g["members"][member] == "InService" and g["healthy"].get(member) is True and |
| + all(t.get(member) == "healthy" for t in g["targets"]), "peer") |
| + self.readiness(member) |
| + s = self.box(h["iid"]) |
| + self.identity(s, h["iid"]) |
| + p = s["permit"] |
| + expected = h["old"] if action == "rollback" else h["new"] |
| + if p.get("transaction") == h["transaction"] and p.get("action") == action and p.get("consumed") is True: |
| + require(s["binary_sha256"] == expected and s["edge"]["identity"] != self.before_process(), "uncertain_action") |
| + return |
| + if action == "rollback" and p.get("state") != "absent" and p.get("action") == "apply": |
| + require(p.get("transaction") == h["transaction"], "permit") |
| + self.box(h["iid"], "revoke") |
| + s = self.box(h["iid"]) |
| + p = s["permit"] |
| + permit = self.j.last("permit-body", action=action) |
| + if p.get("state") == "absent": |
| + body = dict(v=1, **{k: h["identity"][k] for k in |
| + ("account", "region", "group", "iid", "boot_id", "config_digest")}, |
| + transaction=h["transaction"], phase="mutation", action=action, |
| + old_sha256=h["old"], new_sha256=h["new"], |
| + expires=int(self.clock()) + 3600, allow_rollback=action == "apply") |
| + permit = self.event("permit-body", action=action, body=body) |
| + s = self.box(h["iid"], "permit", permit=body) |
| + self.identity(s, h["iid"]) |
| + p = s["permit"] |
| + require(permit and p.get("state") == "present" and p.get("accepted") is True and |
| + p.get("consumed") is False and p.get("action") == action and |
| + p.get("transaction") == h["transaction"] and |
| + p.get("expires") == permit["body"]["expires"], "permit") |
| + self.standby(self.snapshot()) |
| + self.event("phase", phase="mutation", action=action) |
| + self.box(h["iid"], action) |
| + |
| + def resume(self): |
| + self.restore_header() |
| + h = self.header |
| + if self.j.last("done"): |
| + self.state.finish() |
| + return |
| + if self.j.last("exit-intent"): |
| + return self.return_member() |
| + self.prepare() |
| + g = self.snapshot() |
| + self.invariant(g) |
| + phase = g["members"][h["iid"]] |
| + if phase == "InService": |
| + require(g["desired"] == h["n"] and g["minimum"] in (h["n"], h["n"] - 1), "shape") |
| + # Recheck peers and identity before the first group write, including |
| + # resume after preparation or an ambiguous minimum update. |
| + for member in h["members"]: |
| + require(self.call("online", iid=member) is True, "offline") |
| + require(g["members"][member] == "InService" and |
| + g["healthy"].get(member) is True and |
| + all(t.get(member) == "healthy" for t in g["targets"]), "peer") |
| + self.readiness(member) |
| + if g["minimum"] == h["n"]: |
| + self.event("phase", phase="lower-minimum") |
| + self.call("minimum", value=h["n"] - 1) |
| + if self.j.last("intent", op="enter"): |
| + # An attended resume may retry only from the observed original |
| + # InService/desired-N shape. EnteringStandby/Standby instead go |
| + # straight to readback below. No desired-capacity repair exists. |
| + self.event("enter-retry", observed=g) |
| + self.event("phase", phase="enter-standby") |
| + self.call("enter", iid=h["iid"], decrement=True) |
| + self.wait_standby(lambda g: self.standby(g)) |
| + self.say("Standby", h["iid"]) |
| + self.mutation() |
| + self.event("phase", phase="local-verification", action=self.action()) |
| + self.wait_standby(lambda g: self.readiness(h["iid"], maintenance=True)) |
| + return self.return_member() |
| + |
| + def rollback(self, iid): |
| + self.restore_header() |
| + require(iid == self.header["iid"] and not self.j.last("exit-intent"), "rollback_refused") |
| + self.standby(self.snapshot()) |
| + if not self.j.last("rollback-requested"): |
| + s = self.box(iid) |
| + self.identity(s, iid) |
| + require(s["binary_sha256"] == self.header["new"] and |
| + s["permit"].get("transaction") == self.header["transaction"] and |
| + s["permit"].get("action") == "apply" and s["permit"].get("consumed") is True, |
| + "rollback_refused") |
| + self.event("rollback-requested", process=s["edge"]["identity"]) |
| + return self.resume() |
| + |
| + def exit_activity(self): |
| + saved = self.j.last("exit-activity") |
| + if saved: |
| + return saved["activity"] |
| + intent = self.j.last("exit-intent") |
| + rows = self.call("activities", iid=self.header["iid"]) |
| + matches = [r["id"] for r in rows if r["iid"] == self.header["iid"] and r["time"] >= intent["at"] - 1] |
| + require(len(matches) == 1, "activity") |
| + self.event("exit-activity", activity=matches[0]) |
| + return matches[0] |
| + |
| + def return_member(self): |
| + """The only owner of ExitStandby and defensive return CONTINUE.""" |
| + self.restore_header() |
| + h, iid = self.header, self.header["iid"] |
| + self.event("phase", phase="return") |
| + end = self.clock() + WAIT |
| + while True: |
| + if self.clock() >= end: |
| + self.alert("return_phase") |
| + try: |
| + try: |
| + g = self.snapshot() |
| + except (Refusal, Uncertain): |
| + if self.j.last("exit-intent"): |
| + self.alert("return_failed", failed=True) |
| + raise |
| + self.invariant(g) |
| + phase = g["members"][iid] |
| + intent = self.j.last("exit-intent") |
| + if phase == "Standby": |
| + self.standby(g) |
| + if intent: |
| + self.sleep(1) |
| + ready = self.readiness(iid, maintenance=True) |
| + self.event("exit-intent", transaction=h["transaction"], iid=iid, |
| + boot_id=h["identity"]["boot_id"], process=ready["status"]["edge"]["identity"], |
| + observed=ready["observed"], generation=ready["generation"]) |
| + require(0 <= self.clock() - ready["observed"] <= 5, "admission") |
| + try: |
| + result = self.call("exit", iid=iid) |
| + self.event("exit-activity", activity=result["activity"]) |
| + except Uncertain: |
| + pass |
| + # Always describe after a response, including a lost one. |
| + continue |
| + require(intent is not None, "return_intent") |
| + require(g["desired"] == h["n"] and g["minimum"] in (h["n"] - 1, h["n"]), "members") |
| + if phase == "Pending:Wait": |
| + self.state.write(self.state.blocked, dict(transaction=h["transaction"], phase=phase)) |
| + self.event("return-hook", deadline=intent["at"] + 900) |
| + # Leave room for the bounded status sessions and completion. |
| + if self.clock() + 120 >= intent["at"] + 900: |
| + self.alert("return_failed", failed=True) |
| + activity = self.exit_activity() |
| + try: |
| + ready = self.readiness(iid, maintenance=True) |
| + require(ready["status"]["edge"]["identity"] == intent["process"], "admission") |
| + except (Refusal, Uncertain): |
| + self.alert("return_failed", failed=True) |
| + key = [h["transaction"], iid, h["identity"]["boot_id"], intent["process"], activity] |
| + attempts = [r for r in self.j.events if r["kind"] == "return-action" and r["key"] == key] |
| + if self.j.last("return-acknowledged", key=key): |
| + self.sleep(2) |
| + continue |
| + if len(attempts) >= 4: |
| + self.alert("return_attempts", failed=True) |
| + if attempts: |
| + self.sleep((1, 2, 4)[len(attempts) - 1]) |
| + # The next iteration describes before another write and |
| + # then obtains a new readiness observation. |
| + g = self.snapshot() |
| + if g["members"][iid] != "Pending:Wait": |
| + continue |
| + ready = self.readiness(iid, maintenance=True) |
| + require(ready["status"]["edge"]["identity"] == intent["process"], "admission") |
| + self.event("return-action", key=key, attempt=len(attempts) + 1, |
| + deadline=intent["at"] + 900, result="CONTINUE") |
| + require(0 <= self.clock() - ready["observed"] <= 5, "admission") |
| + try: |
| + self.call("complete", iid=iid, hook=self.c["hook"], result="CONTINUE") |
| + self.event("return-outcome", key=key, attempt=len(attempts) + 1, outcome="acknowledged") |
| + self.event("return-acknowledged", key=key) |
| + except Uncertain: |
| + self.event("return-outcome", key=key, attempt=len(attempts) + 1, outcome="uncertain") |
| + continue |
| + if phase == "InService": |
| + require(all(g["members"][member] == "InService" and g["healthy"].get(member) is True and |
| + all(t.get(member) == "healthy" for t in g["targets"]) for member in h["members"]), |
| + "return_phase") |
| + # Once revoked, use the saved observation plus a fresh |
| + # identity/readiness read; a consumed permit may be absent. |
| + if not self.j.last("returned"): |
| + ready = self.readiness(iid, maintenance=True) |
| + require(ready["status"]["edge"]["identity"] == intent["process"], "admission") |
| + self.event("returned", process=intent["process"]) |
| + if g["minimum"] != h["n"]: |
| + self.event("phase", phase="restore-minimum") |
| + self.call("minimum", value=h["n"]) |
| + continue |
| + s = self.box(iid) |
| + self.identity(s, iid) |
| + require(s["edge"]["identity"] == intent["process"] and s["health"]["state"] == "healthy", "admission") |
| + if s["permit"].get("state") != "absent": |
| + require(s["permit"].get("transaction") == h["transaction"], "permit") |
| + self.event("phase", phase="revocation") |
| + self.box(iid, "revoke") |
| + require(self.box(iid)["permit"].get("state") == "absent", "permit") |
| + self.event("done", outcome="failed-probe-recovered" if self.j.last("failed-probe") else "returned", |
| + provider_divergence=self.state.blocked.exists()) |
| + self.state.finish() |
| + self.say("done", TEXT["done"]) |
| + if self.state.blocked.exists(): |
| + self.say("ALERT", TEXT["divergence"]) |
| + return |
| + require(phase in {"Pending", "PreInService", "Pending:Proceed"}, "return_phase") |
| + except FailedProbe: |
| + raise |
| + except (Refusal, Uncertain): |
| + if self.j.last("exit-intent") and (locals().get("phase") == "Pending:Wait" or |
| + self.j.last("return-action")): |
| + self.alert("return_failed", failed=True) |
| + if self.clock() >= end: |
| + self.alert("timeout" if locals().get("phase") == "Standby" else "return_phase") |
| + if self.clock() >= end: |
| + self.alert("return_phase") |
| + self.sleep(5) |
| + |
| + |
| +def main(argv=None): |
| + parser = argparse.ArgumentParser(description=TEXT["help"], formatter_class=argparse.RawDescriptionHelpFormatter) |
| + parser.add_argument("--config", required=True, help=TEXT["config"]) |
| + parser.add_argument("--attended-by", help=TEXT["attended"]) |
| + sub = parser.add_subparsers(dest="command", required=True) |
| + for verb in ("plan", "roll", "rollback", "resume", "status", "return"): |
| + p = sub.add_parser(verb, help=TEXT[verb]) |
| + if verb in {"plan", "roll", "rollback"}: |
| + p.add_argument("--member", required=True, help=TEXT["member"]) |
| + if verb in {"plan", "roll"}: |
| + p.add_argument("--to-sha256", required=True, help=TEXT["sha"]) |
| + if verb in {"rollback", "resume", "status", "return"}: |
| + p.add_argument("--transaction", required=True, help=TEXT["transaction"]) |
| + args = parser.parse_args(argv) |
| + journal = None |
| + try: |
| + require(os.geteuid() == 0, "root") |
| + require(sys.stdin.isatty() or bool(args.attended_by and args.attended_by.strip()), "attended_required") |
| + config = validate_config(decode(Path(args.config).read_bytes())) |
| + state = State(config) |
| + with state.lock(): |
| + op = Operator(config, AWS(config), state, attended_by=args.attended_by or "terminal") |
| + if args.command == "plan": |
| + try: |
| + return 0 if op.plan(args.member, args.to_sha256) else 1 |
| + finally: |
| + journal = op.j |
| + elif args.command == "roll": |
| + try: |
| + op.roll(args.member, args.to_sha256) |
| + finally: |
| + journal = op.j |
| + else: |
| + journal = state.load(args.transaction) |
| + op.j = journal |
| + if args.command == "status": |
| + print(json.dumps(op.saved_status(), sort_keys=True)) |
| + elif args.command == "rollback": |
| + op.rollback(args.member) |
| + elif args.command == "return": |
| + op.return_member() |
| + else: |
| + op.resume() |
| + return 0 |
| + except (Refusal, Uncertain, OSError, KeyError, TypeError, ValueError) as exc: |
| + reason = str(exc) if isinstance(exc, (Refusal, Uncertain)) else TEXT["record"] |
| + print(TEXT["refused"].format(reason=reason), file=sys.stderr) |
| + return 1 |
| + finally: |
| + if journal: |
| + journal.close() |
| + |
| + |
| +if __name__ == "__main__": |
| + sys.exit(main()) |
diff --git a/scripts/region_group_roll_test.py b/scripts/region_group_roll_test.py| new file mode 100644 |
| index 000000000..5c2a6797b |
| --- /dev/null |
| +++ b/scripts/region_group_roll_test.py |
| @@ -0,0 +1,804 @@ |
| +"""Offline witnesses for the attended group maintenance transaction.""" |
| +import copy |
| +import importlib.util |
| +import io |
| +import json |
| +import os |
| +from pathlib import Path |
| +import shlex |
| +import subprocess |
| +import sys |
| +import tempfile |
| +import types |
| +import unittest |
| +from unittest.mock import patch |
| + |
| +SPEC = importlib.util.spec_from_file_location( |
| + "region_group_roll", Path(__file__).with_name("region-group-roll.py")) |
| +roll = importlib.util.module_from_spec(SPEC) |
| +SPEC.loader.exec_module(roll) |
| + |
| +OLD, NEW = "a" * 64, "b" * 64 |
| +IID, PEER = "i-" + "1" * 17, "i-" + "2" * 17 |
| + |
| + |
| +class Death(BaseException): |
| + pass |
| + |
| + |
| +class Fake: |
| + def __init__(self, config): |
| + self.c = config |
| + self.now = 1800000000.0 |
| + self.minimum = self.desired = self.maximum = 2 |
| + self.states = {IID: "InService", PEER: "InService"} |
| + self.tg = {iid: "healthy" for iid in self.states} |
| + self.boxes = {iid: self.box(iid) for iid in self.states} |
| + self.online = True |
| + self.admitted = True |
| + self.writes = [] |
| + self.calls = [] |
| + self.fault = None |
| + self.fault_at = None |
| + self.fail_before = False |
| + self.hook = False |
| + self.deadline = None |
| + self.loss_after_exit = False |
| + self.outage = False |
| + self.prepare_bad = False |
| + self.continues = self.exits = self.launches = self.abandons = 0 |
| + self.activity = [] |
| + self.used = set() |
| + self.after = None |
| + self.launch_receipt = True |
| + |
| + def box(self, iid): |
| + boot = "boot-" + iid |
| + return dict(v=1, iid=iid, boot_id=boot, account=self.c["account"], |
| + region=self.c["region"], group=self.c["group"], |
| + config_digest="c" * 64, box_ref="g-" + iid[2:], |
| + binary_sha256=OLD, permit={"state": "absent"}, |
| + edge=dict(state="known", pid=100, start_time="100", |
| + identity=boot + ":100:100", started_at=roll.stamp(self.now - 60)), |
| + health=dict(state="healthy", code=200)) |
| + |
| + def sleep(self, seconds): |
| + self.now += seconds |
| + if self.deadline and self.now >= self.deadline and self.states[IID] == "Pending:Wait": |
| + self.states[IID] = "Terminated" |
| + self.abandons += 1 |
| + self.launches += 1 |
| + self.deadline = None |
| + |
| + def request(self, op, args): |
| + self.calls.append((op, copy.deepcopy(args))) |
| + write = op in ("minimum", "enter", "exit", "complete", "desired") or ( |
| + op == "session" and args["verb"] != "status") |
| + if write and self.fail_before and self.fault_at == len(self.writes) + 1: |
| + self.fault_at = None |
| + raise Death(op) |
| + result = self.perform(op, args) |
| + if write: |
| + name = args["verb"] if op == "session" else op |
| + self.writes.append(name) |
| + if self.after: |
| + self.after(name) |
| + if self.fault_at == len(self.writes): |
| + fault, self.fault_at = self.fault, None |
| + if fault == "death": |
| + raise Death(name) |
| + raise roll.Uncertain(name) |
| + return copy.deepcopy(result) |
| + |
| + def perform(self, op, a): |
| + if op == "group": |
| + return dict(name=self.c["group"], arn=self.c["group_arn"], |
| + deployment=self.c["deployment"], region=self.c["region"], |
| + minimum=self.minimum, desired=self.desired, maximum=self.maximum, |
| + members=dict(self.states), healthy={i: True for i in self.states}, |
| + target_groups=self.c["target_groups"], |
| + template={"LaunchTemplateId": "lt-example", "Version": "1"}) |
| + if op == "targets": |
| + return dict(self.tg) |
| + if op == "online": |
| + return self.online |
| + if op == "hooks": |
| + return dict(name=self.c["hook"], timeout=900, default="ABANDON", |
| + transition="autoscaling:EC2_INSTANCE_LAUNCHING") |
| + if op == "activities": |
| + return self.activity |
| + if op == "edges": |
| + if self.outage: |
| + raise roll.Uncertain("edges") |
| + iid = next(i for i, s in self.boxes.items() if s["box_ref"] == a["box_ref"]) |
| + return dict(v=1, box=a["box_ref"], generation=roll.stamp(self.now), |
| + admitted=self.admitted, box_role="serve") |
| + if op == "minimum": |
| + self.minimum = a["value"] |
| + return {} |
| + if op == "desired": |
| + self.desired = a["value"] |
| + return {} |
| + if op == "enter": |
| + self.states[IID] = "Standby" |
| + self.tg[IID] = "unused" |
| + if a["decrement"]: |
| + self.desired -= 1 |
| + else: |
| + self.launches += 1 |
| + return {} |
| + if op == "exit": |
| + self.exits += 1 |
| + self.desired += 1 |
| + self.states[IID] = "Pending:Wait" if self.hook else "InService" |
| + self.tg[IID] = "initial" if self.hook else "healthy" |
| + self.activity = [dict(id="exit-1", iid=IID, time=self.now)] |
| + if self.hook: |
| + self.deadline = self.now + 900 |
| + if self.loss_after_exit: |
| + self.admitted = False |
| + return {"activity": "exit-1"} |
| + if op == "complete": |
| + assert a == dict(iid=IID, hook=self.c["hook"], result="CONTINUE") |
| + self.continues += 1 |
| + self.states[IID] = "InService" |
| + self.tg[IID] = "healthy" |
| + return {} |
| + if op == "session": |
| + s = self.boxes[a["iid"]] |
| + verb = a["verb"] |
| + if verb == "status": |
| + p = s["permit"] |
| + if p["state"] == "present": |
| + p["accepted"] = p["expires"] > self.now |
| + p["consumed"] = (p["transaction"], p["action"]) in self.used |
| + return s |
| + if verb == "prepare": |
| + if self.prepare_bad: |
| + raise roll.Refusal("prepare") |
| + return dict(v=1, artifact_sha256=a["sha256"], old_binary_sha256=OLD, |
| + cache_state="verified", request_written=True, config_check="valid") |
| + if verb == "permit": |
| + p = a["permit"] |
| + assert self.states[IID] == "Standby" and self.tg[IID] == "unused" |
| + assert self.desired == self.minimum == 1 and self.maximum == 2 |
| + assert (p["transaction"], p["action"]) not in self.used |
| + s["permit"] = dict(p, state="present", accepted=True, consumed=False) |
| + return s |
| + if verb == "revoke": |
| + s["permit"] = {"state": "absent"} |
| + return {} |
| + if verb in ("apply", "rollback"): |
| + p = s["permit"] |
| + assert p["action"] == verb and p["accepted"] and not p["consumed"] |
| + assert self.states[IID] == "Standby" |
| + self.used.add((p["transaction"], verb)) |
| + s["binary_sha256"] = p["new_sha256"] if verb == "apply" else p["old_sha256"] |
| + s["edge"].update(pid=101 if verb == "apply" else 102, |
| + identity=verb + "-process", started_at=roll.stamp(self.now)) |
| + self.now += 1 |
| + if self.outage: |
| + self.admitted = False |
| + s["health"] = dict(state="unhealthy", code=503) |
| + return {} |
| + raise AssertionError((op, a)) |
| + |
| + |
| +class StandbyTests(unittest.TestCase): |
| + def setUp(self): |
| + base = os.environ.get("TMPDIR") or str(Path.home() / ".cache") |
| + self.tmp = tempfile.TemporaryDirectory(prefix="region-roll-test-", dir=base) |
| + self.addCleanup(self.tmp.cleanup) |
| + self.config = dict(deployment="example", account="0" * 12, region="eu-west-1", |
| + group="example-group", hook="example-launch", |
| + group_arn="arn:aws:autoscaling:eu-west-1:" + "0" * 12 + |
| + ":autoScalingGroup:example:autoScalingGroupName/example-group", |
| + target_groups=["arn:aws:elasticloadbalancing:eu-west-1:" + "0" * 12 + |
| + ":targetgroup/example-" + p + "/" + p * 16 for p in ("8", "4")], |
| + bucket="example-deployment", document="AWS-StartNonInteractiveCommand", |
| + state_dir=self.tmp.name, profile="example") |
| + self.fake = Fake(self.config) |
| + self.output = io.StringIO() |
| + self.store = roll.State(self.config, owner=os.geteuid()) |
| + self.store.observation.write_text(json.dumps(dict( |
| + v=1, group_arn=self.config["group_arn"], hook=self.config["hook"], |
| + template=self.fake.perform("group", {})["template"], documented_no_hook=True))) |
| + self.store.observation.chmod(0o600) |
| + |
| + def engine(self, journal=None): |
| + return roll.Operator(self.config, self.fake, self.store, journal=journal, |
| + clock=lambda: self.fake.now, sleep=self.fake.sleep, |
| + output=self.output, attended_by="test operator") |
| + |
| + def run_roll(self): |
| + with self.store.lock(): |
| + op = self.engine() |
| + try: |
| + return op.roll(IID, NEW) |
| + finally: |
| + if op.j: |
| + op.j.close() |
| + |
| + def resume(self, returning=False): |
| + with self.store.lock(): |
| + journal = self.store.load(self.store.active_id()) |
| + try: |
| + op = self.engine(journal) |
| + return op.return_member() if returning else op.resume() |
| + finally: |
| + journal.close() |
| + |
| + def assert_retained(self): |
| + self.assertEqual(set(self.fake.states), {IID, PEER}) |
| + self.assertEqual(self.fake.launches, 0) |
| + self.assertEqual(self.fake.abandons, 0) |
| + self.assertTrue(all(op != "desired" for op, _ in self.fake.calls)) |
| + |
| + def test_standby_roll_order(self): |
| + self.run_roll() |
| + self.assertEqual(self.fake.writes, ["prepare", "minimum", "enter", "permit", "apply", |
| + "exit", "minimum", "revoke"]) |
| + self.assertEqual((self.fake.minimum, self.fake.desired, self.fake.maximum), (2, 2, 2)) |
| + self.assertEqual(self.fake.boxes[IID]["binary_sha256"], NEW) |
| + self.assertIsNone(self.store.active_id()) |
| + self.assert_retained() |
| + |
| + def test_standby_response_loss(self): |
| + for boundary in range(1, 9): |
| + with self.subTest(boundary=boundary): |
| + self.setUp() |
| + self.fake.fault, self.fake.fault_at = "loss", boundary |
| + try: |
| + self.run_roll() |
| + except (roll.Refusal, roll.Uncertain): |
| + pass |
| + if self.store.active_id(): |
| + self.resume() |
| + self.assertEqual(self.fake.states[IID], "InService") |
| + self.assertEqual(self.fake.exits, 1) |
| + self.assert_retained() |
| + |
| + def test_standby_resume(self): |
| + for boundary in range(1, 9): |
| + with self.subTest(boundary=boundary): |
| + self.setUp() |
| + self.fake.fault, self.fake.fault_at = "death", boundary |
| + with self.assertRaises(Death): |
| + self.run_roll() |
| + self.resume() |
| + self.assertEqual(self.fake.minimum, 2) |
| + self.assertEqual(self.fake.exits, 1) |
| + self.assert_retained() |
| + |
| + def test_standby_resume_before_every_write(self): |
| + for boundary in range(1, 9): |
| + with self.subTest(boundary=boundary): |
| + self.setUp() |
| + self.fake.fail_before = True |
| + self.fake.fault_at = boundary |
| + with self.assertRaises(Death): |
| + self.run_roll() |
| + self.resume() |
| + self.assertEqual(self.fake.minimum, 2) |
| + self.assertEqual(self.fake.exits, 1) |
| + self.assert_retained() |
| + |
| + def test_standby_shared_outage(self): |
| + # The fault starts only after preparation and peer preflight. |
| + self.fake.after = lambda name: setattr(self.fake, "outage", True) if name == "permit" else None |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + self.assertEqual(self.fake.states[IID], "Standby") |
| + self.assertGreaterEqual(self.fake.now, 1800000900) |
| + self.assertEqual((self.fake.exits, self.fake.continues), (0, 0)) |
| + self.assertIsNotNone(self.store.active_id()) |
| + self.assert_retained() |
| + self.fake.outage = False |
| + self.fake.admitted = True |
| + self.fake.boxes[IID]["health"] = dict(state="healthy", code=200) |
| + self.resume() |
| + self.assert_retained() |
| + |
| + def test_standby_exit_pending_wait(self): |
| + self.fake.hook = True |
| + self.run_roll() |
| + self.assertEqual(self.fake.continues, 1) |
| + self.assertTrue(self.store.blocked.exists()) |
| + self.assert_retained() |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + |
| + def test_standby_exit_pending_wait_resume_and_loss(self): |
| + for fault, boundary in (("death", 6), ("death", 7), ("loss", 6), ("loss", 7)): |
| + with self.subTest(fault=fault, boundary=boundary): |
| + self.setUp() |
| + self.fake.hook = True |
| + self.fake.fault, self.fake.fault_at = fault, boundary |
| + try: |
| + self.run_roll() |
| + except (Death, roll.Refusal, roll.Uncertain): |
| + pass |
| + if self.store.active_id(): |
| + self.resume() |
| + self.assertEqual(self.fake.continues, 1) |
| + self.assertEqual(self.fake.exits, 1) |
| + self.assert_retained() |
| + |
| + def test_standby_exit_pending_wait_admission_loss(self): |
| + self.fake.hook = self.fake.loss_after_exit = True |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + self.assertLess(self.fake.now, self.fake.deadline) |
| + self.assertEqual(self.fake.continues, 0) |
| + self.assertIn("FAIL", self.output.getvalue()) |
| + self.fake.sleep(901) |
| + self.assertEqual(self.fake.abandons, 1) |
| + with self.assertRaises(roll.Refusal): |
| + self.resume() |
| + |
| + def test_precheck_failures_before_minimum(self): |
| + cases = (lambda: setattr(self.fake, "online", False), |
| + lambda: setattr(self.fake, "prepare_bad", True), |
| + lambda: setattr(self.fake, "minimum", 1), |
| + lambda: self.fake.boxes[IID].update(group="wrong"), |
| + lambda: self.fake.boxes[PEER]["health"].update(state="unknown"), |
| + lambda: setattr(self.fake, "admitted", False)) |
| + for change in cases: |
| + with self.subTest(change=change): |
| + self.setUp() |
| + change() |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + self.assertNotIn("minimum", self.fake.writes) |
| + self.assertNotIn("enter", self.fake.writes) |
| + |
| + def test_lock_refuses_second_writer(self): |
| + with self.store.lock(): |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + self.assertEqual(self.fake.writes, []) |
| + |
| + def test_rollback_same_transaction(self): |
| + self.fake.fault, self.fake.fault_at = "death", 5 |
| + with self.assertRaises(Death): |
| + self.run_roll() |
| + tx = self.store.active_id() |
| + with self.store.lock(): |
| + op = self.engine(self.store.load(tx)) |
| + try: |
| + op.rollback(IID) |
| + finally: |
| + op.j.close() |
| + self.assertEqual(self.fake.boxes[IID]["binary_sha256"], OLD) |
| + self.assertEqual(self.fake.writes[5:9], ["revoke", "permit", "rollback", "exit"]) |
| + self.assertEqual(self.fake.used, {(tx, "apply"), (tx, "rollback")}) |
| + self.assert_retained() |
| + |
| + def test_standby_rollback_crash_boundaries(self): |
| + for boundary in range(6, 12): |
| + with self.subTest(boundary=boundary): |
| + self.setUp() |
| + self.fake.fault, self.fake.fault_at = "death", 5 |
| + with self.assertRaises(Death): |
| + self.run_roll() |
| + tx = self.store.active_id() |
| + self.fake.fault_at = boundary |
| + with self.store.lock(): |
| + op = self.engine(self.store.load(tx)) |
| + try: |
| + with self.assertRaises(Death): |
| + op.rollback(IID) |
| + finally: |
| + op.j.close() |
| + self.resume() |
| + self.assertEqual(self.fake.boxes[IID]["binary_sha256"], OLD) |
| + self.assertEqual(self.fake.states[IID], "InService") |
| + self.assert_retained() |
| + |
| + def test_standby_preinservice_is_not_inservice(self): |
| + describe = self.fake.perform |
| + polls = 0 |
| + |
| + def perform(op, a): |
| + nonlocal polls |
| + result = describe(op, a) |
| + if op == "exit": |
| + self.fake.states[IID] = "PreInService" |
| + if op == "group" and self.fake.states[IID] == "PreInService": |
| + polls += 1 |
| + if polls == 3: |
| + self.fake.states[IID] = "InService" |
| + if op == "minimum" and a["value"] == 2: |
| + self.assertEqual(self.fake.states[IID], "InService") |
| + return result |
| + |
| + self.fake.perform = perform |
| + self.run_roll() |
| + self.assertGreaterEqual(polls, 3) |
| + self.assertEqual(self.fake.exits, 1) |
| + |
| + def test_standby_pending_proceed_no_duplicate_completion(self): |
| + self.fake.hook = True |
| + perform = self.fake.perform |
| + polls = 0 |
| + |
| + def delayed(op, a): |
| + nonlocal polls |
| + result = perform(op, a) |
| + if op == "complete": |
| + self.fake.states[IID] = "Pending:Proceed" |
| + if op == "group" and self.fake.states[IID] == "Pending:Proceed": |
| + polls += 1 |
| + if polls == 3: |
| + self.fake.states[IID] = "InService" |
| + return result |
| + |
| + self.fake.perform = delayed |
| + self.run_roll() |
| + self.assertGreaterEqual(polls, 3) |
| + self.assertEqual(self.fake.continues, 1) |
| + |
| + def test_rev1_receipt_suppression_reaches_default_abandon(self): |
| + self.fake.hook = True |
| + self.fake.states[IID] = "Standby" |
| + self.fake.desired = self.fake.minimum = 1 |
| + self.fake.request("exit", dict(iid=IID)) |
| + self.assertTrue(self.fake.launch_receipt) |
| + self.fake.sleep(901) |
| + self.assertEqual(self.fake.abandons, 1) |
| + self.assertEqual(self.fake.states[IID], "Terminated") |
| + # The production-path witness above starts with the same valid receipt |
| + # and must complete exactly once, instead of taking this rev-1 path. |
| + |
| + def test_standby_completion_retry_budget_and_journal(self): |
| + self.fake.hook = True |
| + request = self.fake.request |
| + attempts = [] |
| + |
| + def fail_completion(op, a): |
| + if op == "complete": |
| + attempts.append(self.fake.now) |
| + raise roll.Uncertain("response lost before acceptance") |
| + return request(op, a) |
| + |
| + self.fake.request = fail_completion |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + self.assertEqual(len(attempts), 4) |
| + self.assertEqual([b - a for a, b in zip(attempts, attempts[1:])], [1, 2, 4]) |
| + j = self.store.load(self.store.active_id()) |
| + try: |
| + actions = [r for r in j.events if r["kind"] == "return-action"] |
| + self.assertEqual([r["attempt"] for r in actions], [1, 2, 3, 4]) |
| + self.assertEqual(len(set(tuple(r["key"]) for r in actions)), 1) |
| + self.assertIsNotNone(j.last("failed-probe")) |
| + finally: |
| + j.close() |
| + with self.assertRaises(roll.Refusal): |
| + self.resume() |
| + self.assertEqual(len(attempts), 4) |
| + self.assertLess(self.fake.now, self.fake.deadline) |
| + |
| + def test_standby_return_process_or_transaction_changes(self): |
| + for kind in ("process", "transaction", "boot"): |
| + with self.subTest(kind=kind): |
| + self.setUp() |
| + self.fake.fault, self.fake.fault_at = "death", 5 |
| + with self.assertRaises(Death): |
| + self.run_roll() |
| + if kind == "transaction": |
| + self.fake.boxes[IID]["permit"]["transaction"] = "other" |
| + elif kind == "boot": |
| + self.fake.boxes[IID]["boot_id"] = "other" |
| + else: |
| + self.fake.boxes[IID]["edge"]["identity"] = self.fake.boxes[IID]["boot_id"] + ":100:100" |
| + with self.assertRaises(roll.Refusal): |
| + self.resume(returning=True) |
| + self.assertEqual(self.fake.exits, 0) |
| + self.assert_retained() |
| + |
| + def test_standby_post_exit_api_loss_fails_immediately(self): |
| + self.fake.hook = True |
| + request = self.fake.request |
| + |
| + def fail_describe(op, a): |
| + if op == "group" and self.fake.exits: |
| + raise roll.Uncertain("API unavailable") |
| + return request(op, a) |
| + |
| + self.fake.request = fail_describe |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + self.assertLess(self.fake.now, self.fake.deadline) |
| + self.assertEqual(self.fake.continues, 0) |
| + self.assertIn("FAIL", self.output.getvalue()) |
| + |
| + def test_consumed_uncertain_action_never_replays(self): |
| + self.fake.fault, self.fake.fault_at = "death", 5 |
| + with self.assertRaises(Death): |
| + self.run_roll() |
| + self.fake.boxes[IID]["binary_sha256"] = OLD |
| + before = list(self.fake.writes) |
| + with self.assertRaises(roll.Refusal): |
| + self.resume() |
| + self.assertEqual(self.fake.writes, before) |
| + self.assertEqual(self.fake.states[IID], "Standby") |
| + |
| + def test_permit_readiness_requires_action_and_unconsumed(self): |
| + for field, value in (("accepted", False), ("consumed", True), ("action", "repair")): |
| + with self.subTest(field=field): |
| + self.setUp() |
| + self.fake.fault, self.fake.fault_at = "death", 4 |
| + with self.assertRaises(Death): |
| + self.run_roll() |
| + original = self.fake.perform |
| + |
| + def status(op, a): |
| + result = original(op, a) |
| + if op == "session" and a["verb"] == "status" and a["iid"] == IID: |
| + result["permit"][field] = value |
| + return result |
| + |
| + self.fake.perform = status |
| + with self.assertRaises(roll.Refusal): |
| + self.resume() |
| + self.assertNotIn("apply", self.fake.writes) |
| + |
| + def test_stale_and_racing_readiness(self): |
| + for race in ("generation", "slow", "restart"): |
| + with self.subTest(race=race): |
| + self.setUp() |
| + request = self.fake.request |
| + |
| + def racing(op, a): |
| + result = request(op, a) |
| + if op == "edges": |
| + if race == "generation": |
| + result["generation"] = self.fake.boxes[IID]["edge"]["started_at"] |
| + elif race == "slow": |
| + self.fake.sleep(6) |
| + else: |
| + self.fake.boxes[IID]["edge"]["identity"] += "-restarted" |
| + return result |
| + |
| + self.fake.request = racing |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + self.assertEqual(self.fake.writes, []) |
| + |
| + def test_journal_missing_or_corrupt_refuses_before_write(self): |
| + for fault in ("missing", "partial", "changed", "lost-active", "symlink"): |
| + with self.subTest(fault=fault): |
| + self.setUp() |
| + self.fake.fault, self.fake.fault_at = "death", 3 |
| + with self.assertRaises(Death): |
| + self.run_roll() |
| + tx = self.store.active_id() |
| + path = self.store.directory / (tx + ".jsonl") |
| + if fault == "missing": |
| + path.unlink() |
| + elif fault == "partial": |
| + with path.open("ab") as file: |
| + file.write(b'{"partial":') |
| + elif fault == "changed": |
| + data = path.read_bytes().replace(NEW.encode(), OLD.encode(), 1) |
| + path.write_bytes(data) |
| + elif fault == "lost-active": |
| + self.store.active.unlink() |
| + else: |
| + original = path.with_suffix(".saved") |
| + path.rename(original) |
| + path.symlink_to(original) |
| + before = list(self.fake.writes) |
| + with self.assertRaises((roll.Refusal, OSError)): |
| + self.resume() |
| + self.assertEqual(before, self.fake.writes) |
| + |
| + def test_plan_collects_refusals_without_mutation(self): |
| + self.fake.minimum = 1 |
| + self.fake.online = False |
| + self.fake.tg[PEER] = "unhealthy" |
| + with self.store.lock(): |
| + op = self.engine() |
| + try: |
| + self.assertFalse(op.plan(IID, NEW)) |
| + finally: |
| + op.j.close() |
| + self.assertEqual(self.fake.writes, []) |
| + self.assertIn(roll.TEXT["offline"], self.output.getvalue()) |
| + self.assertIn(roll.TEXT["shape"], self.output.getvalue()) |
| + self.assertIn(roll.TEXT["peer"], self.output.getvalue()) |
| + |
| + |
| +class AdapterTests(unittest.TestCase): |
| + setUp = StandbyTests.setUp |
| + |
| + def test_config_strict_and_no_real_defaults(self): |
| + self.assertEqual(roll.validate_config(self.config), self.config) |
| + for key, value in (("account", "wrong"), ("group_arn", "arn:wrong"), |
| + ("state_dir", "relative"), ("document", "SSM-SessionManagerRunShell"), |
| + ("profile", "a;touch invalid"), ("unknown", True)): |
| + with self.subTest(key=key): |
| + with self.assertRaises(roll.Refusal): |
| + roll.validate_config(dict(self.config, **{key: value})) |
| + with self.assertRaises(roll.Refusal): |
| + roll.decode('{"account":"a","account":"b"}') |
| + |
| + def test_api_shapes_match_policy_and_remote_verbs(self): |
| + adapter = roll.AWS(self.config) |
| + calls = [] |
| + |
| + def invoke(service, verb, args, **kwargs): |
| + calls.append((service, verb, args, kwargs)) |
| + if verb == "exit-standby": |
| + return {"Activities": [{"ActivityId": "activity"}]} |
| + if verb == "get-object": |
| + return {"admitted": True} |
| + if verb == "start-session": |
| + params = json.loads(args[args.index("--parameters") + 1]) |
| + command = params["command"][0] |
| + self.assertTrue(command.startswith("/usr/bin/env -i ")) |
| + self.assertIn("/bin/sh -c ", command) |
| + self.assertIn("/opt/carlos/carlos system", command) |
| + self.assertNotIn("systemctl", command) |
| + nonce = roll.re.search(r"([0-9a-f]{32}):BEGIN", command)[1] |
| + return "Starting session\n" + nonce + ":BEGIN\n{}\n" + nonce + ":END:0\nExiting session\n" |
| + return {} |
| + |
| + with patch.object(adapter, "invoke", side_effect=invoke): |
| + adapter.request("minimum", {"value": 1}) |
| + adapter.request("enter", {"iid": IID, "decrement": True}) |
| + adapter.request("exit", {"iid": IID}) |
| + adapter.request("complete", {"iid": IID, "hook": self.config["hook"], "result": "CONTINUE"}) |
| + adapter.request("edges", {"box_ref": "g-example"}) |
| + for verb in ("status", "prepare", "permit", "revoke", "apply", "rollback"): |
| + adapter.request("session", dict(iid=IID, verb=verb, sha256=NEW, permit={"v": 1})) |
| + self.assertEqual([(s, v) for s, v, _, _ in calls[:5]], [ |
| + ("autoscaling", "update-auto-scaling-group"), ("autoscaling", "enter-standby"), |
| + ("autoscaling", "exit-standby"), ("autoscaling", "complete-lifecycle-action"), |
| + ("s3api", "get-object")]) |
| + self.assertNotIn("--desired-capacity", calls[0][2]) |
| + self.assertEqual(calls[3][3]["timeout"], 2) |
| + self.assertIn("--instance-id", calls[3][2]) |
| + self.assertNotIn("--lifecycle-action-token", calls[3][2]) |
| + self.assertIn("control/edges/g-example.json", calls[4][2]) |
| + self.assertTrue(calls[4][3]["object_body"]) |
| + |
| + def test_remote_frame_and_root_failure_refuse(self): |
| + adapter = roll.AWS(self.config) |
| + for body in ("", "{}", "session closed", "wrong:BEGIN\n{}\nwrong:END:0\n"): |
| + with patch.object(adapter, "invoke", return_value=body): |
| + with self.assertRaises(roll.Refusal): |
| + adapter.request("session", dict(iid=IID, verb="status")) |
| + command = roll.AWS.remote_command(dict(verb="status"), "nonce") |
| + self.assertIn('id -u', command) |
| + self.assertIn('exit 77', command) |
| + self.assertNotIn('sudo', command) |
| + |
| + def test_remote_shell_preserves_permit_bytes(self): |
| + root = Path(self.tmp.name) |
| + # Execute the generated framing shell against fixture executables only. |
| + # No root verb, live account, or /opt file is opened by this test. |
| + fake_id, fake_binary = root / "id", root / "carlos" |
| + fake_id.write_text("#!/bin/sh\nprintf '0\\n'\n") |
| + fake_binary.write_text("#!/bin/sh\ncat\n") |
| + fake_id.chmod(0o700) |
| + fake_binary.chmod(0o700) |
| + permit = {"transaction": "example", "old_sha256": OLD, "new_sha256": NEW} |
| + command = roll.AWS.remote_command(dict(verb="permit", permit=permit), "nonce") |
| + argv = shlex.split(command) |
| + script = argv[argv.index("-c") + 1].replace("/opt/carlos/carlos", shlex.quote(str(fake_binary))) |
| + result = subprocess.run(["/bin/sh", "-c", script], capture_output=True, text=True, |
| + env=dict(os.environ, PATH=str(root) + ":/usr/bin:/bin"), timeout=5) |
| + self.assertEqual(result.returncode, 0) |
| + self.assertIn(roll.encoded(permit).decode(), result.stdout) |
| + self.assertIn("nonce:END:0", result.stdout) |
| + |
| + def test_cli_flags_and_retry_environment(self): |
| + seen = [] |
| + |
| + class Process: |
| + pid = 123456 |
| + |
| + def __init__(self, command, **kwargs): |
| + seen.append((command, kwargs)) |
| + kwargs["stdout"].write(b'{}') |
| + |
| + def wait(self, timeout=None): |
| + return 0 |
| + |
| + adapter = roll.AWS(self.config) |
| + with patch.object(roll.subprocess, "Popen", Process): |
| + adapter.invoke("autoscaling", "describe-lifecycle-hooks", []) |
| + command, kwargs = seen[0] |
| + for flag in ("--profile", "--region", "--output", "--no-cli-pager", "--no-paginate", |
| + "--cli-read-timeout", "--cli-connect-timeout"): |
| + self.assertIn(flag, command) |
| + self.assertEqual(kwargs["env"]["AWS_MAX_ATTEMPTS"], "1") |
| + self.assertTrue(kwargs["start_new_session"]) |
| + self.assertEqual(kwargs["stdin"], subprocess.DEVNULL) |
| + |
| + def test_session_pty_captures_noninteractive_output(self): |
| + result = roll.AWS.session_output( |
| + [sys.executable, "-c", "import os; print('terminal=' + str(os.isatty(1))); print('complete')"], |
| + dict(os.environ), 5) |
| + self.assertIn("terminal=True", result) |
| + self.assertIn("complete", result) |
| + |
| + def test_session_pty_timeout(self): |
| + with self.assertRaises(roll.Uncertain): |
| + roll.AWS.session_output([sys.executable, "-c", "import time; time.sleep(10)"], dict(os.environ), 0.1) |
| + |
| + def test_fsync_precedes_provider_write(self): |
| + trace = [] |
| + original_fsync = roll.os.fsync |
| + request = self.fake.request |
| + |
| + def sync(fd): |
| + trace.append("sync") |
| + return original_fsync(fd) |
| + |
| + def call(op, a): |
| + self.assertEqual(trace[-1], "sync") |
| + trace.append("api") |
| + return request(op, a) |
| + |
| + self.fake.request = call |
| + with patch.object(roll.os, "fsync", side_effect=sync): |
| + with self.store.lock(): |
| + op = roll.Operator(self.config, self.fake, self.store, |
| + clock=lambda: self.fake.now, sleep=self.fake.sleep, output=self.output) |
| + try: |
| + op.roll(IID, NEW) |
| + sessions = [r for r in op.j.events if r["kind"] == "intent" and r["op"] == "session"] |
| + self.assertEqual([r["session"] for r in sessions], list(range(1, len(sessions) + 1))) |
| + finally: |
| + op.j.close() |
| + |
| + |
| +class MutationTests(unittest.TestCase): |
| + def test_eight_required_mutations(self): |
| + source = Path(roll.__file__).read_text() |
| + cases = [ |
| + ("decrement=false", [("decrement=True)", "decrement=False)")], "test_standby_roll_order"), |
| + ("permit-before-Standby", [ |
| + ('self.call("enter", iid=h["iid"], decrement=True)', |
| + 'self.box(h["iid"], "permit", permit={})\n self.call("enter", iid=h["iid"], decrement=True)')], |
| + "test_standby_roll_order"), |
| + ("blind desired reset", [ |
| + ('result = self.call("exit", iid=iid)', |
| + 'result = self.call("exit", iid=iid)\n self.call("desired", value=h["n"])')], |
| + "test_standby_roll_order"), |
| + ("exit-on-timeout", [ |
| + ('self.alert("timeout")', 'self.call("exit", iid=self.header["iid"])\n self.alert("timeout")')], |
| + "test_standby_shared_outage"), |
| + ("ignored transaction lock", [ |
| + ('fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)', 'pass')], "test_lock_refuses_second_writer"), |
| + ("original receipt suppresses return completion", [ |
| + ('self.call("complete", iid=iid, hook=self.c["hook"], result="CONTINUE")', 'self.sleep(901)')], |
| + "test_standby_exit_pending_wait"), |
| + ("completion before fresh admission", [ |
| + ('try:\n ready = self.readiness(iid, maintenance=True)', |
| + 'try:\n self.call("complete", iid=iid, hook=self.c["hook"], result="CONTINUE")\n ready = self.readiness(iid, maintenance=True)')], |
| + "test_standby_exit_pending_wait_admission_loss"), |
| + ("PreInService as InService", [('== "InService"', 'in {"InService", "PreInService"}')], |
| + "test_standby_preinservice_is_not_inservice"), |
| + ] |
| + for name, replacements, test in cases: |
| + with self.subTest(mutation=name): |
| + changed = source |
| + for old, new in replacements: |
| + self.assertIn(old, changed) |
| + changed = changed.replace(old, new) |
| + mutant = types.ModuleType("region_roll_mutant") |
| + mutant.__file__ = roll.__file__ |
| + exec(compile(changed, roll.__file__, "exec"), mutant.__dict__) |
| + output = io.StringIO() |
| + with patch.object(sys.modules[__name__], "roll", mutant): |
| + result = unittest.TextTestRunner(stream=output).run(unittest.TestSuite([StandbyTests(test)])) |
| + self.assertFalse(result.wasSuccessful(), name + " survived\n" + output.getvalue()) |
| + print("mutation caught: " + name, file=sys.stderr) |
| + |
| + |
| +if __name__ == "__main__": |
| + unittest.main() |