region HA: replace and remove transactions; roll drains first
scripts/region-group-roll.py gains replace and remove beside roll (spec 25.6, 25.9, 25.15). All three share one shape: preflight and the floor, lower minimum, EnterStandby with decrement, verified deregistration, drain, a re-read of every lock that names the member, the fence and incarnation check (H5), then the action. - replace stops carlos-edge.service under the fence, proves MainPID 0, terminates the Standby member without decrement, restores desired then minimum, and watches the replacement (admitted, healthy in both target groups, ha_take: 1) and the departure. fence-clear is moot. - remove leaves desired and minimum at N-1, refuses an unserved pool or fewer than 2 survivors, and names box_count for tofu. - roll drains before apply; after ExitStandby it lifts the fence with fence-clear, then restores minimum. Without the floor it uses DR-4's lock-free rule and says so; replace and remove refuse. - H4: the adapter refuses any desired-lowering call other than the member's EnterStandby with decrement; terminate is Standby-only and never decrements. AWS docs cited at the adapter; the Standby case is a live-check item, and the tool FAILs if desired or membership moves. - A failed drain or pre-action check returns the member, restores the shape and prints the drain --cancel instruction. No override. - Optional config keys ha_floor and data_prefix. - The operator document's Branch T admits the three new exact forms. Tests: scripts/region_group_held_test.py (fakes, argv, adapter H4 trap) and document pattern witnesses; 19/19 mutations killed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
infra/modules/region-group-operator-document/README.md+7 −0infra/modules/region-group-operator-document/tool-pattern.txt+1 −1scripts/region-group-roll.py+700 −24scripts/region_group_document_test.py+36 −1scripts/region_group_held_test.py+871 −0scripts/region_group_roll_test.py+1 −1
Intent
<task-notification> <task-id>a40e6294574b2458e</task-id> <tool-use-id>toolu_01VnnJgoteM1py3gCt4oBEcp</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/a40e6294574b2458e.output</output-file> <status>completed</status> <summary>Agent "Implement Task 5: drain driver" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE. Fix round 2 makes `drain --cancel` remove the fence only when the edge is confirmed stopped. Commits: - `acb910eb` region HA: drain --cancel lifts the fence only on a confirmed stop - `a4b6f05d` census: re-propose held-requests after Task 5 fix round 2 Tests: the host covering tests pass with `-race`. The new seven-case test passes: running, timed-out probe, systemctl failure, malformed MainPID, failed identity read, no PID with no error, and confirmed stop. The no-agent test now uses a confirmed stop. Mutating the check to "any probe error counts as stopped" makes four of the seven cases fail. The census test passes after the re-propose; the #280 verdict is still owed. Contract for Task 6: when the drain socket doesn't answer, the fence is removed only if systemctl reports MainPID 0. Otherwise the fence stays and the command exits 1: - `errDrainSocketDown` if the edge is running; - `errDrainEdgeAbsent` if the probe can't tell. The tool must stop the edge and confirm it's stopped before retrying, or use `fence-clear <txn>` once the member is gone. `status` output is unchanged. Concerns: none new. Report (fix round 2 section appended): `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-held-build/.superpowers/sdd/2026-11-08-region-ha-held-requests/task-5-report.md`</result> <usage><subagent_tokens>506373</subagent_tokens><tool_uses>8</tool_uses><duration_ms>260240</duration_ms></usage> </task-notification>
diff --git a/infra/modules/region-group-operator-document/README.md b/infra/modules/region-group-operator-document/README.md| index 1950aa13f..0d90fb467 100644 |
| --- a/infra/modules/region-group-operator-document/README.md |
| +++ b/infra/modules/region-group-operator-document/README.md |
| @@ -59,8 +59,15 @@ printf %s B64 | base64 -d | /opt/carlos/carlos system group-maintenance permit & |
| /opt/carlos/carlos system group-maintenance revoke |
| /usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance apply |
| /usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance rollback |
| +/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain TX |
| +/opt/carlos/carlos system group-maintenance fence-clear TX && /opt/carlos/carlos system group-maintenance status |
| +/usr/bin/timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge.service |
| ``` |
| +`TX` is a transaction ID: 1 to 80 letters, digits, underscores or hyphens, |
| +not starting with a hyphen. The last three forms serve planned handovers |
| +(region HA spec section 25): `replace`, `remove` and the drained `roll`. |
| + |
| Branch H is test apparatus for an attended dev witness. It is absent unless |
| `harness_bundle_sha256` is set to the approved bundle's 64-character lowercase |
| hexadecimal SHA256 digest. Set it only for that witness window. During cleanup, |
diff --git a/infra/modules/region-group-operator-document/tool-pattern.txt b/infra/modules/region-group-operator-document/tool-pattern.txt| index 98a539ea0..465a605d0 100644 |
| --- a/infra/modules/region-group-operator-document/tool-pattern.txt |
| +++ b/infra/modules/region-group-operator-document/tool-pattern.txt |
| @@ -1 +1 @@ |
| -/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c '\[ "\$\(id -u\)" = 0 \] \|\| exit 77; printf '"'"'\\n[0-9a-f]{32}:BEGIN\\n'"'"'; \((/opt/carlos/carlos system group-maintenance (status|revoke)|/opt/carlos/carlos system group-maintenance prepare --sha256 [0-9a-f]{64}|printf %s [A-Za-z0-9+/=]+ \| base64 -d \| /opt/carlos/carlos system group-maintenance permit && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance (apply|rollback))\); result=\$\?; printf '"'"'\\n[0-9a-f]{32}:END:%s\\n'"'"' "\$result"' |
| +/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c '\[ "\$\(id -u\)" = 0 \] \|\| exit 77; printf '"'"'\\n[0-9a-f]{32}:BEGIN\\n'"'"'; \((/opt/carlos/carlos system group-maintenance (status|revoke)|/opt/carlos/carlos system group-maintenance prepare --sha256 [0-9a-f]{64}|printf %s [A-Za-z0-9+/=]+ \| base64 -d \| /opt/carlos/carlos system group-maintenance permit && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance (apply|rollback)|/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain [A-Za-z0-9_][A-Za-z0-9_-]{0,79}|/opt/carlos/carlos system group-maintenance fence-clear [A-Za-z0-9_][A-Za-z0-9_-]{0,79} && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge\.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge\.service)\); result=\$\?; printf '"'"'\\n[0-9a-f]{32}:END:%s\\n'"'"' "\$result"' |
diff --git a/scripts/region-group-roll.py b/scripts/region-group-roll.py| index 92f27b06a..fbe3df269 100755 |
| --- a/scripts/region-group-roll.py |
| +++ b/scripts/region-group-roll.py |
| @@ -51,6 +51,22 @@ Verify interruption behavior with the approved document on the live card. |
| The operator's AWS_CONFIG_FILE, AWS_SHARED_CREDENTIALS_FILE and AWS_CA_BUNDLE |
| pass through for profile and trust configuration. Ambient access keys, profile |
| selection and AWS_ENDPOINT_URL overrides are removed. --profile is explicit. |
| + |
| +Planned handovers (region HA spec section 25). Two optional config keys enable |
| +them: ha_floor, the first release with held requests, and data_prefix, the |
| +region's CARLOS_HIBERNATE_PREFIX ("" for none). replace and remove share one |
| +shape: preflight and the floor, lower minimum, EnterStandby with decrement, |
| +verify deregistration, drain, re-read every lock that names the member, check |
| +the start fence and the agent's incarnation, stop carlos-edge.service and prove |
| +MainPID 0, terminate without decrement, then restore and watch. replace raises |
| +desired, then minimum, back to N and watches the replacement and the departure. |
| +remove leaves desired and minimum at N-1; set box_count in tofu afterwards. |
| +roll drains before apply when the floor holds; after ExitStandby it lifts the |
| +fence with fence-clear, then restores minimum. Without the floor, roll uses |
| +DR-4's lock-free rule and says so; replace and remove refuse. Desired capacity |
| +is lowered only by the member's EnterStandby with decrement (H4). A failed |
| +drain returns the member and restores the shape; the member stays fenced and |
| +draining until the operator runs drain --cancel on it. |
| """ |
| import argparse |
| import base64 |
| @@ -58,6 +74,7 @@ from contextlib import contextmanager |
| from datetime import datetime, timezone |
| import fcntl |
| import getpass |
| +import gzip |
| import hashlib |
| import json |
| import os |
| @@ -148,13 +165,57 @@ TEXT = { |
| "rollback_digest": "The installed artifact does not match the recorded old or new digest", |
| "unsupported": "Unsupported operation", |
| "divergence": "The provider used a return hook. The member is held in Standby; further rolls are blocked.", |
| + # Planned handovers (spec section 25). Pending the controller's copy pass. |
| + "replace": "Drain one member, terminate it and let the group launch its replacement.", |
| + "remove": "Drain one member and terminate it without a replacement (scale-in).", |
| + "depart_transaction": "Transaction ID to use. It may not start with - or probe-.", |
| + "rule_drain": "Floor met: drain before the provider action (section 25).", |
| + "rule_dr4": "Floor not met: DR-4's lock-free rule applies. Replace only lock-free members.", |
| + "floor_refused": "The held-requests floor is not met, so this member cannot be drained. DR-4's lock-free rule applies", |
| + "floor_config": "The config has no ha_floor or data_prefix", |
| + "floor_box": "Live box {box} does not publish ha_take: 1", |
| + "floor_unreadable": "The edges file {key} cannot be read", |
| + "floor_template": "The pinned launch template boots release {release}, below ha_floor", |
| + "floor_version": "The roll's release {release} is below ha_floor", |
| + "drain_failed": "The drain failed. The member was returned to service and the group shape restored", |
| + "drain_cancel": "The member stays fenced and draining. To end it, run on {iid}: carlos system group-maintenance drain --cancel {transaction}", |
| + "drain_reason": "drain: {reason}", |
| + "drain_report": "The drain printed no valid report for this transaction", |
| + "fence_missing": "The start fence of this transaction is not in place", |
| + "drain_void": "The agent does not report a finished drain of this transaction", |
| + "incarnation": "The agent's incarnation changed after the drain", |
| + "lock_held": "A lock still names the member: {hosts}", |
| + "data_bucket": "The member's edges file names no data bucket in this region", |
| + "edge_running": "carlos-edge.service is still running after the stop. The member is held in Standby", |
| + "h4": "Desired capacity may only be lowered by the member's EnterStandby with decrement", |
| + "desired_changed": "Desired capacity or membership changed when the member was terminated", |
| + "remove_minimum": "remove must leave at least 2 members", |
| + "remove_pools": "The survivors would leave pool {pool} with no server", |
| + "remove_pools_unknown": "The member's served_pools are unknown", |
| + "watch_timeout": "The replacement or the departure did not finish in time", |
| + "lock_held_resume": "A lock still names the member after its edge stopped. The member is held in Standby", |
| + "fence_moot": "The member is gone, so its start fence went with it. No fence-clear is needed.", |
| + "replaced": "Member replaced.", |
| + "removed": "Member removed. Set box_count to {n} in the region's tofu and apply; the plan should show no instance change.", |
| } |
| 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 |
| -SESSION_TIMEOUTS = {"prepare": 360, "apply": 990, "rollback": 990} |
| +# The drain's own deadline is 15 min + 1 min per 20 awake hosts; this box bound |
| +# covers 900 awake hosts. The local bound adds the 30 s TERM grace and a margin. |
| +DRAIN_BOUND = 3600 |
| +EDGE_STOP_BOUND = 120 |
| +SESSION_TIMEOUTS = {"prepare": 360, "apply": 990, "rollback": 990, |
| + "drain": DRAIN_BOUND + 90, "edge-stop": EDGE_STOP_BOUND + 90, "fence-clear": 30} |
| +DEPART_KINDS = ("replace", "remove") |
| +# boxchoice.MaxEdgesAge and maxEdgesSkew: an edges file is live while its |
| +# generation is at most 15 minutes old and at most 1 minute in the future. |
| +EDGES_MAX_AGE, EDGES_SKEW = 15 * 60, 60 |
| +EDGES_KEY = re.compile(r"control/edges/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\.json\Z") |
| +BUCKET = re.compile(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]\Z") |
| +HOST_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,252}\Z") |
| class Decision(NamedTuple): |
| @@ -183,7 +244,8 @@ def classify(facts) -> Decision: |
| if context == "resume": |
| if f.get("done"): |
| return Decision("finish") |
| - if f.get("exit_intent") or f.get("hook") or f.get("hold_started"): |
| + # A failed drain stops the transaction: return the member and the shape. |
| + if f.get("exit_intent") or f.get("hook") or f.get("hold_started") or f.get("drain_failed"): |
| return Decision("return") |
| if f.get("operation_error") or f.get("describe_error"): |
| return Decision("resumable", f.get("error_reason", "api")) |
| @@ -238,6 +300,9 @@ def classify(facts) -> Decision: |
| return Decision("resumable", "shape") |
| if not f.get("peers_checked"): |
| return Decision("check-peers") |
| + # The floor decides the rule (drain or DR-4) before any group write. |
| + if not f.get("floor_checked", True): |
| + return Decision("floor") |
| return Decision("lower-minimum" if minimum == n else "enter") |
| if phase in {"Standby", "EnteringStandby"}: |
| if minimum != n - 1 or desired != n - 1: |
| @@ -292,6 +357,10 @@ class DivergenceHeld(Refusal): |
| pass |
| +class DrainFailed(Refusal): |
| + """The drain or the pre-action check failed: return the member (no override).""" |
| + |
| + |
| class Uncertain(Exception): |
| def __init__(self, message, **details): |
| super().__init__(message) |
| @@ -353,7 +422,16 @@ def below_floor(version, floor): |
| def validate_config(c): |
| keys = {"deployment", "account", "region", "group", "group_arn", "hook", |
| "target_groups", "bucket", "document", "state_dir", "profile", "min_release"} |
| - require(isinstance(c, dict) and set(c) == keys, "config_invalid") |
| + # Optional: the held-requests floor release and the hibernate prefix. |
| + optional = {"ha_floor", "data_prefix"} |
| + require(isinstance(c, dict) and keys <= set(c) <= keys | optional, "config_invalid") |
| + if "ha_floor" in c: |
| + require(release_version(c["ha_floor"]) is not None, "config_invalid") |
| + if "data_prefix" in c: |
| + require(isinstance(c["data_prefix"], str) and len(c["data_prefix"]) <= 1024 and |
| + (c["data_prefix"] == "" or |
| + re.fullmatch(r"[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*", c["data_prefix"])) and |
| + ".." not in c["data_prefix"].split("/"), "config_invalid") |
| for key in keys - {"target_groups"}: |
| require(isinstance(c[key], str) and 0 < len(c[key]) <= 1024, "config_invalid") |
| require(release_version(c["min_release"]) is not None, "config_invalid") |
| @@ -660,10 +738,26 @@ class AWS: |
| @staticmethod |
| def remote_command(a, nonce): |
| verb = a["verb"] |
| - require(verb in {"status", "prepare", "permit", "revoke", "apply", "rollback"}, "unsupported") |
| + require(verb in {"status", "prepare", "permit", "revoke", "apply", "rollback", |
| + "drain", "fence-clear", "edge-stop"}, "unsupported") |
| binary = "/opt/carlos/carlos" |
| command = binary + " system group-maintenance " + verb |
| - if verb == "prepare": |
| + if verb in {"drain", "fence-clear"}: |
| + # groupTransactionID, and never a leading "-" (the verb's own rule). |
| + tx = a["transaction"] |
| + require(isinstance(tx, str) and TX.fullmatch(tx) and not tx.startswith("-"), "record") |
| + command += " " + tx |
| + if verb == "drain": |
| + command = "/usr/bin/timeout --signal=TERM --kill-after=30s %ds %s" % (DRAIN_BOUND, command) |
| + else: |
| + command += " && " + binary + " system group-maintenance status" |
| + elif verb == "edge-stop": |
| + # Prove the process gone with systemd's own answer: MainPID 0. |
| + command = ("/usr/bin/timeout --signal=TERM --kill-after=10s %ds " |
| + "/usr/bin/systemctl stop carlos-edge.service; " |
| + "/usr/bin/systemctl show --property=MainPID --property=ActiveState " |
| + "carlos-edge.service" % EDGE_STOP_BOUND) |
| + elif verb == "prepare": |
| require(SHA.fullmatch(a["sha256"]), "prepare") |
| command += " --sha256 " + a["sha256"] |
| elif verb == "permit": |
| @@ -784,13 +878,159 @@ class AWS: |
| self.session_started(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) == 1, "remote") |
| + if a["verb"] == "drain": |
| + return self.drain_output(*match[0]) |
| + require(match[0][1] == "0", "remote") |
| + if a["verb"] == "edge-stop": |
| + return self.edge_stop_output(match[0][0]) |
| + if a["verb"] in {"status", "prepare", "permit", "fence-clear"}: |
| require(len(match[0][0].encode()) <= 8192, "remote") |
| return decode(match[0][0]) |
| return {} |
| + if op == "edges_list": |
| + keys, _ = self.list_objects(self.c["bucket"], "control/edges/") |
| + return sorted(keys) |
| + if op == "edges_key": |
| + require(isinstance(a["key"], str) and EDGES_KEY.fullmatch(a["key"]), "api") |
| + return self.invoke("s3api", "get-object", ["--bucket", self.c["bucket"], "--key", a["key"]], |
| + object_body=True) |
| + if op == "lock_hosts": |
| + prefix = self.data_prefix(a) |
| + _, prefixes = self.list_objects(a["bucket"], prefix, delimiter=True) |
| + hosts = [] |
| + for entry in prefixes: |
| + require(entry.startswith(prefix) and entry.endswith("/"), "api") |
| + hosts.append(entry[len(prefix):-1]) |
| + return sorted(hosts) |
| + if op == "lock": |
| + prefix = self.data_prefix(a) |
| + require(isinstance(a["host"], str) and HOST_NAME.fullmatch(a["host"]), "api") |
| + key = prefix + a["host"] + "/lock.json" |
| + # An absent lock is only ever S3's listing answer, never a failed GET. |
| + keys, _ = self.list_objects(a["bucket"], key) |
| + if key not in keys: |
| + return dict(absent=True) |
| + return dict(absent=False, lock=self.invoke("s3api", "get-object", [ |
| + "--bucket", a["bucket"], "--key", key], object_body=True)) |
| + if op == "template_release": |
| + return self.template_release(a["template"]) |
| + if op == "terminate": |
| + # H4. Terminating a Standby member without decrement leaves desired |
| + # unchanged. TerminateInstanceInAutoScalingGroup: "If you do not |
| + # specify the option to decrement the desired capacity, Amazon EC2 |
| + # Auto Scaling launches instances to replace the ones that are |
| + # terminated", and ShouldDecrementDesiredCapacity "indicates whether |
| + # terminating the instance also decrements the size of the Auto |
| + # Scaling group" (docs.aws.amazon.com/autoscaling/ec2/APIReference/ |
| + # API_TerminateInstanceInAutoScalingGroup.html). A Standby member |
| + # entered with decrement is already outside desired ("If you choose |
| + # to decrement the desired capacity ... this prevents the launch of |
| + # an instance to replace the one on standby", userguide/ |
| + # as-enter-exit-standby.html), so with desired = N-1 and N-1 members |
| + # in service nothing launches. The docs do not state the Standby case |
| + # outright: the operator checks it on dev, and the tool FAILs if a |
| + # later describe shows desired or membership moved. |
| + require(a.get("decrement") is False and isinstance(a.get("iid"), str) and |
| + IID.fullmatch(a["iid"]), "h4") |
| + g = self.request("group", {}) |
| + require(g["members"].get(a["iid"]) == "Standby" and g["desired"] == g["minimum"], "h4") |
| + result = self.invoke("autoscaling", "terminate-instance-in-auto-scaling-group", [ |
| + "--instance-id", a["iid"], "--no-should-decrement-desired-capacity"]) |
| + activity = result.get("Activity") if isinstance(result, dict) else None |
| + if isinstance(activity, dict) and activity.get("ActivityId"): |
| + return {"activity": activity["ActivityId"]} |
| + return {"outcome": "uncertain-success", "response": result} |
| + if op == "desired": |
| + # H4: this call only raises desired, for the transaction's restore. |
| + g = self.request("group", {}) |
| + require(type(a.get("value")) is int and g["desired"] <= a["value"] <= g["maximum"], "h4") |
| + return self.invoke("autoscaling", "update-auto-scaling-group", |
| + group + ["--desired-capacity", str(a["value"])]) |
| raise Refusal(TEXT["unsupported"]) |
| + @staticmethod |
| + def data_prefix(a): |
| + require(isinstance(a.get("bucket"), str) and BUCKET.fullmatch(a["bucket"]), "data_bucket") |
| + prefix = a.get("prefix") |
| + require(isinstance(prefix, str), "config_invalid") |
| + return prefix + "/" if prefix else "" |
| + |
| + def list_objects(self, bucket, prefix, delimiter=False): |
| + keys, prefixes, token = [], [], None |
| + for _ in range(1000): |
| + args = ["--bucket", bucket, "--prefix", prefix] |
| + if delimiter: |
| + args += ["--delimiter", "/"] |
| + if token: |
| + args += ["--continuation-token", token] |
| + r = self.invoke("s3api", "list-objects-v2", args) |
| + require(isinstance(r, dict) and isinstance(r.get("Contents", []), list) and |
| + isinstance(r.get("CommonPrefixes", []), list), "api") |
| + for row in r.get("Contents", []): |
| + require(isinstance(row, dict) and isinstance(row.get("Key"), str), "api") |
| + keys.append(row["Key"]) |
| + for row in r.get("CommonPrefixes", []): |
| + require(isinstance(row, dict) and isinstance(row.get("Prefix"), str), "api") |
| + prefixes.append(row["Prefix"]) |
| + if not r.get("IsTruncated"): |
| + return keys, prefixes |
| + token = r.get("NextContinuationToken") |
| + require(isinstance(token, str) and token, "api") |
| + raise Refusal(TEXT["api"]) |
| + |
| + def template_release(self, template): |
| + # The pinned template's CARLOS_RELEASE (group_config.release), from the |
| + # init script in its user data (infra/modules/region-host/group.tf). |
| + require(isinstance(template, dict) and isinstance(template.get("Version"), str), "scope") |
| + ref = (["--launch-template-id", template["LaunchTemplateId"]] if template.get("LaunchTemplateId") |
| + else ["--launch-template-name", template.get("LaunchTemplateName", "")]) |
| + r = self.invoke("ec2", "describe-launch-template-versions", ref + ["--versions", template["Version"]]) |
| + rows = r.get("LaunchTemplateVersions") if isinstance(r, dict) else None |
| + require(isinstance(rows, list) and len(rows) == 1 and isinstance(rows[0], dict) and |
| + str(rows[0].get("VersionNumber")) == template["Version"], "api") |
| + try: |
| + raw = base64.b64decode(rows[0]["LaunchTemplateData"]["UserData"], validate=True) |
| + if raw[:2] == b"\x1f\x8b": |
| + raw = gzip.decompress(raw) |
| + script = raw.decode() |
| + except (KeyError, TypeError, ValueError, OSError, EOFError, UnicodeError) as exc: |
| + raise Refusal(TEXT["api"]) from exc |
| + found = re.findall(r"^CARLOS_RELEASE='([^']*)'$", script, re.M) |
| + require(len(found) == 1, "api") |
| + return found[0] |
| + |
| + @staticmethod |
| + def drain_output(body, code): |
| + # The verb prints its report as one JSON line, and exits 0 only when |
| + # the report's result is ok. A refusal prints no report. |
| + require(code in ("0", "1") and len(body.encode()) <= 1024 * 1024, "remote") |
| + report = None |
| + for line in body.splitlines(): |
| + line = line.strip() |
| + if line.startswith("{"): |
| + try: |
| + candidate = decode(line) |
| + except Refusal: |
| + continue |
| + if isinstance(candidate, dict) and candidate.get("v") == 1: |
| + report = candidate |
| + return dict(exit=int(code), report=report) |
| + |
| + @staticmethod |
| + def edge_stop_output(body): |
| + props = {} |
| + for line in body.splitlines(): |
| + line = line.strip() |
| + if not line: |
| + continue |
| + key, sep, value = line.partition("=") |
| + require(sep and key in {"MainPID", "ActiveState"} and key not in props, "remote") |
| + props[key] = value |
| + require(set(props) == {"MainPID", "ActiveState"} and re.fullmatch(r"[0-9]{1,10}", props["MainPID"]), |
| + "remote") |
| + return dict(main_pid=int(props["MainPID"]), active_state=props["ActiveState"]) |
| + |
| @staticmethod |
| def activity_response(result): |
| rows = result.get("Activities", []) if isinstance(result, dict) else [] |
| @@ -802,6 +1042,7 @@ class AWS: |
| class Operator: |
| + # The roll operator also owns the planned-handover kinds (DEPART_KINDS). |
| journal_kind = "roll" |
| def __init__(self, config, adapter, state, journal=None, clock=time.time, |
| @@ -824,6 +1065,10 @@ class Operator: |
| return self.j.add(kind, at=self.clock(), **data) |
| def call(self, op, freshness=None, **args): |
| + # H4: only this transaction's member may enter Standby with decrement. |
| + if op == "enter": |
| + require(self.header is not None and args.get("iid") == self.header.get("iid") and |
| + args.get("decrement") is True, "h4") |
| 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) |
| dispatched = False |
| @@ -901,7 +1146,11 @@ class Operator: |
| e.get("admitted") is True and e.get("box_role") == "serve" and |
| instant(e.get("generation")) >= instant(s["edge"].get("started_at")) + 2 and |
| 0 <= self.clock() - observed <= 60, "admission") |
| - if maintenance: |
| + if maintenance and self.unchanged(): |
| + # A failed drain returns the member it found: no action ran. |
| + require(s["binary_sha256"] == self.header["old"] and |
| + s["edge"]["identity"] == self.header["original_process"], "process") |
| + elif maintenance: |
| action = self.action() |
| restored = self.j.last("rollback-requested", already_restored=True) |
| expected = self.header["old"] if action == "rollback" else self.header["new"] |
| @@ -912,10 +1161,10 @@ class Operator: |
| p.get("action") == ("apply" if restored else 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 |
| + return dict(observation, edges=e) |
| - def preflight(self, iid, digest): |
| - require(IID.fullmatch(iid) and SHA.fullmatch(digest), "config_invalid") |
| + def preflight(self, iid, digest=None): |
| + require(IID.fullmatch(iid) and (digest is None or SHA.fullmatch(digest)), "config_invalid") |
| require(not self.state.blocked.exists(), "blocked") |
| g = self.snapshot() |
| n = g["desired"] |
| @@ -930,15 +1179,16 @@ class Operator: |
| 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") |
| + self.member_edges = {} |
| 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) |
| + self.member_edges[member] = self.readiness(member)["edges"] |
| s = self.box(iid) |
| self.identity(s, iid) |
| require(s["permit"].get("state") == "absent", "permit") |
| - require(s["binary_sha256"] != digest, "process") |
| + require(digest is None or s["binary_sha256"] != digest, "process") |
| return g, s |
| def plan(self, iid, digest): |
| @@ -990,8 +1240,9 @@ class Operator: |
| def roll(self, iid, digest, transaction=None): |
| if transaction is not None: |
| + # The drain and fence-clear verbs refuse a leading "-". |
| require(isinstance(transaction, str) and TX.fullmatch(transaction) and |
| - not transaction.startswith("probe-"), "record") |
| + not transaction.startswith(("probe-", "-")), "record") |
| 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. |
| @@ -1026,8 +1277,12 @@ class Operator: |
| last_event=self.j.events[-1], journal=str(self.j.path)) |
| def check_journal_kind(self): |
| - require(self.j and self.j.events[0].get("header", {}).get("kind", "roll") == |
| - self.journal_kind, "journal_kind") |
| + # A subclass with its own kind (the probe) owns only that kind. |
| + kinds = (self.journal_kind,) + (DEPART_KINDS if self.journal_kind == "roll" else ()) |
| + require(self.j and self.kind() in kinds, "journal_kind") |
| + |
| + def kind(self): |
| + return self.j.events[0].get("header", {}).get("kind", "roll") |
| def abandon(self): |
| self.check_journal_kind() |
| @@ -1036,9 +1291,10 @@ class Operator: |
| # or a running binary. Even an unsent group write intent blocks closure. |
| for row in self.j.events: |
| if row["kind"] == "intent": |
| - require(row.get("op") not in {"minimum", "enter", "exit", "complete", "desired"} and |
| + require(row.get("op") not in {"minimum", "enter", "exit", "complete", "desired", "terminate"} and |
| not (row.get("op") == "session" and row["args"].get("verb") in |
| - {"permit", "revoke", "apply", "rollback"}), "abandon_refused") |
| + {"permit", "revoke", "apply", "rollback", "drain", "edge-stop", "fence-clear"}), |
| + "abandon_refused") |
| require(not self.j.last("exit-intent"), "abandon_refused") |
| if not self.j.last("done"): |
| self.event("abandoned", attended_by=self.attended) |
| @@ -1190,6 +1446,9 @@ class Operator: |
| p.get("transaction") == h["transaction"] and |
| p.get("expires") == permit["body"]["expires"], "permit") |
| self.standby(self.snapshot()) |
| + if action == "apply" and self.rule() == "drain": |
| + # H5, immediately before the action: locks, fence and incarnation. |
| + self.pre_action() |
| self.event("phase", phase="mutation", action=action) |
| try: |
| self.box(h["iid"], action) |
| @@ -1230,6 +1489,8 @@ class Operator: |
| minimum_intent=bool(self.j.last("intent", op="minimum")), |
| action_verified=bool(self.j.last("box-action-verified", action=self.action())), |
| already_restored=bool(self.j.last("rollback-requested", already_restored=True)), |
| + floor_checked=self.kind() != "roll" or bool(self.j.last("floor")), |
| + drain_failed=bool(self.j.last("drain-failed")), |
| observed=group is not None, n=h["n"]) |
| if group is not None: |
| facts.update(phase=group["members"].get(h["iid"]), |
| @@ -1254,6 +1515,8 @@ class Operator: |
| def resume(self): |
| self.restore_header() |
| + if self.kind() in DEPART_KINDS: |
| + return self.depart() |
| h = self.header |
| end = self.clock() + WAIT |
| group, error = None, None |
| @@ -1285,6 +1548,10 @@ class Operator: |
| all(t.get(member) == "healthy" for t in group["targets"]), "peer") |
| self.readiness(member) |
| observed["peers_checked"] = True |
| + elif action == "floor": |
| + prepared = self.j.last("prepared") |
| + self.floor("roll", version=prepared["result"].get("version") if prepared else None) |
| + group = None |
| elif action == "lower-minimum": |
| self.event("phase", phase="lower-minimum") |
| self.call("minimum", value=h["n"] - 1) |
| @@ -1299,6 +1566,8 @@ class Operator: |
| group = None |
| end = self.clock() + WAIT |
| elif action == "mutate": |
| + if self.rule() == "drain" and self.action() == "apply" and not self.j.last("drained"): |
| + self.drain() |
| self.mutation() |
| self.event("phase", phase="local-verification", action=self.action()) |
| group = None |
| @@ -1316,13 +1585,17 @@ class Operator: |
| observed.pop("readiness", None) |
| else: |
| raise AssertionError(decision) |
| + except DrainFailed: |
| + # Recorded as drain-failed; classify() now chooses the return. |
| + group = None |
| except (Refusal, Uncertain) as exc: |
| error = exc |
| observed["operation_error"] = True |
| def rollback(self, iid): |
| self.restore_header() |
| - require(iid == self.header["iid"] and not self.j.last("exit-intent"), "rollback_refused") |
| + require(self.kind() == "roll" and iid == self.header["iid"] and not self.j.last("exit-intent") and |
| + not self.j.last("drain-failed"), "rollback_refused") |
| # Failed apply verification is a reason to roll back. Read installed |
| # state first instead of demanding that the failed apply verify again. |
| # The root status verb refuses while apply holds its lock. A cut |
| @@ -1360,6 +1633,8 @@ class Operator: |
| """Execute classify() decisions. Sole owner of ExitStandby.""" |
| self.restore_header() |
| h, iid = self.header, self.header["iid"] |
| + # replace and remove return a member only after a failed drain. |
| + require(self.kind() not in DEPART_KINDS or self.unchanged(), "journal_kind") |
| self.event("phase", phase="return") |
| end = self.clock() + WAIT |
| group, ready, error = None, None, None |
| @@ -1389,7 +1664,7 @@ class Operator: |
| intent = self.j.last("exit-intent") |
| if intent and group["members"][iid] != "Standby": |
| require(ready["status"]["edge"]["identity"] == intent["process"], "admission") |
| - expected = h["old"] if self.action() == "rollback" else h["new"] |
| + expected = h["old"] if self.action() == "rollback" or self.unchanged() else h["new"] |
| require(ready["status"]["binary_sha256"] == expected, "process") |
| observed["readiness"] = "ok" |
| except (Refusal, Uncertain): |
| @@ -1416,6 +1691,8 @@ class Operator: |
| self.sleep(max(0, min(decision.delay, end - self.clock()))) |
| group, observed = None, {} |
| elif action == "restore-minimum": |
| + # Roll after a drain: ExitStandby, then lift the fence, then minimum. |
| + self.lift_fence() |
| self.event("returned", process=self.j.last("exit-intent")["process"]) |
| self.event("phase", phase="restore-minimum") |
| self.call("minimum", value=h["n"]) |
| @@ -1431,25 +1708,419 @@ class Operator: |
| def finish_return(self, ready): |
| h, iid = self.header, self.header["iid"] |
| + self.lift_fence() |
| s = ready["status"] |
| 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", |
| + failed_drain = self.unchanged() |
| + self.event("done", outcome="drain-failed" if failed_drain else |
| + "failed-probe-recovered" if self.j.last("failed-probe") else "returned", |
| provider_divergence=self.state.blocked.exists()) |
| self.state.finish() |
| + if failed_drain: |
| + self.say("ALERT", TEXT["drain_cancel"].format(iid=iid, transaction=h["transaction"])) |
| + raise Refusal(TEXT["drain_failed"]) |
| self.say("done", TEXT["done"]) |
| + # Planned handovers (region HA spec section 25). |
| + |
| + def unchanged(self): |
| + """A failed drain: the member returns as it was, with no action run.""" |
| + return bool(self.j and self.j.last("drain-failed")) |
| + |
| + def rule(self): |
| + floor = self.j.last("floor") if self.j else None |
| + return floor["rule"] if floor else "dr4" |
| + |
| + def floor(self, kind, version=None): |
| + """Section 25.9. Drain only if every live box publishes ha_take: 1 and |
| + the release the transaction leaves running is at or above ha_floor.""" |
| + reasons, live = [], [] |
| + floor = self.c.get("ha_floor") |
| + if floor is None or "data_prefix" not in self.c: |
| + reasons.append(TEXT["floor_config"]) |
| + else: |
| + try: |
| + for key in self.call("edges_list"): |
| + match = EDGES_KEY.fullmatch(key) |
| + if not match: |
| + continue |
| + try: |
| + e = self.call("edges_key", key=key) |
| + except (Refusal, Uncertain): |
| + reasons.append(TEXT["floor_unreadable"].format(key=key)) |
| + continue |
| + try: |
| + age = self.clock() - instant(e.get("generation") if isinstance(e, dict) else None) |
| + except Refusal: |
| + continue |
| + # DrainAckPeers' liveness: a file outside it is not a live box. |
| + if not -EDGES_SKEW <= age <= EDGES_MAX_AGE: |
| + continue |
| + live.append(match[1]) |
| + take = e.get("ha_take") |
| + if not (type(take) is int and take == 1): |
| + reasons.append(TEXT["floor_box"].format(box=match[1])) |
| + if kind == "replace": |
| + release = self.call("template_release", template=self.header["template"]) |
| + if release_version(release) is None or below_floor(release, floor): |
| + reasons.append(TEXT["floor_template"].format(release=release)) |
| + if kind == "roll" and (release_version(version) is None or below_floor(version, floor)): |
| + reasons.append(TEXT["floor_version"].format(release=version)) |
| + except (Refusal, Uncertain) as exc: |
| + reasons.append(str(exc)) |
| + rule = "dr4" if reasons else "drain" |
| + self.event("floor", rule=rule, reasons=reasons, live=live, ha_floor=floor) |
| + self.say("rule", TEXT["rule_drain"] if rule == "drain" else TEXT["rule_dr4"]) |
| + for reason in reasons: |
| + self.say("floor", reason) |
| + return rule |
| + |
| + def drain_failed(self, reasons, report=None): |
| + self.event("drain-failed", reasons=reasons, report=report) |
| + for reason in reasons: |
| + self.say("ALERT", TEXT["drain_reason"].format(reason=reason)) |
| + raise DrainFailed(TEXT["drain_failed"]) |
| + |
| + def drain(self): |
| + h = self.header |
| + tx = h["transaction"] |
| + self.event("phase", phase="drain") |
| + try: |
| + r = self.box(h["iid"], "drain", transaction=tx) |
| + except (Refusal, Uncertain) as exc: |
| + self.drain_failed([str(exc)]) |
| + report = r.get("report") if isinstance(r, dict) else None |
| + if not isinstance(report, dict): |
| + self.drain_failed([TEXT["drain_report"]]) |
| + if not (r.get("exit") == 0 and report.get("transaction") == tx and report.get("step") == "move" and |
| + report.get("result") == "ok" and report.get("fence") == tx and |
| + isinstance(report.get("incarnation"), str) and |
| + re.fullmatch(r"[0-9a-f]{32}", report["incarnation"])): |
| + reasons = report.get("reasons") |
| + if (report.get("transaction") != tx or not isinstance(reasons, list) or not reasons or |
| + not all(isinstance(x, str) for x in reasons)): |
| + reasons = [TEXT["drain_report"]] |
| + self.drain_failed(reasons[:32], report) |
| + self.event("drained", incarnation=report["incarnation"], report=report) |
| + return report |
| + |
| + def locks_naming_member(self): |
| + """Every lock in the region's data bucket that names the member and is |
| + neither a release marker nor another box's (section 25.6 step 4).""" |
| + ident = self.header["identity"] |
| + ref, iid = ident["box_ref"], self.header["iid"] |
| + e = self.call("edges", box_ref=ref) |
| + bucket = e.get("data_bucket") if isinstance(e, dict) else None |
| + require(isinstance(bucket, str) and BUCKET.fullmatch(bucket) and |
| + e.get("data_bucket_region") == self.c["region"], "data_bucket") |
| + prefix = self.c["data_prefix"] |
| + held = [] |
| + for host in self.call("lock_hosts", bucket=bucket, prefix=prefix): |
| + if not HOST_NAME.fullmatch(host): |
| + continue |
| + v = self.call("lock", bucket=bucket, prefix=prefix, host=host) |
| + if v.get("absent") is True: |
| + continue |
| + lock = v.get("lock") |
| + owner = lock.get("owner") if isinstance(lock, dict) else None |
| + if isinstance(lock, dict) and (lock.get("carlos_release") is not None or |
| + (isinstance(owner, str) and owner.startswith("released/v1;"))): |
| + continue |
| + if not isinstance(owner, str): |
| + held.append(host) |
| + elif owner.startswith("box/v1;"): |
| + fields = owner[len("box/v1;"):].split(";") |
| + if "ref=" + ref in fields or "iid=" + iid in fields: |
| + held.append(host) |
| + elif ref in owner or iid in owner: |
| + held.append(host) |
| + return held |
| + |
| + def pre_action(self): |
| + """H5 and R3.1: the locks, then the fence, the drain and the |
| + incarnation, read once more right before the provider action.""" |
| + h, tx = self.header, self.header["transaction"] |
| + drained = self.j.last("drained") |
| + try: |
| + held = self.locks_naming_member() |
| + s = self.box(h["iid"]) |
| + self.identity(s, h["iid"]) |
| + except (Refusal, Uncertain) as exc: |
| + self.drain_failed([str(exc)]) |
| + if held: |
| + self.drain_failed([TEXT["lock_held"].format(hosts=", ".join(held[:20]))]) |
| + fence, d = s.get("fence") or {}, s.get("drain") or {} |
| + if not (fence.get("state") == "present" and fence.get("transaction") == tx): |
| + self.drain_failed([TEXT["fence_missing"]]) |
| + if not (d.get("state") == "known" and d.get("transaction") == tx and d.get("step") == "move" and |
| + d.get("result") == "ok"): |
| + self.drain_failed([TEXT["drain_void"]]) |
| + if not drained or d.get("incarnation") != drained["incarnation"]: |
| + self.drain_failed([TEXT["incarnation"]]) |
| + self.event("pre-action-checked", fence=fence, drain=d) |
| + |
| + def stop_edge(self): |
| + """R3.1: stop carlos-edge.service under the fence and prove it gone.""" |
| + h, tx = self.header, self.header["transaction"] |
| + self.event("phase", phase="edge-stop") |
| + r = self.box(h["iid"], "edge-stop") |
| + if not (r.get("main_pid") == 0 and r.get("active_state") in {"inactive", "failed"}): |
| + self.alert("edge_running") |
| + s = self.box(h["iid"]) |
| + self.identity(s, h["iid"]) |
| + fence = s.get("fence") or {} |
| + if not (fence.get("state") == "present" and fence.get("transaction") == tx): |
| + self.alert("fence_missing") |
| + self.event("edge-stopped", systemd=r, fence=fence) |
| + |
| + def fence_clear(self): |
| + h = self.header |
| + s = self.box(h["iid"], "fence-clear", transaction=h["transaction"]) |
| + self.identity(s, h["iid"]) |
| + require((s.get("fence") or {}).get("state") == "absent", "fence_missing") |
| + self.event("fence-cleared", fence=s["fence"]) |
| + |
| + def lift_fence(self): |
| + if self.j.last("drained") and not self.unchanged() and not self.j.last("fence-cleared"): |
| + self.fence_clear() |
| + |
| + def start_depart(self, iid, kind, transaction=None): |
| + require(kind in DEPART_KINDS, "unsupported") |
| + require(transaction is None or (isinstance(transaction, str) and TX.fullmatch(transaction) and |
| + not transaction.startswith(("probe-", "-"))), "record") |
| + require(self.state.held and self.state.active_id() is None, "active") |
| + tx = uuid.uuid4().hex if transaction is None else transaction |
| + self.j = self.state.create(dict(kind=kind, transaction=tx, config=self.c, iid=iid, |
| + attended_by=self.attended)) |
| + self.header = self.j.events[0] |
| + self.say("journal", str(self.j.path)) |
| + try: |
| + g, s = self.preflight(iid) |
| + if kind == "remove": |
| + self.check_remove(g, iid) |
| + except Exception: |
| + self.event("done", outcome="preflight-refused") |
| + self.state.finish() |
| + raise |
| + details = dict(old=s["binary_sha256"], new=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.depart() |
| + |
| + def check_remove(self, g, iid): |
| + require(g["desired"] - 1 >= 2, "remove_minimum") |
| + pools = self.member_edges[iid].get("served_pools") |
| + require(isinstance(pools, list) and all(isinstance(p, str) for p in pools), "remove_pools_unknown") |
| + served = set() |
| + for member, e in self.member_edges.items(): |
| + theirs = e.get("served_pools") |
| + # Unknown served_pools prove nothing, so they serve nothing here. |
| + if member != iid and isinstance(theirs, list) and all(isinstance(p, str) for p in theirs): |
| + served.update(theirs) |
| + for pool in pools: |
| + if pool not in served: |
| + raise Refusal(TEXT["remove_pools"].format(pool=pool)) |
| + |
| + def depart(self): |
| + """replace and remove: the shared shape, then the action and the watch. |
| + Each step is decided from the journal and a fresh group read, so |
| + resume continues where a cut left off.""" |
| + self.restore_header() |
| + h, iid, kind, n = self.header, self.header["iid"], self.kind(), self.header["n"] |
| + if self.j.last("done"): |
| + self.state.finish() |
| + return |
| + if self.unchanged(): |
| + return self.return_member() |
| + if not self.j.last("floor"): |
| + if self.floor(kind) != "drain": |
| + self.event("done", outcome="floor-refused") |
| + self.state.finish() |
| + raise Refusal(TEXT["floor_refused"]) |
| + require(self.rule() == "drain", "record") |
| + # The H5 check passed before the first edge-stop was sent. A stopped |
| + # agent cannot answer it again, so after a cut re-prove the stop and |
| + # read the locks again instead. |
| + resumed_stop = self.stop_sent() |
| + end = self.clock() + WAIT |
| + peers_checked = False |
| + while not self.j.last("intent", op="terminate"): |
| + if self.clock() >= end: |
| + self.alert("timeout") |
| + g = self.snapshot() |
| + self.invariant(g) |
| + phase = g["members"].get(iid) |
| + if phase == "InService": |
| + require(not self.j.last("drained"), "held") |
| + if not peers_checked: |
| + 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) |
| + peers_checked = True |
| + if g["minimum"] == g["desired"] == n: |
| + self.event("phase", phase="lower-minimum") |
| + self.call("minimum", value=n - 1) |
| + elif g["minimum"] == n - 1 and g["desired"] == n: |
| + self.event("phase", phase="enter-standby") |
| + if not self.j.last("enter-activity-baseline"): |
| + self.event("enter-activity-baseline", activities=self.call("activities", iid=iid)) |
| + result = self.call("enter", iid=iid, decrement=True) |
| + if result.get("activity"): |
| + self.event("enter-activity", activity=result["activity"]) |
| + end = self.clock() + WAIT |
| + else: |
| + self.alert("members") |
| + continue |
| + if phase not in {"Standby", "EnteringStandby"}: |
| + self.alert("members") |
| + self.standby(g, deregistered=False) |
| + if phase != "Standby" or not all(t.get(iid, "unused") == "unused" for t in g["targets"]): |
| + self.sleep(max(0, min(5, end - self.clock()))) |
| + continue |
| + for member in h["members"]: |
| + if member != 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") |
| + if not self.stop_sent(): |
| + try: |
| + if not self.j.last("drained"): |
| + self.drain() |
| + self.pre_action() |
| + except DrainFailed: |
| + return self.return_member() |
| + self.stop_edge() |
| + if resumed_stop: |
| + # The edge may have been restarted since the last proof. It ran |
| + # fenced, but read the locks again after this stop. |
| + held = self.locks_naming_member() |
| + if held: |
| + self.alert("lock_held_resume") |
| + self.event("phase", phase="terminate") |
| + try: |
| + result = self.call("terminate", iid=iid, decrement=False) |
| + if result.get("activity"): |
| + self.event("terminate-activity", activity=result["activity"]) |
| + except Uncertain: |
| + pass |
| + return self.depart_watch() |
| + |
| + def stop_sent(self): |
| + return any(r["kind"] == "intent" and r.get("op") == "session" and |
| + r["args"].get("verb") == "edge-stop" for r in self.j.events) |
| + |
| + def depart_watch(self): |
| + h, iid, kind, n = self.header, self.header["iid"], self.kind(), self.header["n"] |
| + survivors = [m for m in h["members"] if m != iid] |
| + start = self.j.last("intent", op="terminate")["at"] |
| + end = self.clock() + WAIT |
| + departed_at = replacement = None |
| + while True: |
| + if self.clock() >= end: |
| + self.alert("watch_timeout") |
| + g = self.snapshot() |
| + require(g["maximum"] == n and g["template"] == h["template"], "members") |
| + phase = g["members"].get(iid) |
| + if phase is not None and not phase.startswith("Terminat"): |
| + # Still a member: retry only a terminate that got no answer. |
| + require(phase == "Standby", "members") |
| + if self.j.last("error", op="terminate") and ( |
| + self.j.last("error", op="terminate")["seq"] > |
| + (self.j.last("response", op="terminate") or {}).get("seq", -1)): |
| + self.stop_edge() |
| + self.event("phase", phase="terminate") |
| + try: |
| + self.call("terminate", iid=iid, decrement=False) |
| + except Uncertain: |
| + pass |
| + continue |
| + self.sleep(max(0, min(5, end - self.clock()))) |
| + continue |
| + others = sorted(m for m in g["members"] if m != iid) |
| + if not self.j.last("terminate-checked"): |
| + # The provider check behind H4: terminating the Standby member |
| + # changed neither desired nor membership. |
| + if not (g["desired"] == g["minimum"] == n - 1 and others == survivors): |
| + self.alert("desired_changed", failed=True) |
| + self.event("terminate-checked", desired=g["desired"], members=sorted(g["members"])) |
| + if kind == "replace" and g["desired"] < n: |
| + self.event("phase", phase="restore-desired") |
| + self.call("desired", value=n) |
| + continue |
| + if kind == "replace" and g["minimum"] < n: |
| + self.event("phase", phase="restore-minimum") |
| + self.call("minimum", value=n) |
| + continue |
| + if departed_at is None: |
| + if h["identity"]["box_ref"] not in [EDGES_KEY.fullmatch(k)[1] for k in self.call("edges_list") |
| + if EDGES_KEY.fullmatch(k)]: |
| + departed_at = self.clock() |
| + self.event("departure-finished", seconds=departed_at - start) |
| + healthy = lambda m: (g["members"].get(m) == "InService" and g["healthy"].get(m) is True and |
| + all(t.get(m) == "healthy" for t in g["targets"])) |
| + ready = all(healthy(m) for m in survivors) |
| + if kind == "replace": |
| + new = [m for m in others if m not in h["members"]] |
| + require(len(new) <= 1 and g["desired"] == g["minimum"] == n, "members") |
| + ready = ready and len(new) == 1 and healthy(new[0]) |
| + if ready and replacement is None: |
| + try: |
| + require(self.call("online", iid=new[0]) is True, "offline") |
| + e = self.readiness(new[0])["edges"] |
| + # Section 25.9: the replacement is at the floor too. |
| + require(type(e.get("ha_take")) is int and e["ha_take"] == 1, "admission") |
| + replacement = new[0] |
| + self.event("replacement-admitted", iid=replacement, seconds=self.clock() - start) |
| + except (Refusal, Uncertain): |
| + ready = False |
| + ready = ready and replacement is not None |
| + elif not (g["desired"] == g["minimum"] == n - 1 and others == survivors): |
| + self.alert("desired_changed", failed=True) |
| + if ready and departed_at is not None: |
| + return self.finish_depart(start, departed_at, replacement) |
| + self.sleep(max(0, min(5, end - self.clock()))) |
| + |
| + def finish_depart(self, start, departed_at, replacement): |
| + h, kind, n = self.header, self.kind(), self.header["n"] |
| + # R3.1: the fence lived in the member's /run, which went with it. |
| + self.event("fence-moot", reason=TEXT["fence_moot"]) |
| + self.say("fence", TEXT["fence_moot"]) |
| + report = (self.j.last("drained") or {}).get("report") or {} |
| + holds = report.get("holds") if isinstance(report.get("holds"), dict) else {} |
| + summary = dict(transaction=h["transaction"], transaction_kind=kind, member=h["iid"], replacement=replacement, |
| + hosts_moved=len(report.get("moved") or []), |
| + hosts_released=len(report.get("released") or []), |
| + longest_hold_ms=holds.get("longest_ms"), todays_answer=holds.get("todays_answer"), |
| + connections_closed_at_bound=report.get("connections_closed_at_bound"), |
| + departure_seconds=departed_at - start) |
| + self.event("report", **summary) |
| + print(json.dumps(summary, sort_keys=True), file=self.output, flush=True) |
| + self.event("done", outcome="replaced" if kind == "replace" else "removed") |
| + self.state.finish() |
| + self.say("done", TEXT["replaced"] if kind == "replace" else TEXT["removed"].format(n=n - 1)) |
| + |
| + |
| 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", "abandon", "close-lost"): |
| + for verb in ("plan", "roll", "replace", "remove", "rollback", "resume", "status", "return", "abandon", |
| + "close-lost"): |
| p = sub.add_parser(verb, help=TEXT[verb]) |
| + if verb in {"replace", "remove"}: |
| + p.add_argument("--member", required=True, help=TEXT["member"]) |
| + p.add_argument("--transaction", help=TEXT["depart_transaction"]) |
| if verb in {"plan", "roll", "rollback"}: |
| p.add_argument("--member", required=True, help=TEXT["member"]) |
| if verb in {"plan", "roll"}: |
| @@ -1461,9 +2132,9 @@ def main(argv=None): |
| args = parser.parse_args(argv) |
| journal = None |
| try: |
| - if args.command == "roll" and args.transaction is not None: |
| + if args.command in {"roll", "replace", "remove"} and args.transaction is not None: |
| require(TX.fullmatch(args.transaction) and |
| - not args.transaction.startswith("probe-"), "record") |
| + not args.transaction.startswith(("probe-", "-")), "record") |
| 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())) |
| @@ -1485,6 +2156,11 @@ def main(argv=None): |
| op.roll(args.member, args.to_sha256, transaction=args.transaction) |
| finally: |
| journal = op.j |
| + elif args.command in {"replace", "remove"}: |
| + try: |
| + op.start_depart(args.member, args.command, transaction=args.transaction) |
| + finally: |
| + journal = op.j |
| else: |
| journal = state.load(args.transaction) |
| op.j = journal |
diff --git a/scripts/region_group_document_test.py b/scripts/region_group_document_test.py| index fdafebaf6..27bf8aeb4 100644 |
| --- a/scripts/region_group_document_test.py |
| +++ b/scripts/region_group_document_test.py |
| @@ -51,6 +51,41 @@ class DocumentPatternTests(unittest.TestCase): |
| self.assertAccepted(command) |
| self.assertAccepted(command, harness=True) |
| + def test_planned_handover_forms(self): |
| + # Region HA section 25: drain, fence-clear and the edge stop the roll |
| + # tool sends for replace, remove and the drained roll. |
| + for transaction in ("a", "t6_held-1", "A_9-" * 20): |
| + for verb in ("drain", "fence-clear"): |
| + command = frames.roll.AWS.remote_command(dict(verb=verb, transaction=transaction), NONCE) |
| + with self.subTest(verb=verb, transaction=transaction): |
| + self.assertAccepted(command) |
| + self.assertAccepted(command, harness=True) |
| + self.assertAccepted(frames.roll.AWS.remote_command({"verb": "edge-stop"}, NONCE)) |
| + drain = frames.roll.AWS.remote_command(dict(verb="drain", transaction="t6"), NONCE) |
| + clear = frames.roll.AWS.remote_command(dict(verb="fence-clear", transaction="t6"), NONCE) |
| + stop = frames.roll.AWS.remote_command({"verb": "edge-stop"}, NONCE) |
| + bad = { |
| + "leading dash": drain.replace("drain t6", "drain -t6"), |
| + "cancel": drain.replace("drain t6", "drain --cancel t6"), |
| + "two transactions": drain.replace("drain t6", "drain t6 t7"), |
| + "long transaction": drain.replace("drain t6", "drain " + "a" * 81), |
| + "drain without timeout": drain.replace("/usr/bin/timeout --signal=TERM --kill-after=30s 3600s ", ""), |
| + "drain longer bound": drain.replace("3600s", "3601s"), |
| + "fence-clear without status": clear.replace(" && " + STATUS, ""), |
| + "fence-clear dash": clear.replace("fence-clear t6", "fence-clear -t6"), |
| + "stop another unit": stop.replace("stop carlos-edge.service", "stop sshd.service"), |
| + "start the edge": stop.replace("stop carlos-edge.service", "start carlos-edge.service"), |
| + "stop without bound": stop.replace("/usr/bin/timeout --signal=TERM --kill-after=10s 120s ", ""), |
| + "unescaped dot": stop.replace("carlos-edge.service;", "carlos-edgexservice;"), |
| + "other property": stop.replace("--property=ActiveState", "--property=Environment"), |
| + } |
| + for addition in ("; id", " && id", " | sh"): |
| + bad["drain " + repr(addition)] = drain.replace("drain t6", "drain t6" + addition) |
| + bad["stop " + repr(addition)] = stop.replace("carlos-edge.service)", "carlos-edge.service" + addition + ")") |
| + for label, command in bad.items(): |
| + with self.subTest(case=label): |
| + self.assertRefused(command) |
| + |
| def test_permit_payload_edges(self): |
| payloads = [{}, {"x": ""}, {"x": "a"}, {"x": "ab"}, {"x": "abc"}, |
| {"x": "'\" ; & | $ ` ( ) < > \n\r\\\x00"}, {"x": "\u2603"}, |
| @@ -220,7 +255,7 @@ class DocumentPatternTests(unittest.TestCase): |
| elif char == "[": |
| end = source.index("]", index) |
| self.assertIn(source[index:end + 1], ( |
| - "[0-9a-f]", "[A-Za-z0-9+/=]", "[A-Za-z0-9_-]", "[1-9]", "[1-5]", "[0-9]")) |
| + "[0-9a-f]", "[A-Za-z0-9+/=]", "[A-Za-z0-9_-]", "[A-Za-z0-9_]", "[1-9]", "[1-5]", "[0-9]")) |
| index = end |
| elif char == "{": |
| end = source.index("}", index) |
diff --git a/scripts/region_group_held_test.py b/scripts/region_group_held_test.py| new file mode 100644 |
| index 000000000..8b0f5919c |
| --- /dev/null |
| +++ b/scripts/region_group_held_test.py |
| @@ -0,0 +1,871 @@ |
| +"""Offline witnesses for planned handovers: replace, remove and the drained roll |
| +(region HA spec sections 25.6, 25.9 and 25.15; H4 and H5).""" |
| +import base64 |
| +import copy |
| +from contextlib import closing |
| +import gzip |
| +import io |
| +import json |
| +from collections import Counter |
| +import os |
| +from pathlib import Path |
| +import tempfile |
| +import unittest |
| +from unittest.mock import patch |
| + |
| +from scripts import region_group_roll_test as base |
| + |
| +roll, live = base.roll, base.live |
| +IID, PEER, OLD, NEW = base.IID, base.PEER, base.OLD, base.NEW |
| +THIRD = "i-0aaaaaaaaaaaaaaaa" |
| +REPLACEMENT = "i-0bbbbbbbbbbbbbbbb" |
| +REF = "g-" + IID[2:] |
| +PEER_REF = "g-" + PEER[2:] |
| +INCARNATION, RESTARTED = "1" * 32, "2" * 32 |
| +DATA_BUCKET = "example-bucket" |
| + |
| + |
| +def held_config(state_dir): |
| + config = base.test_config(state_dir) |
| + config.update(ha_floor="v0.35.0", data_prefix="instances") |
| + return config |
| + |
| + |
| +def marker(box): |
| + return dict(generation=3, expires_at="1970-01-01T00:00:00Z", owner="released/v1;ref=" + box, |
| + carlos_release=dict(box=box, lifetime="l1", clean=True)) |
| + |
| + |
| +def held_lock(ref, iid): |
| + return dict(generation=4, expires_at="2030-01-01T00:00:00Z", |
| + owner="box/v1;ref=%s;iid=%s;pid=7;ha=1" % (ref, iid)) |
| + |
| + |
| +class HeldFake(base.Fake): |
| + """The roll Fake, with every group write sent through the real AWS adapter |
| + (and so through its H4 guards) to a CLI-level provider. That provider |
| + terminates a different instance whenever desired capacity is lowered in |
| + any way other than the member's EnterStandby with decrement.""" |
| + activity_response = staticmethod(roll.AWS.activity_response) |
| + data_prefix = staticmethod(roll.AWS.data_prefix) |
| + list_objects = roll.AWS.list_objects |
| + template_release = roll.AWS.template_release |
| + |
| + def __init__(self, config, members=2): |
| + super().__init__(config) |
| + self.version = "v0.35.0" |
| + if members == 3: |
| + self.add_member(THIRD, "InService") |
| + self.minimum = self.desired = self.maximum = 3 |
| + self.ha_take = {} |
| + self.pools = {} |
| + self.fixed = {"adi": dict(ha_take=1, age=5)} |
| + self.template_rel = "v0.35.0" |
| + self.locks = {"shop": marker(PEER_REF), "blog": held_lock(PEER_REF, PEER), "idle": None} |
| + self.drain_mode = "ok" |
| + self.after_drain = None |
| + self.incarnation = INCARNATION |
| + self.drain_state = dict(state="known", incarnation=INCARNATION, transaction=None, step=None, |
| + result="none", error=None) |
| + self.fence = None |
| + self.edge_stops = True |
| + self.h4_violations = [] |
| + self.departure_delay = 120 |
| + self.departure_at = None |
| + self.terminated_at = None |
| + self.departed = set() |
| + self.launch_delay = 60 |
| + self.launched_at = None |
| + self.s3 = Counter() |
| + |
| + def add_member(self, iid, state): |
| + self.states[iid] = state |
| + self.tg[iid] = "healthy" if state == "InService" else "initial" |
| + self.boxes[iid] = self.box(iid) |
| + self.published[iid] = self.now - 5 |
| + |
| + def violate(self, how): |
| + self.h4_violations.append(how) |
| + self.states[PEER] = "Terminated" |
| + self.tg.pop(PEER, None) |
| + |
| + def perform(self, op, a): |
| + if op in {"minimum", "enter", "exit", "terminate", "desired", |
| + "edges_list", "edges_key", "lock_hosts", "lock", "template_release"}: |
| + return roll.AWS.request(self, op, a) |
| + if op == "session": |
| + return self.session(a) |
| + return super().perform(op, a) |
| + |
| + def session(self, a): |
| + verb, iid = a["verb"], a["iid"] |
| + s = self.boxes[iid] |
| + if verb == "status": |
| + mine = iid == IID |
| + s["fence"] = dict(state="present" if mine and self.fence else "absent", |
| + transaction=self.fence if mine else None, error=None) |
| + s["drain"] = copy.deepcopy(self.drain_state) if mine else dict( |
| + state="known", incarnation="9" * 32, transaction=None, step=None, result="none", error=None) |
| + return super().perform("session", a) |
| + assert iid == IID, (verb, iid) |
| + if verb == "drain": |
| + assert self.states[IID] == "Standby" and self.tg[IID] == "unused" |
| + assert self.desired == self.minimum == self.maximum - 1 |
| + if self.drain_mode == "uncertain": |
| + raise roll.Uncertain("drain") |
| + tx, ok = a["transaction"], self.drain_mode == "ok" |
| + assert self.fence in (None, tx) |
| + self.fence = tx |
| + self.drain_state = dict(state="known", incarnation=self.incarnation, transaction=tx, step="move", |
| + result="ok" if ok else "failed", error=None) |
| + report = dict(v=1, transaction=tx, incarnation=self.incarnation, step="move", |
| + result="ok" if ok else "failed", |
| + reasons=[] if ok else ["the connections did not drain"], fence=tx, |
| + moved=[dict(host="blog", holder=PEER_REF, gen=4, confirmed="take")], |
| + released=[], unclean=[], left=[], |
| + holds=dict(longest_ms=1500, todays_answer=0, refused_at_once=0), |
| + connections_closed_at_bound=0) |
| + if self.after_drain: |
| + self.after_drain() |
| + return dict(exit=0 if ok else 1, report=report) |
| + if verb == "fence-clear": |
| + assert self.fence in (None, a["transaction"]) |
| + self.fence = None |
| + return self.session(dict(a, verb="status")) |
| + if verb == "edge-stop": |
| + if not self.edge_stops: |
| + return dict(main_pid=4242, active_state="active") |
| + s["edge"].update(state="unknown", pid=None, identity=None) |
| + s["health"].update(state="unhealthy", code=None) |
| + # The drain socket went with the agent. |
| + self.drain_state = dict(state="unknown", incarnation=None, transaction=None, step=None, |
| + result=None, error="dial") |
| + return dict(main_pid=0, active_state="inactive") |
| + if verb == "apply": |
| + result = super().perform("session", a) |
| + # A restarted agent: a new incarnation that is not draining. |
| + self.incarnation = RESTARTED |
| + self.drain_state = dict(state="known", incarnation=RESTARTED, transaction=None, step=None, |
| + result="none", error=None) |
| + return result |
| + return super().perform("session", a) |
| + |
| + def edge_refs(self): |
| + refs = [s["box_ref"] for i, s in self.boxes.items() if s["box_ref"] not in self.departed] |
| + return sorted(refs) + sorted(self.fixed) |
| + |
| + def edges_body(self, ref): |
| + if ref in self.fixed: |
| + body = live.load("edges-" + live.PEER_BOX + ".json") |
| + spec = self.fixed[ref] |
| + body.update(box=ref, box_id=ref, generation=roll.stamp(self.now - spec["age"])) |
| + if spec["ha_take"] is not None: |
| + body["ha_take"] = spec["ha_take"] |
| + return body |
| + body = super().invoke("s3api", "get-object", ["--bucket", self.c["bucket"], "--key", |
| + "control/edges/" + ref + ".json"]) |
| + take = self.ha_take.get(ref, 1) |
| + if take is not None: |
| + body["ha_take"] = take |
| + if ref in self.pools: |
| + body["served_pools"] = self.pools[ref] |
| + return body |
| + |
| + def invoke(self, service, verb, args, **kwargs): |
| + def value(flag): |
| + return args[args.index(flag) + 1] |
| + if verb in {"list-objects-v2", "get-object"}: |
| + key = value("--prefix") if verb == "list-objects-v2" else value("--key") |
| + self.s3[(verb, "data" if value("--bucket") == DATA_BUCKET else |
| + "edges" if key.startswith("control/edges/") else "other")] += 1 |
| + if verb == "list-objects-v2": |
| + bucket, prefix = value("--bucket"), value("--prefix") |
| + if bucket == self.c["bucket"]: |
| + assert prefix == "control/edges/" and "--delimiter" not in args |
| + return dict(Contents=[dict(Key="control/edges/%s.json" % r) for r in self.edge_refs()] + |
| + [dict(Key="control/edges/index/v1")], IsTruncated=False) |
| + assert bucket == DATA_BUCKET, bucket |
| + if "--delimiter" in args: |
| + assert prefix == "instances/" |
| + hosts = sorted(self.locks) |
| + # One host per page, to walk the continuation token. |
| + page = int(value("--continuation-token")) if "--continuation-token" in args else 0 |
| + more = page + 1 < len(hosts) |
| + return dict(CommonPrefixes=[dict(Prefix="instances/%s/" % hosts[page])], IsTruncated=more, |
| + **(dict(NextContinuationToken=str(page + 1)) if more else {})) |
| + host = prefix[len("instances/"):-len("/lock.json")] |
| + assert prefix == "instances/" + host + "/lock.json" |
| + return dict(Contents=[dict(Key=prefix)] if self.locks.get(host) is not None else [], |
| + IsTruncated=False) |
| + if verb == "get-object": |
| + key = value("--key") |
| + match = roll.EDGES_KEY.fullmatch(key) |
| + if match: |
| + return self.edges_body(match[1]) |
| + assert value("--bucket") == DATA_BUCKET and key.startswith("instances/") |
| + return copy.deepcopy(self.locks[key[len("instances/"):-len("/lock.json")]]) |
| + if verb == "describe-launch-template-versions": |
| + script = "#!/bin/sh\nCARLOS_DEPLOYMENT='example'\nCARLOS_RELEASE='%s'\nexport CARLOS_RELEASE\n" % ( |
| + self.template_rel) |
| + return dict(LaunchTemplateVersions=[dict(VersionNumber=int(value("--versions")), LaunchTemplateData=dict( |
| + UserData=base64.b64encode(gzip.compress(script.encode())).decode()))]) |
| + if verb == "update-auto-scaling-group": |
| + if "--min-size" in args: |
| + return super().perform("minimum", dict(value=int(value("--min-size")))) |
| + wanted = int(value("--desired-capacity")) |
| + if wanted < self.desired: |
| + self.violate("update-auto-scaling-group --desired-capacity") |
| + self.desired = wanted |
| + return {} |
| + if verb == "set-desired-capacity": |
| + wanted = int(value("--desired-capacity")) |
| + if wanted < self.desired: |
| + self.violate("set-desired-capacity") |
| + self.desired = wanted |
| + return {} |
| + if verb == "enter-standby": |
| + iid = value("--instance-ids") |
| + decrement = "--should-decrement-desired-capacity" in args |
| + assert iid == IID |
| + result = super().perform("enter", dict(iid=iid, decrement=decrement)) |
| + return dict(Activities=[dict(ActivityId=result["activity"])]) |
| + if verb == "exit-standby": |
| + result = super().perform("exit", dict(iid=value("--instance-ids"))) |
| + return dict(Activities=[dict(ActivityId=result["activity"])]) |
| + if verb == "terminate-instance-in-auto-scaling-group": |
| + iid = value("--instance-id") |
| + if "--should-decrement-desired-capacity" in args: |
| + self.violate("terminate with decrement") |
| + self.desired -= 1 |
| + self.states[iid] = "Terminating" |
| + self.tg.pop(iid, None) |
| + self.terminated_at = self.now |
| + self.departure_at = self.now + self.departure_delay |
| + return dict(Activity=dict(ActivityId="terminate-1")) |
| + if verb == "describe-instance-information": |
| + iid = json.loads(value("--filters"))[0]["Values"][0] |
| + if iid in (THIRD, REPLACEMENT): |
| + result = super().invoke(service, verb, ["--filters", json.dumps( |
| + [{"Key": "InstanceIds", "Values": [IID]}])]) |
| + for row in result["InstanceInformationList"]: |
| + row["InstanceId"] = iid |
| + return result |
| + return super().invoke(service, verb, args, **kwargs) |
| + |
| + def sleep(self, seconds): |
| + super().sleep(seconds) |
| + if self.terminated_at is not None and self.now >= self.terminated_at + 30: |
| + self.states[IID] = "Terminated" |
| + if self.departure_at is not None and self.now >= self.departure_at: |
| + self.departed.add(REF) |
| + serving = [i for i, s in self.states.items() if s in {"InService", "Pending", "PreInService"}] |
| + if REPLACEMENT not in self.states and len(serving) < self.desired: |
| + self.add_member(REPLACEMENT, "Pending") |
| + self.boxes[REPLACEMENT]["edge"]["started_at"] = roll.stamp(self.now) |
| + self.published[REPLACEMENT] = self.now + 2 |
| + self.launched_at = self.now |
| + if self.states.get(REPLACEMENT) == "Pending" and self.now >= self.launched_at + self.launch_delay: |
| + self.states[REPLACEMENT] = "InService" |
| + if self.states.get(REPLACEMENT) == "InService" and self.now >= self.launched_at + self.launch_delay + 20: |
| + self.tg[REPLACEMENT] = "healthy" |
| + |
| + |
| +class HeldBase(unittest.TestCase): |
| + members = 2 |
| + |
| + def setUp(self): |
| + directory = os.environ.get("TMPDIR") or str(Path.home() / ".cache") |
| + self.tmp = tempfile.TemporaryDirectory(prefix="region-held-test-", dir=directory) |
| + self.addCleanup(self.tmp.cleanup) |
| + self.config = held_config(self.tmp.name) |
| + self.fake = HeldFake(self.config, self.members) |
| + 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 depart(self, kind="replace", transaction="t6-held"): |
| + with self.store.lock(): |
| + op = self.engine() |
| + try: |
| + return op.start_depart(IID, kind, transaction=transaction) |
| + finally: |
| + if op.j: |
| + op.j.close() |
| + |
| + def run_roll(self): |
| + with self.store.lock(): |
| + op = self.engine() |
| + try: |
| + return op.roll(IID, NEW, transaction="t6-roll") |
| + finally: |
| + if op.j: |
| + op.j.close() |
| + |
| + def resume(self): |
| + with self.store.lock(): |
| + journal = self.store.load(self.store.active_id()) |
| + try: |
| + return self.engine(journal).resume() |
| + finally: |
| + journal.close() |
| + |
| + def journal(self, tx="t6-held"): |
| + return closing(self.store.load(tx, readonly=True)) |
| + |
| + def verbs(self): |
| + return [a["verb"] if op == "session" else op for op, a in self.fake.calls |
| + if op in {"minimum", "enter", "exit", "terminate", "desired"} or |
| + (op == "session" and a["verb"] != "status")] |
| + |
| + def assert_h4(self): |
| + self.assertEqual(self.fake.h4_violations, []) |
| + self.assertNotEqual(self.fake.states[PEER], "Terminated") |
| + |
| + def assert_returned(self, tx="t6-held"): |
| + """A failed drain: the member is back in service with the shape restored, |
| + nothing was terminated, and the fence stays for drain --cancel.""" |
| + self.assertEqual(self.fake.states[IID], "InService") |
| + n = self.fake.maximum |
| + self.assertEqual((self.fake.minimum, self.fake.desired), (n, n)) |
| + self.assertNotIn("terminate", self.verbs()) |
| + self.assertNotIn("edge-stop", self.verbs()) |
| + self.assertNotIn("fence-clear", self.verbs()) |
| + self.assertEqual(self.fake.fence, tx) |
| + self.assertIsNone(self.store.active_id()) |
| + self.assertIn(roll.TEXT["drain_cancel"].format(iid=IID, transaction=tx), self.output.getvalue()) |
| + with self.journal(tx) as journal: |
| + self.assertEqual(journal.last("done")["outcome"], "drain-failed") |
| + self.assert_h4() |
| + |
| + |
| +class ReplaceTests(HeldBase): |
| + def test_replace_order_restores_shape_and_watches(self): |
| + self.depart() |
| + self.assertEqual(self.verbs(), ["minimum", "enter", "drain", "edge-stop", "terminate", |
| + "desired", "minimum"]) |
| + self.assertEqual((self.fake.minimum, self.fake.desired, self.fake.maximum), (2, 2, 2)) |
| + self.assertEqual(self.fake.states[IID], "Terminated") |
| + self.assertEqual(self.fake.states[REPLACEMENT], "InService") |
| + self.assertEqual(self.fake.launches, 0) |
| + self.assertIn(REF, self.fake.departed) |
| + self.assert_h4() |
| + self.assertIsNone(self.store.active_id()) |
| + with self.journal() as journal: |
| + kinds = [r["kind"] for r in journal.events] |
| + # The H5 check is the last thing before the stop, and the stop is |
| + # proven before the provider call. |
| + self.assertLess(kinds.index("drained"), kinds.index("pre-action-checked")) |
| + self.assertLess(kinds.index("pre-action-checked"), kinds.index("edge-stopped")) |
| + terminate = journal.last("intent", op="terminate") |
| + self.assertLess(journal.last("edge-stopped")["seq"], terminate["seq"]) |
| + self.assertEqual(terminate["args"], dict(iid=IID, decrement=False)) |
| + self.assertEqual(journal.last("floor")["rule"], "drain") |
| + self.assertEqual(sorted(journal.last("floor")["live"]), sorted([REF, PEER_REF, "adi"])) |
| + self.assertIsNotNone(journal.last("fence-moot")) |
| + self.assertIsNotNone(journal.last("replacement-admitted")) |
| + report = journal.last("report") |
| + self.assertEqual((report["hosts_moved"], report["longest_hold_ms"], report["todays_answer"]), |
| + (1, 1500, 0)) |
| + self.assertEqual(report["replacement"], REPLACEMENT) |
| + self.assertEqual(journal.last("done")["outcome"], "replaced") |
| + self.assertIn(roll.TEXT["rule_drain"], self.output.getvalue()) |
| + self.assertIn(roll.TEXT["fence_moot"], self.output.getvalue()) |
| + # Store calls, counted: the lock re-read is one listing page per host |
| + # (3 here), one exact-key listing per host and one GET per lock that |
| + # exists (idle has none). It runs once per transaction, never on a timer. |
| + self.assertEqual(self.fake.s3[("list-objects-v2", "data")], 3 + 3) |
| + self.assertEqual(self.fake.s3[("get-object", "data")], 2) |
| + |
| + def test_replace_resumes_after_every_write(self): |
| + for before in (False, True): |
| + for boundary in range(1, 8): |
| + with self.subTest(before=before, boundary=boundary): |
| + self.setUp() |
| + self.fake.fail_before = before |
| + self.fake.fault, self.fake.fault_at = "death", boundary |
| + with self.assertRaises(base.Death): |
| + self.depart() |
| + self.resume() |
| + self.assertEqual((self.fake.minimum, self.fake.desired), (2, 2)) |
| + self.assertEqual(self.fake.states[IID], "Terminated") |
| + self.assertEqual(self.fake.states[REPLACEMENT], "InService") |
| + # A terminate cut before it reached the provider is sent again. |
| + self.assertEqual(self.fake.writes.count("terminate"), 1) |
| + self.assertIsNone(self.store.active_id()) |
| + self.assert_h4() |
| + |
| + def test_failed_drain_returns_member_and_prints_cancel(self): |
| + self.fake.drain_mode = "fail" |
| + with self.assertRaises(roll.Refusal) as caught: |
| + self.depart() |
| + self.assertEqual(str(caught.exception), roll.TEXT["drain_failed"]) |
| + self.assertEqual(self.verbs(), ["minimum", "enter", "drain", "exit", "minimum"]) |
| + self.assert_returned() |
| + self.assertIn(roll.TEXT["drain_reason"].format(reason="the connections did not drain"), |
| + self.output.getvalue()) |
| + |
| + def test_uncertain_drain_session_is_a_failed_drain(self): |
| + self.fake.drain_mode = "uncertain" |
| + self.fake.fence = None |
| + with self.assertRaises(roll.Refusal): |
| + self.depart() |
| + self.assertEqual(self.fake.states[IID], "InService") |
| + self.assertEqual((self.fake.minimum, self.fake.desired), (2, 2)) |
| + self.assertNotIn("terminate", self.verbs()) |
| + self.assertIn(roll.TEXT["drain_cancel"].format(iid=IID, transaction="t6-held"), self.output.getvalue()) |
| + |
| + def test_lock_still_naming_member_refuses_action(self): |
| + for owner in ("box/v1;ref=%s;iid=%s;pid=9;ha=1" % (REF, IID), "box/v1;ref=other;iid=%s;pid=9;ha=1" % IID, |
| + "%s:4242" % REF): |
| + with self.subTest(owner=owner): |
| + self.setUp() |
| + self.fake.locks["blog"] = dict(held_lock(PEER_REF, PEER), owner=owner) |
| + with self.assertRaises(roll.Refusal): |
| + self.depart() |
| + self.assert_returned() |
| + with self.journal() as journal: |
| + self.assertEqual(journal.last("drain-failed")["reasons"], |
| + [roll.TEXT["lock_held"].format(hosts="blog")]) |
| + |
| + def test_marker_and_other_owner_locks_pass(self): |
| + self.fake.locks.update(a=marker(REF), b=held_lock("g-" + IID[2:] + "x", PEER)) |
| + self.depart() |
| + self.assertEqual(self.fake.states[IID], "Terminated") |
| + # Every host page was walked: shop, blog, idle, a and b. |
| + with self.journal() as journal: |
| + hosts = journal.last("response", op="lock_hosts")["result"] |
| + self.assertEqual(hosts, ["a", "b", "blog", "idle", "shop"]) |
| + |
| + def test_stale_incarnation_refuses_action(self): |
| + def restart(): |
| + self.fake.drain_state = dict(state="known", incarnation=RESTARTED, transaction=None, step=None, |
| + result="none", error=None) |
| + self.fake.after_drain = restart |
| + with self.assertRaises(roll.Refusal): |
| + self.depart() |
| + self.assert_returned() |
| + with self.journal() as journal: |
| + self.assertEqual(journal.last("drain-failed")["reasons"], [roll.TEXT["drain_void"]]) |
| + |
| + def test_changed_incarnation_with_finished_drain_refuses(self): |
| + # A second agent that reports the same finished drain is still void. |
| + def restart(): |
| + self.fake.drain_state = dict(self.fake.drain_state, incarnation=RESTARTED) |
| + self.fake.after_drain = restart |
| + with self.assertRaises(roll.Refusal): |
| + self.depart() |
| + self.assert_returned() |
| + with self.journal() as journal: |
| + self.assertEqual(journal.last("drain-failed")["reasons"], [roll.TEXT["incarnation"]]) |
| + |
| + def test_missing_fence_refuses_action(self): |
| + self.fake.after_drain = lambda: setattr(self.fake, "fence", None) |
| + with self.assertRaises(roll.Refusal): |
| + self.depart() |
| + self.assertEqual(self.fake.states[IID], "InService") |
| + self.assertNotIn("terminate", self.verbs()) |
| + with self.journal() as journal: |
| + self.assertEqual(journal.last("drain-failed")["reasons"], [roll.TEXT["fence_missing"]]) |
| + |
| + def test_edge_still_running_holds_standby_until_proven(self): |
| + self.fake.edge_stops = False |
| + with self.assertRaises(roll.Refusal) as caught: |
| + self.depart() |
| + self.assertEqual(str(caught.exception), roll.TEXT["edge_running"]) |
| + self.assertEqual(self.fake.states[IID], "Standby") |
| + self.assertEqual((self.fake.minimum, self.fake.desired), (1, 1)) |
| + self.assertNotIn("terminate", self.verbs()) |
| + self.assertEqual(self.store.active_id(), "t6-held") |
| + self.fake.edge_stops = True |
| + self.resume() |
| + self.assertEqual(self.fake.states[IID], "Terminated") |
| + self.assertEqual(self.verbs().count("edge-stop"), 2) |
| + # The resumed stop read the locks again after the edge was gone. |
| + with self.journal() as journal: |
| + stops = [r["seq"] for r in journal.events if r["kind"] == "edge-stopped"] |
| + lock_reads = [r["seq"] for r in journal.events if r["kind"] == "intent" and r["op"] == "lock_hosts"] |
| + self.assertTrue(any(seq > stops[-1] for seq in lock_reads)) |
| + self.assert_h4() |
| + |
| + def test_restart_after_last_check_is_fenced_and_stopped(self): |
| + # R3.1 witness, offline: the agent restarts after the tool's last H5 |
| + # check, while the provider call is still to come. The tool stops the |
| + # edge and proves MainPID 0, and the fence is still in place. |
| + request = self.fake.request |
| + |
| + def restart_then(op, a): |
| + if op == "session" and a["verb"] == "edge-stop": |
| + self.fake.drain_state = dict(state="known", incarnation=RESTARTED, transaction=None, |
| + step=None, result="none", error=None) |
| + self.assertEqual(self.fake.fence, "t6-held") |
| + if op == "terminate": |
| + self.assertEqual(self.fake.boxes[IID]["edge"]["pid"], None) |
| + self.assertEqual(self.fake.fence, "t6-held") |
| + return request(op, a) |
| + |
| + self.fake.request = restart_then |
| + self.depart() |
| + self.assertEqual(self.fake.states[IID], "Terminated") |
| + |
| + def test_provider_changing_desired_on_terminate_fails(self): |
| + invoke = self.fake.invoke |
| + |
| + def launching(service, verb, args, **kwargs): |
| + result = invoke(service, verb, args, **kwargs) |
| + if verb == "terminate-instance-in-auto-scaling-group": |
| + self.fake.desired += 1 |
| + return result |
| + |
| + self.fake.invoke = launching |
| + with self.assertRaises(roll.FailedProbe): |
| + self.depart() |
| + self.assertTrue(self.store.blocked.exists()) |
| + self.assertNotIn("desired", self.verbs()) |
| + |
| + |
| +class FloorTests(HeldBase): |
| + def assert_floor_refused(self, reason): |
| + with self.assertRaises(roll.Refusal) as caught: |
| + self.depart() |
| + self.assertEqual(str(caught.exception), roll.TEXT["floor_refused"]) |
| + self.assertEqual(self.verbs(), []) |
| + self.assertIsNone(self.store.active_id()) |
| + out = self.output.getvalue() |
| + self.assertIn(roll.TEXT["rule_dr4"], out) |
| + self.assertIn(reason, out) |
| + with self.journal() as journal: |
| + self.assertEqual(journal.last("done")["outcome"], "floor-refused") |
| + self.assertEqual(journal.last("floor")["rule"], "dr4") |
| + |
| + def test_member_without_ha_take(self): |
| + self.fake.ha_take[PEER_REF] = None |
| + self.assert_floor_refused(roll.TEXT["floor_box"].format(box=PEER_REF)) |
| + |
| + def test_member_with_other_ha_take(self): |
| + for take in (0, 2, True, "1"): |
| + with self.subTest(take=take): |
| + self.setUp() |
| + self.fake.ha_take[REF] = take |
| + self.assert_floor_refused(roll.TEXT["floor_box"].format(box=REF)) |
| + |
| + def test_fixed_forwarder_without_ha_take(self): |
| + self.fake.fixed["adi"]["ha_take"] = None |
| + self.assert_floor_refused(roll.TEXT["floor_box"].format(box="adi")) |
| + |
| + def test_stale_box_is_not_live(self): |
| + self.fake.fixed["old"] = dict(ha_take=None, age=16 * 60) |
| + self.depart() |
| + self.assertEqual(self.fake.states[IID], "Terminated") |
| + with self.journal() as journal: |
| + self.assertNotIn("old", journal.last("floor")["live"]) |
| + |
| + def test_old_pinned_template(self): |
| + for release in ("v0.34.9", "v0.35.0-rc1", "a" * 64): |
| + with self.subTest(release=release): |
| + self.setUp() |
| + self.fake.template_rel = release |
| + self.assert_floor_refused(roll.TEXT["floor_template"].format(release=release)) |
| + |
| + def test_no_floor_config(self): |
| + for key in ("ha_floor", "data_prefix"): |
| + with self.subTest(key=key): |
| + self.setUp() |
| + del self.config[key] |
| + self.assert_floor_refused(roll.TEXT["floor_config"]) |
| + |
| + def test_unreadable_edges_file(self): |
| + invoke = self.fake.invoke |
| + |
| + def failing(service, verb, args, **kwargs): |
| + if verb == "get-object" and "control/edges/adi.json" in args: |
| + raise roll.Uncertain(roll.TEXT["api"]) |
| + return invoke(service, verb, args, **kwargs) |
| + |
| + self.fake.invoke = failing |
| + self.assert_floor_refused(roll.TEXT["floor_unreadable"].format(key="control/edges/adi.json")) |
| + |
| + |
| +class RemoveTests(HeldBase): |
| + members = 3 |
| + |
| + def test_remove_leaves_n_minus_one_and_names_box_count(self): |
| + self.fake.pools = {REF: ["shop"], PEER_REF: ["shop"], "g-" + THIRD[2:]: ["blog"]} |
| + self.depart("remove") |
| + self.assertEqual(self.verbs(), ["minimum", "enter", "drain", "edge-stop", "terminate"]) |
| + self.assertEqual((self.fake.minimum, self.fake.desired, self.fake.maximum), (2, 2, 3)) |
| + self.assertEqual(self.fake.states[IID], "Terminated") |
| + self.assertNotIn(REPLACEMENT, self.fake.states) |
| + self.assert_h4() |
| + self.assertIn(roll.TEXT["removed"].format(n=2), self.output.getvalue()) |
| + with self.journal() as journal: |
| + self.assertEqual(journal.last("done")["outcome"], "removed") |
| + |
| + def test_remove_refuses_an_unserved_pool(self): |
| + self.fake.pools = {REF: ["shop", "blog"], PEER_REF: ["shop"], "g-" + THIRD[2:]: None} |
| + with self.assertRaises(roll.Refusal) as caught: |
| + self.depart("remove") |
| + self.assertEqual(str(caught.exception), roll.TEXT["remove_pools"].format(pool="blog")) |
| + self.assertEqual(self.verbs(), []) |
| + with self.journal() as journal: |
| + self.assertEqual(journal.last("done")["outcome"], "preflight-refused") |
| + |
| + def test_remove_refuses_unknown_member_pools(self): |
| + self.fake.pools = {REF: "shop"} |
| + with self.assertRaises(roll.Refusal) as caught: |
| + self.depart("remove") |
| + self.assertEqual(str(caught.exception), roll.TEXT["remove_pools_unknown"]) |
| + self.assertEqual(self.verbs(), []) |
| + |
| + |
| +class RemoveMinimumTests(HeldBase): |
| + def test_remove_needs_two_survivors(self): |
| + with self.assertRaises(roll.Refusal) as caught: |
| + self.depart("remove") |
| + self.assertEqual(str(caught.exception), roll.TEXT["remove_minimum"]) |
| + self.assertEqual(self.verbs(), []) |
| + |
| + |
| +class DrainedRollTests(HeldBase): |
| + def test_roll_drains_before_apply_and_lifts_fence_after_exit(self): |
| + seen = {} |
| + request = self.fake.request |
| + |
| + def observe(op, a): |
| + if op == "session" and a["verb"] == "fence-clear": |
| + seen["fence-clear"] = (self.fake.states[IID], self.fake.minimum, self.fake.desired) |
| + if op == "session" and a["verb"] == "apply": |
| + seen["apply"] = self.fake.fence |
| + return request(op, a) |
| + |
| + self.fake.request = observe |
| + self.run_roll() |
| + self.assertEqual(self.fake.writes, ["prepare", "minimum", "enter", "drain", "permit", "apply", |
| + "exit", "fence-clear", "minimum", "revoke"]) |
| + # apply restarted the edge behind the fence; the fence is lifted only |
| + # after ExitStandby, and before minimum is restored. |
| + self.assertEqual(seen["apply"], "t6-roll") |
| + self.assertEqual(seen["fence-clear"], ("InService", 1, 2)) |
| + self.assertIsNone(self.fake.fence) |
| + 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()) |
| + with self.journal("t6-roll") as journal: |
| + self.assertEqual(journal.last("floor")["rule"], "drain") |
| + self.assertLess(journal.last("pre-action-checked")["seq"], |
| + journal.last("intent", op="session", args=dict(iid=IID, verb="apply"))["seq"]) |
| + self.assert_h4() |
| + |
| + def test_roll_failed_drain_returns_unchanged(self): |
| + self.fake.drain_mode = "fail" |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + self.assertEqual(self.fake.writes, ["prepare", "minimum", "enter", "drain", "exit", "minimum"]) |
| + self.assertEqual(self.fake.boxes[IID]["binary_sha256"], OLD) |
| + self.assert_returned("t6-roll") |
| + |
| + def test_roll_lock_after_permit_returns_and_revokes(self): |
| + self.fake.locks["blog"] = held_lock(REF, IID) |
| + with self.assertRaises(roll.Refusal): |
| + self.run_roll() |
| + self.assertEqual(self.fake.writes, ["prepare", "minimum", "enter", "drain", "permit", "exit", |
| + "minimum", "revoke"]) |
| + self.assertEqual(self.fake.boxes[IID]["binary_sha256"], OLD) |
| + self.assert_returned("t6-roll") |
| + |
| + def test_roll_below_floor_uses_dr4_and_says_so(self): |
| + self.fake.ha_take[PEER_REF] = None |
| + self.run_roll() |
| + self.assertEqual(self.fake.writes, ["prepare", "minimum", "enter", "permit", "apply", "exit", |
| + "minimum", "revoke"]) |
| + self.assertIn(roll.TEXT["rule_dr4"], self.output.getvalue()) |
| + self.assertIn(roll.TEXT["floor_box"].format(box=PEER_REF), self.output.getvalue()) |
| + |
| + def test_roll_to_release_below_floor_uses_dr4(self): |
| + self.fake.version = "v0.34.0" |
| + self.run_roll() |
| + self.assertNotIn("drain", self.fake.writes) |
| + self.assertIn(roll.TEXT["floor_version"].format(release="v0.34.0"), self.output.getvalue()) |
| + |
| + def test_drained_roll_resumes_after_every_write(self): |
| + for boundary in range(1, 11): |
| + with self.subTest(boundary=boundary): |
| + self.setUp() |
| + self.fake.fault, self.fake.fault_at = "death", boundary |
| + with self.assertRaises(base.Death): |
| + self.run_roll() |
| + self.resume() |
| + self.assertEqual((self.fake.minimum, self.fake.desired), (2, 2)) |
| + self.assertEqual(self.fake.states[IID], "InService") |
| + self.assertIsNone(self.fake.fence) |
| + self.assertIsNone(self.store.active_id()) |
| + self.assert_h4() |
| + |
| + |
| +class AdapterH4Tests(unittest.TestCase): |
| + """H4 at the adapter: the real AWS adapter, with its CLI calls answered by |
| + the provider that punishes any other desired-lowering call.""" |
| + |
| + def setUp(self): |
| + directory = os.environ.get("TMPDIR") or str(Path.home() / ".cache") |
| + tmp = tempfile.TemporaryDirectory(prefix="region-held-h4-", dir=directory) |
| + self.addCleanup(tmp.cleanup) |
| + self.config = held_config(tmp.name) |
| + self.fake = HeldFake(self.config) |
| + self.adapter = roll.AWS(self.config) |
| + self.cli = [] |
| + |
| + def invoke(adapter, service, verb, args, **kwargs): |
| + self.cli.append(verb) |
| + return self.fake.invoke(service, verb, args, **kwargs) |
| + |
| + patcher = patch.object(roll.AWS, "invoke", autospec=True, side_effect=invoke) |
| + patcher.start() |
| + self.addCleanup(patcher.stop) |
| + |
| + def test_trap_fires_on_any_other_lowering(self): |
| + # The control: the provider really does punish a direct lowering. |
| + self.fake.invoke("autoscaling", "set-desired-capacity", ["--desired-capacity", "1"]) |
| + self.assertEqual(self.fake.h4_violations, ["set-desired-capacity"]) |
| + self.assertEqual(self.fake.states[PEER], "Terminated") |
| + |
| + def test_adapter_refuses_every_other_lowering(self): |
| + self.fake.states[IID] = "Standby" |
| + self.fake.minimum = self.fake.desired = 1 |
| + for op, args in (("desired", dict(value=0)), ("desired", dict(value=3)), ("desired", dict(value="2")), |
| + ("terminate", dict(iid=IID, decrement=True)), ("terminate", dict(iid=IID)), |
| + ("terminate", dict(iid=PEER, decrement=False)), |
| + ("enter", dict(iid=IID, decrement=False))): |
| + with self.subTest(op=op, args=args): |
| + self.cli.clear() |
| + with self.assertRaises(roll.Refusal) as caught: |
| + self.adapter.request(op, args) |
| + self.assertIn(str(caught.exception), {roll.TEXT["h4"], roll.TEXT["held"]}) |
| + self.assertNotIn("terminate-instance-in-auto-scaling-group", self.cli) |
| + self.assertNotIn("update-auto-scaling-group", self.cli) |
| + self.assertNotIn("enter-standby", self.cli) |
| + self.assertEqual(self.fake.h4_violations, []) |
| + self.assertEqual(self.fake.states[PEER], "InService") |
| + |
| + def test_terminate_of_standby_member_without_decrement(self): |
| + self.fake.states[IID] = "Standby" |
| + self.fake.minimum = self.fake.desired = 1 |
| + self.assertEqual(self.adapter.request("terminate", dict(iid=IID, decrement=False)), |
| + {"activity": "terminate-1"}) |
| + self.assertEqual(self.cli[-1], "terminate-instance-in-auto-scaling-group") |
| + self.assertEqual(self.fake.desired, 1) |
| + self.assertEqual(self.fake.h4_violations, []) |
| + |
| + def test_desired_only_raises(self): |
| + self.fake.minimum = self.fake.desired = 1 |
| + self.adapter.request("desired", dict(value=2)) |
| + self.assertEqual(self.fake.desired, 2) |
| + self.assertEqual(self.fake.h4_violations, []) |
| + |
| + def test_operator_enters_only_its_member(self): |
| + state = roll.State(self.config, owner=os.geteuid()) |
| + op = roll.Operator(self.config, self.fake, state) |
| + op.header = dict(iid=IID) |
| + for args in (dict(iid=PEER, decrement=True), dict(iid=IID, decrement=False)): |
| + with self.assertRaises(roll.Refusal): |
| + op.call("enter", **args) |
| + self.assertEqual(self.fake.calls, []) |
| + |
| + |
| +class RemoteCommandTests(unittest.TestCase): |
| + def test_commands(self): |
| + drain = roll.AWS.remote_command(dict(verb="drain", transaction="t6"), "n" * 32) |
| + self.assertIn("/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos " |
| + "system group-maintenance drain t6", drain) |
| + clear = roll.AWS.remote_command(dict(verb="fence-clear", transaction="t6"), "n" * 32) |
| + self.assertIn("group-maintenance fence-clear t6 && /opt/carlos/carlos system group-maintenance status", |
| + clear) |
| + stop = roll.AWS.remote_command(dict(verb="edge-stop"), "n" * 32) |
| + self.assertIn("systemctl stop carlos-edge.service; /usr/bin/systemctl show --property=MainPID " |
| + "--property=ActiveState carlos-edge.service", stop) |
| + for tx in ("-x", "a b", "", "x" * 81, None): |
| + with self.subTest(tx=tx): |
| + with self.assertRaises(roll.Refusal): |
| + roll.AWS.remote_command(dict(verb="drain", transaction=tx), "n" * 32) |
| + with self.assertRaises(roll.Refusal): |
| + roll.AWS.remote_command(dict(verb="drain-cancel", transaction="t6"), "n" * 32) |
| + |
| + def test_drain_output(self): |
| + report = dict(v=1, transaction="t6", result="ok") |
| + body = "\n".join(["noise", json.dumps(report)]) |
| + self.assertEqual(roll.AWS.drain_output(body, "0"), dict(exit=0, report=report)) |
| + failed = "\n".join([json.dumps(dict(report, result="failed")), "group-maintenance: drain failed"]) |
| + self.assertEqual(roll.AWS.drain_output(failed, "1")["report"]["result"], "failed") |
| + self.assertEqual(roll.AWS.drain_output("group-maintenance: fence of another transaction", "1"), |
| + dict(exit=1, report=None)) |
| + for code in ("2", "77", "124"): |
| + with self.assertRaises(roll.Refusal): |
| + roll.AWS.drain_output(body, code) |
| + |
| + def test_edge_stop_output(self): |
| + self.assertEqual(roll.AWS.edge_stop_output("MainPID=0\r\nActiveState=inactive\r\n"), |
| + dict(main_pid=0, active_state="inactive")) |
| + for body in ("MainPID=0\n", "MainPID=x\nActiveState=inactive\n", |
| + "MainPID=0\nMainPID=0\nActiveState=inactive\n", "MainPID=0\nActiveState=inactive\nOther=1\n"): |
| + with self.subTest(body=body): |
| + with self.assertRaises(roll.Refusal): |
| + roll.AWS.edge_stop_output(body) |
| + |
| + |
| +class ConfigTests(unittest.TestCase): |
| + def test_optional_keys(self): |
| + config = held_config("/state") |
| + self.assertEqual(roll.validate_config(dict(config)), config) |
| + self.assertEqual(roll.validate_config(dict(config, data_prefix="")), dict(config, data_prefix="")) |
| + base_config = base.test_config("/state") |
| + self.assertEqual(roll.validate_config(dict(base_config)), base_config) |
| + for bad in (dict(ha_floor="next"), dict(data_prefix="/x"), dict(data_prefix="a/../b"), |
| + dict(data_prefix="a/"), dict(other="x")): |
| + with self.subTest(bad=bad): |
| + with self.assertRaises(roll.Refusal): |
| + roll.validate_config(dict(config, **bad)) |
| + |
| + |
| +class DepartArgvTests(base.CLIHarness, unittest.TestCase): |
| + roll_module = entry = roll |
| + |
| + def setUp(self): |
| + super().setUp() |
| + with self.store.lock(): |
| + self.store.write(self.store.observation, dict(v=1, group_arn=self.config["group_arn"], |
| + hook=self.config["hook"], template=self.template, documented_no_hook=True)) |
| + |
| + def test_replace_without_floor_config_refuses_read_only(self): |
| + self.assertEqual(self.cli("replace", "--member", IID, "--transaction", "argv-replace"), 1) |
| + self.assert_first_group() |
| + self.assert_refusal("floor_refused") |
| + self.assertTrue(all(verb.startswith("describe-") or verb in {"start-session", "get-object"} |
| + for _, verb, _, _ in self.calls), self.calls) |
| + self.assertIsNone(self.store.active_id()) |
| + with closing(self.store.load("argv-replace", readonly=True)) as journal: |
| + self.assertEqual(journal.events[0]["header"], dict(kind="replace")) |
| + self.assertEqual(journal.last("done")["outcome"], "floor-refused") |
| + self.assertIn(self.roll_module.TEXT["rule_dr4"], self.stdout.getvalue()) |
| + |
| + def test_remove_with_two_members_refuses(self): |
| + self.assertEqual(self.cli("remove", "--member", IID), 1) |
| + self.assert_refusal("remove_minimum") |
| + |
| + def test_transaction_ids(self): |
| + for tx in ("-leading", "probe-x"): |
| + with self.subTest(tx=tx): |
| + self.calls.clear() |
| + self.assertEqual(self.cli("replace", "--member", IID, "--transaction=" + tx), 1) |
| + self.assertEqual(self.calls, []) |
| + self.assertEqual(self.cli("roll", "--member", IID, "--to-sha256", NEW, "--transaction=-x"), 1) |
| + |
| + |
| +if __name__ == "__main__": |
| + unittest.main() |
diff --git a/scripts/region_group_roll_test.py b/scripts/region_group_roll_test.py| index 2712ba216..add5820a4 100644 |
| --- a/scripts/region_group_roll_test.py |
| +++ b/scripts/region_group_roll_test.py |
| @@ -110,7 +110,7 @@ class Fake: |
| def request(self, op, args): |
| self.calls.append((op, copy.deepcopy(args))) |
| - write = op in ("minimum", "enter", "exit", "complete", "desired") or ( |
| + write = op in ("minimum", "enter", "exit", "complete", "desired", "terminate") 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 |