carlos / platform Public

scripts: PPv2 gate fixes: bound evidence, steady polls, locked apply

Review round 1 (Astra, Fable) and controller rulings R1-R4:
- apply goes straight into convergence; converge only resumes the
  same apply, never clears a failure, and needs polls spanning the
  probes, with health every 10 s independent of SSM (no gap > 15 s).
- probe records must cover exactly the NLB's public addresses, read
  from its interfaces by prereq, which also checks --sources against
  them and says it is automated checks only.
- every record back to prereq.json is checked; targets must match the
  apply; root and record directory are locked; per-run plan files.
- A steps allowed behind a barrier, B steps not; R steps never refuse
  on trust-status. Intent record before tofu apply; signals restore
  the tfvars before apply; one-line errors, no tracebacks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 1077a2e0737d55b328ebeef3646b494db5926d83 parent ab28a84
6 files changed, +1,493 −517
  • scripts/ppv2-probe.py +14 −3
  • scripts/ppv2-step.py +728 −318
  • scripts/ppv2_probe_test.py +76 −0
  • scripts/ppv2_step_test.py +672 −195
  • scripts/testdata/ppv2/probe-responses.json +2 −1
  • scripts/testdata/ppv2/trust-status.json +1 −0
diff --git a/scripts/ppv2-probe.py b/scripts/ppv2-probe.py
index 9817b2974..f53fec535 100755
--- a/scripts/ppv2-probe.py
+++ b/scripts/ppv2-probe.py
@@ -38,6 +38,8 @@ import time
SIGNATURE = b'\r\n\r\n\x00\r\nQUIT\n'
MARKER_SOURCE = '192.0.2.1'
MARKER_NET = ipaddress.ip_network('192.0.2.0/24')
+MARKER_TEXT = re.compile(r'(?<![\d.])192\.0\.2\.\d{1,3}(?!\d)')
+EXCHANGE_BOUND = 10.0 # one connection, connect to close, however the peer drips bytes
NEEDED = 30
INTERVAL = 2.0
CONNECT_TIMEOUT = 5.0
@@ -82,9 +84,9 @@ def outcome_from_raw(raw):
"""What came back on a connection that closed (or stopped) after raw."""
if not raw:
return {'kind': 'closed', 'detail': 'closed with no answer'}
- head, _, body = raw.partition(b'\r\n\r\n')
+ head, sep, body = raw.partition(b'\r\n\r\n')
match = STATUS_RE.match(head)
- if not match:
+ if not match or not sep: # no status line, or headers cut short: not an answer
return {'kind': 'garbled', 'detail': repr(raw[:80])}
headers = {}
for line in head.split(b'\r\n')[1:]:
@@ -128,13 +130,15 @@ def echoed_client(outcome):
def forged(outcome):
+ """The marker's network anywhere in an echo: as an entry, or anywhere in the
+ body, so an echo in another format still fails fast with the S3 reason."""
for entry in xff_entries(outcome):
try:
if ipaddress.ip_address(entry) in MARKER_NET:
return True
except ValueError:
continue
- return False
+ return outcome.get('kind') == 'answer' and bool(MARKER_TEXT.search(outcome.get('body', '')))
def describe(outcome):
@@ -246,6 +250,7 @@ class Connector:
def exchange(self, marker):
sock = None
+ deadline = time.monotonic() + EXCHANGE_BOUND
try:
sock, source = self.bound()
sock.settimeout(CONNECT_TIMEOUT)
@@ -257,6 +262,12 @@ class Connector:
sock.sendall(self.request)
raw = b''
while len(raw) < READ_LIMIT:
+ left = deadline - time.monotonic()
+ if left <= 0:
+ if raw:
+ break
+ raise TimeoutError(f'no answer within {EXCHANGE_BOUND:g} s')
+ sock.settimeout(min(CONNECT_TIMEOUT, left))
try:
chunk = sock.recv(READ_LIMIT - len(raw))
except (socket.timeout, TimeoutError):
diff --git a/scripts/ppv2-step.py b/scripts/ppv2-step.py
index 7c5b47d44..244de4507 100755
--- a/scripts/ppv2-step.py
+++ b/scripts/ppv2-step.py
@@ -13,11 +13,19 @@ in one of four states:
The only moves are S0 to S1 and S1 to S2 forward, and S2 to S1 back. None of
them changes PPv2 while preservation is off, so no node can pass through S3.
- prereq checks the prerequisites (spec 6.1) and writes prereq.json.
- apply makes one step on one target group through a targeted tofu plan
- and writes <step>-applied.json with every target's baseline.
- converge after apply, polls health and trust counters until both probe
- records are in, then writes <step>.json, the next step's evidence.
+ prereq the automated part of the prerequisites (spec 6.1): both target
+ groups in S0, every target armed with the NLB's node addresses,
+ barrier down, the trust alarm OK. Writes prereq.json with the
+ NLB's public addresses. Versions, the bootstrap object hash and a
+ delivered alarm notification are still checked by hand.
+ apply makes one step on one target group through a targeted tofu plan,
+ writes <step>-applied.json, then goes straight into convergence:
+ it polls target health every 10 s and trust counters every 30 s
+ until the probe records are in, and writes <step>.json, the next
+ step's evidence. Forward steps need --probe-records.
+ converge resumes the convergence of the latest apply of a step, after an
+ interrupted apply. Polls already made for that apply count, and a
+ failure already seen is never cleared.
Steps: A80, A443 (PPv2 on), B80, B443 (preservation off), R443, R80
(preservation back on). Nothing turns PPv2 off; there is no step for it.
@@ -27,15 +35,25 @@ in the root directory, which this script owns:
{"ppv2_preserve_client_ip":{"80":true,"443":true},
"ppv2_proxy_protocol_v2":{"80":false,"443":false}}
-Exit codes: 0 done or passed, 1 refused or failed, 2 invalid arguments.
+Records, in --record-dir: prereq.json, <step>-intent.json (written before
+tofu apply starts), <step>-applied.json, <step>-polls.jsonl (every poll, as
+it is made) and <step>.json. A run holds .ppv2-step.lock in the root and in
+the record directory; a second run refuses while one is held.
+
+Exit codes: 0 done or passed, 1 refused or failed, 2 invalid arguments,
+130 interrupted.
"""
import argparse
from collections import namedtuple
+from contextlib import contextmanager
from datetime import datetime, timezone
+import fcntl
import json
import os
from pathlib import Path
import re
+import secrets
+import signal
import subprocess
import sys
import time
@@ -49,7 +67,8 @@ STEPS = {
'R443': Step('443', 'preserve_client_ip', True, 'S2', 'S1', False),
'R80': Step('80', 'preserve_client_ip', True, 'S2', 'S1', False),
}
-# The record each step needs, passed and for the same NLB (spec 6.2, 6.4).
+# The record each step needs (spec 6.2, 6.4). A step walks the whole chain
+# back to prereq.json, so B80 also needs A80.json.
PREDECESSOR = {'A80': 'prereq', 'A443': 'A80', 'B80': 'A443', 'B443': 'B80', 'R443': None, 'R80': None}
# A reverse step undoes this forward step's evidence.
SUPERSEDES = {'R443': 'B443', 'R80': 'B80'}
@@ -58,6 +77,7 @@ STATE = {(True, False): 'S0', (True, True): 'S1', (False, True): 'S2', (False, F
LIVE_KEY = {'preserve_client_ip': 'preserve_client_ip.enabled', 'proxy_protocol_v2': 'proxy_protocol_v2.enabled'}
TFVARS_FILE = 'ppv2.auto.tfvars.json'
TFVARS_KEY = {'preserve_client_ip': 'ppv2_preserve_client_ip', 'proxy_protocol_v2': 'ppv2_proxy_protocol_v2'}
+LOCK_FILE = '.ppv2-step.lock'
COUNTERS = ('proxied', 'no_client', 'no_client_refused', 'ignored', 'ignored_private',
'marker_trusted', 'malformed', 'timeout')
# Counters that must not move from the apply's baseline until convergence.
@@ -67,23 +87,74 @@ TRUST_STATUS = '/opt/carlos/carlos system edge trust-status'
ARMED_LINE = 'edge: proxy protocol: armed on'
JOURNAL = "journalctl -u carlos-edge.service -o cat --no-pager | grep -F '%s' | tail -n 1" % ARMED_LINE
ARMED_RE = re.compile(r'edge: proxy protocol: armed on :80 and :443, trusting (\S+), barrier (up|down)')
+INSTANCE_RE = re.compile(r'^i-[0-9a-f]{8,17}$')
+MANUAL_PREREQUISITES = (
+ 'vN or later on every target in both target groups (spec 6.1 item 1)',
+ "the region's boot/bootstrap-object and boot/bootstrap-sha256 name a vN build, checked against the object's hash (item 2)",
+ 'the group module at vN (item 4)',
+ 'a trust alarm notification seen delivered (item 5)',
+)
HEALTH_EVERY = 10.0
+# The target groups' health check runs every 10 s and needs two results to
+# change a target's state, so a target reported unhealthy stays so for at
+# least 20 s. Observations at most 15 s apart cannot miss one.
+HEALTH_GAP_MAX = 15.0
TRUST_EVERY = 30.0
SSM_BOUND = 120.0
+TICK = 1.0
+TERMINAL = ('Success', 'Failed', 'TimedOut', 'Cancelled', 'Cancelling', 'Undeliverable', 'Terminated')
+SSM_ERROR_MARK = '----------ERROR-------'
class Refused(Exception):
pass
-def now_iso():
- return datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
+class Interrupted(BaseException):
+ """A signal arrived where the run must stop; carries what it means."""
+
+
+# Which part of a run a signal lands in. During tofu apply a signal is only
+# noted: the apply finishes and its record is written before the run stops.
+PHASE = {'name': 'idle', 'pending': None}
+
+
+def on_signal(signum, frame):
+ name = signal.Signals(signum).name
+ if PHASE['name'] in ('apply', 'restore'):
+ PHASE['pending'] = name
+ print(f'{name} noted; waiting for tofu apply or the restore to finish', file=sys.stderr)
+ return
+ raise Interrupted(name)
+
+
+class Clock:
+ def time(self):
+ return time.time()
+
+ def sleep(self, seconds):
+ time.sleep(seconds)
+
+
+def iso(t):
+ return datetime.fromtimestamp(t, timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
def parse_time(text):
return datetime.fromisoformat(text.replace('Z', '+00:00'))
+def epoch(text):
+ try:
+ return parse_time(text).timestamp()
+ except (AttributeError, TypeError, ValueError):
+ return None
+
+
+def one_line(text):
+ return ' '.join(str(text).split())
+
+
def state_of(preserve, ppv2):
return STATE[(preserve, ppv2)]
@@ -160,6 +231,9 @@ def plan_refusal(plan, address, attribute, before, after):
if (norm(old[attribute]), norm(new[attribute])) != (norm(before), norm(after)):
return (f'the plan sets {attribute} from {norm(old[attribute])} to {norm(new[attribute])}; '
f'this step sets it from {norm(before)} to {norm(after)}')
+ # Defence in depth: a preservation step only ever runs with PPv2 on.
+ if attribute == 'preserve_client_ip' and norm(new.get('proxy_protocol_v2')) != 'true':
+ return f'the plan leaves proxy_protocol_v2 {norm(new.get("proxy_protocol_v2"))} on {address}; a preservation step needs it on'
return None
@@ -186,6 +260,16 @@ def parse_trust(text):
return doc
+def trust_of(iid, code, stdout, stderr):
+ """A target's trust-status answer as a dict, or a string saying why there is none."""
+ if code == 2:
+ return f'{iid} is not armed: {one_line(stderr)}'
+ if code != 0:
+ return f'{iid}: trust-status failed ({code}): {one_line(stderr)}'
+ doc = parse_trust(stdout)
+ return doc if doc else f'{iid}: trust-status answered something that is not a status line'
+
+
def first_json(stdout, key):
"""The JSON document in stdout carrying key: the whole output, or one of its lines."""
try:
@@ -214,15 +298,15 @@ def find_resource(module, address):
class Cloud:
"""The aws and tofu calls, through the executables on PATH."""
- def __init__(self, profile, region, sleep=time.sleep, clock=time.monotonic):
+ def __init__(self, profile, region, clock=None):
self.profile, self.region = profile, region
- self.sleep, self.clock = sleep, clock
+ self.clock = clock or Clock()
def aws(self, *args):
result = subprocess.run(['aws', '--profile', self.profile, '--region', self.region, '--output', 'json', *args],
capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
if result.returncode != 0:
- raise Refused(f"aws {' '.join(args[:2])} failed: {result.stderr.strip()}")
+ raise Refused(f"aws {' '.join(args[:2])} failed: {one_line(result.stderr)}")
try:
return json.loads(result.stdout)
except ValueError:
@@ -251,46 +335,69 @@ class Cloud:
doc = self.aws('elbv2', 'describe-target-health', '--target-group-arn', tg_arn)
return {d['Target']['Id']: d['TargetHealth']['State'] for d in doc.get('TargetHealthDescriptions') or []}
+ def interfaces(self, nlb_arn):
+ """[(private address, public address or None)] of the NLB's node interfaces."""
+ suffix = nlb_arn.split(':loadbalancer/', 1)[-1]
+ if not suffix.startswith('net/'):
+ raise Refused(f'{nlb_arn} is not a network load balancer ARN')
+ doc = self.aws('ec2', 'describe-network-interfaces', '--filters',
+ json.dumps([{'Name': 'description', 'Values': ['ELB ' + suffix]}]))
+ return sorted((n.get('PrivateIpAddress'), (n.get('Association') or {}).get('PublicIp'))
+ for n in doc.get('NetworkInterfaces') or [])
+
+ def send(self, targets, command):
+ return self.aws('ssm', 'send-command', '--document-name', 'AWS-RunShellScript',
+ '--comment', 'ppv2-step', '--timeout-seconds', '60', '--instance-ids', *targets,
+ '--parameters', json.dumps({'commands': [command]}))['Command']['CommandId']
+
+ def invocations(self, cid):
+ """{instance: (status, response code, stdout, stderr)}, one call for every target."""
+ doc = self.aws('ssm', 'list-command-invocations', '--command-id', cid, '--details')
+ out = {}
+ for inv in doc.get('CommandInvocations') or []:
+ plugin = (inv.get('CommandPlugins') or [{}])[0]
+ stdout, _, stderr = (plugin.get('Output') or '').partition(SSM_ERROR_MARK)
+ out[inv.get('InstanceId')] = (inv.get('Status'), plugin.get('ResponseCode'), stdout, stderr)
+ return out
+
def ssm(self, targets, command):
- """{instance: (response code, stdout, stderr)} for command run on every target."""
- cid = self.aws('ssm', 'send-command', '--document-name', 'AWS-RunShellScript',
- '--comment', 'ppv2-step', '--timeout-seconds', '60', '--instance-ids', *targets,
- '--parameters', json.dumps({'commands': [command]}))['Command']['CommandId']
- results, until = {}, self.clock() + SSM_BOUND
- while len(results) < len(targets):
- for iid in targets:
- if iid in results:
- continue
- try:
- doc = self.aws('ssm', 'get-command-invocation', '--command-id', cid, '--instance-id', iid)
- except Refused:
- doc = {} # InvocationDoesNotExist until the command registers
- if doc.get('Status') in ('Success', 'Failed', 'TimedOut', 'Cancelled', 'Cancelling'):
- results[iid] = (doc.get('ResponseCode'), doc.get('StandardOutputContent') or '',
- doc.get('StandardErrorContent') or '')
- if len(results) < len(targets):
- if self.clock() > until:
- missing = ', '.join(t for t in targets if t not in results)
- raise Refused(f'SSM command {cid} did not finish on {missing}')
- self.sleep(2)
- return results
+ """{instance: (response code, stdout, stderr)}, waiting for every target."""
+ cid = self.send(targets, command)
+ results, until = {}, self.clock.time() + SSM_BOUND
+ while True:
+ try:
+ for iid, (status, code, stdout, stderr) in self.invocations(cid).items():
+ if iid in targets and status in TERMINAL:
+ results[iid] = (code, stdout, stderr)
+ except Refused:
+ pass # not registered yet
+ if len(results) == len(targets):
+ return results
+ if self.clock.time() > until:
+ missing = ', '.join(t for t in targets if t not in results)
+ raise Refused(f'SSM command {cid} did not finish on {missing}')
+ self.clock.sleep(2)
def trust(self, targets):
"""{instance: trust-status dict, or a string saying why there is none}."""
- out = {}
- for iid, (code, stdout, stderr) in self.ssm(targets, TRUST_STATUS).items():
- if code == 2:
- out[iid] = f'{iid} is not armed: {stderr.strip()}'
- elif code != 0:
- out[iid] = f'{iid}: trust-status failed ({code}): {stderr.strip()}'
- else:
- doc = parse_trust(stdout)
- out[iid] = doc if doc else f'{iid}: trust-status answered something that is not a status line'
- return out
+ return {iid: trust_of(iid, *answer) for iid, answer in self.ssm(targets, TRUST_STATUS).items()}
def tofu(self, root, *args):
- return subprocess.run(['tofu', f'-chdir={root}', *args], capture_output=True, text=True,
- stdin=subprocess.DEVNULL)
+ # Its own session, so a terminal Ctrl-C reaches only this script, which
+ # then stops tofu with SIGINT (never SIGKILL: that can strand a state lock).
+ proc = subprocess.Popen(['tofu', f'-chdir={root}', *args], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ stdin=subprocess.DEVNULL, text=True, start_new_session=True)
+ try:
+ out, err = proc.communicate()
+ except BaseException:
+ proc.send_signal(signal.SIGINT)
+ try:
+ proc.communicate(timeout=120)
+ except BaseException:
+ proc.kill()
+ proc.communicate()
+ raise
+ return subprocess.CompletedProcess(proc.args, proc.returncode, out, err)
def registered_refusals(health, targets):
@@ -301,7 +408,7 @@ def registered_refusals(health, targets):
elif health[iid] != 'healthy':
reasons.append(f'{iid} is {health[iid]}')
for iid in sorted(set(health) - set(targets)):
- reasons.append(f'{iid} is registered but not in --targets')
+ reasons.append(f'{iid} is registered but not in the targets')
return reasons
@@ -317,33 +424,87 @@ def load_record(path):
return doc
+def atomic_write(path, data):
+ tmp = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
+ try:
+ tmp.write_bytes(data)
+ os.replace(tmp, path)
+ except BaseException:
+ remove_quietly(tmp)
+ raise
+
+
def write_record(path, doc):
- tmp = path.with_name(path.name + '.tmp')
- tmp.write_text(json.dumps(doc, indent=2, sort_keys=True) + '\n')
- os.replace(tmp, path)
+ atomic_write(path, (json.dumps(doc, indent=2, sort_keys=True) + '\n').encode())
-def predecessor_refusal(step, record_dir, nlb_arn):
- pred = PREDECESSOR[step]
- if pred is None:
- return None
- record = load_record(record_dir / f'{pred}.json')
+def remove_quietly(path):
+ try:
+ path.unlink()
+ except FileNotFoundError:
+ pass
+
+
+@contextmanager
+def locked(*dirs):
+ """Exclusive, non-blocking: a second run refuses rather than waits."""
+ handles = []
+ try:
+ for d in sorted({str(Path(d).resolve()) for d in dirs}):
+ path = Path(d) / LOCK_FILE
+ handle = open(path, 'a')
+ try:
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ handle.close()
+ raise Refused(f'another ppv2-step run holds {path}')
+ handles.append(handle)
+ yield
+ finally:
+ for handle in handles:
+ handle.close()
+
+
+def record_refusal(name, record_dir, nlb_arn):
+ record = load_record(record_dir / f'{name}.json')
if record is None:
- return f'step {step} needs {pred}.json in {record_dir}'
+ return f'{name}.json is missing from {record_dir}'
if record.get('passed') is not True:
- return f'{pred}.json did not pass'
+ return f'{name}.json did not pass'
if record.get('nlb_arn') != nlb_arn:
- return f"{pred}.json is for another load balancer ({record.get('nlb_arn')})"
- if pred != 'prereq':
- if record.get('step') != pred:
- return f"{pred}.json is a record of {record.get('step')}"
- applied = load_record(record_dir / f'{pred}-applied.json')
- if applied is None or applied.get('applied_at') != record.get('applied_at') or applied.get('nlb_arn') != nlb_arn:
- return (f"{pred}.json is not for its latest apply ({pred}-applied.json applied_at "
- f"{(applied or {}).get('applied_at')}, {pred}.json {record.get('applied_at')})")
+ return f"{name}.json is for another load balancer ({record.get('nlb_arn')})"
+ if name == 'prereq':
+ return None
+ if record.get('step') != name:
+ return f"{name}.json is a record of {record.get('step')}"
+ applied = load_record(record_dir / f'{name}-applied.json')
+ if applied is None or applied.get('applied_at') != record.get('applied_at') or applied.get('nlb_arn') != nlb_arn:
+ return (f"{name}.json is not for its latest apply ({name}-applied.json applied_at "
+ f"{(applied or {}).get('applied_at')}, {name}.json {record.get('applied_at')})")
return None
+def chain_refusal(step, record_dir, nlb_arn):
+ """Every record back to prereq.json: passed, this NLB, bound to its latest apply."""
+ name = PREDECESSOR[step]
+ while name:
+ reason = record_refusal(name, record_dir, nlb_arn)
+ if reason:
+ return f'step {step} needs {PREDECESSOR[step]} and every step before it: {reason}'
+ name = PREDECESSOR.get(name)
+ return None
+
+
+def prereq_for(record_dir, nlb_arn):
+ """prereq.json for this NLB, which names its node and public addresses."""
+ prereq = load_record(record_dir / 'prereq.json')
+ if not prereq or prereq.get('passed') is not True or prereq.get('nlb_arn') != nlb_arn:
+ raise Refused(f'convergence needs a passed prereq.json for {nlb_arn} in {record_dir}')
+ if not prereq.get('public_addresses') or not prereq.get('sources'):
+ raise Refused('prereq.json names no NLB addresses; run prereq again with this version')
+ return prereq
+
+
def tfvars_check(doc, port, live):
if not isinstance(doc, dict) or set(doc) != set(TFVARS_KEY.values()):
return f'{TFVARS_FILE} must hold exactly {", ".join(sorted(TFVARS_KEY.values()))}'
@@ -360,7 +521,7 @@ def tfvars_check(doc, port, live):
def check_state_address(cloud, args):
result = cloud.tofu(args.root, 'state', 'show', '-json', args.tg_address)
if result.returncode != 0:
- raise Refused(f'tofu state show {args.tg_address} failed: {result.stderr.strip()}')
+ raise Refused(f'tofu state show {args.tg_address} failed: {one_line(result.stderr)}')
doc = first_json(result.stdout, 'values')
if doc is None:
raise Refused(f'tofu state show {args.tg_address} printed no state')
@@ -374,82 +535,161 @@ def check_state_address(cloud, args):
raise Refused(f"{args.tg_address} has port {values.get('port')}, not {args.port}")
+def split(text):
+ items = [t.strip() for t in (text or '').split(',') if t.strip()]
+ if not items or len(set(items)) != len(items):
+ raise Refused(f'a comma-separated list without repeats is required, not {text!r}')
+ return items
+
+
+def target_list(text):
+ targets = split(text)
+ for iid in targets:
+ if not INSTANCE_RE.match(iid):
+ raise Refused(f'{iid!r} is not an instance id')
+ return targets
+
+
+def pending_intent(record_dir, step):
+ intent = load_record(record_dir / f'{step}-intent.json')
+ applied = load_record(record_dir / f'{step}-applied.json')
+ if intent and (not applied or applied.get('intent_started_at') != intent.get('started_at')):
+ return (f' ({step}-intent.json records an apply started at {intent.get("started_at")} that wrote no '
+ f'{step}-applied.json; see its tfvars_before)')
+ return ''
+
+
def cmd_apply(args, cloud):
step = STEPS[args.step]
if step.port != args.port:
raise Refused(f'step {args.step} is for port {step.port}, not {args.port}')
- record_dir = Path(args.record_dir)
- if not record_dir.is_dir():
- raise Refused(f'--record-dir {record_dir} is not a directory')
- targets = split(args.targets)
- # Before anything else: the address names the target group we were given.
- check_state_address(cloud, args)
- cloud.target_group(args.tg_arn, args.nlb_arn, args.port)
- live = cloud.attributes(args.tg_arn)
- reason = step_refusal(args.step, live)
- if reason:
- raise Refused(reason)
- reason = predecessor_refusal(args.step, record_dir, args.nlb_arn)
- if reason:
- raise Refused(reason)
- reasons = registered_refusals(cloud.health(args.tg_arn), targets)
- if step.forward and reasons:
- raise Refused('every target must be registered and healthy: ' + '; '.join(reasons))
- baseline = cloud.trust(targets)
- if step.forward:
- for iid in targets:
- status = baseline[iid]
- if isinstance(status, str):
- raise Refused(status)
- if not status['armed']:
- raise Refused(f'{iid} is not armed')
- if status['barrier']:
- raise Refused(f'the trust barrier is up on {iid}; no forward step while it is up (spec 4.7)')
- tfvars = Path(args.root) / TFVARS_FILE
- try:
- original = tfvars.read_bytes()
- doc = json.loads(original)
- except (OSError, ValueError) as err:
- raise Refused(f'cannot read {tfvars}: {err}')
- reason = tfvars_check(doc, args.port, live)
- if reason:
- raise Refused(reason)
- doc[TFVARS_KEY[step.attribute]][args.port] = step.value
- planfile = f'ppv2-{args.step}.tfplan'
- tfvars.write_bytes((json.dumps(doc, indent=2) + '\n').encode())
- try:
- result = cloud.tofu(args.root, 'plan', '-input=false', '-lock=true', f'-target={args.tg_address}',
- f'-out={planfile}')
- if result.returncode != 0:
- raise Refused(f'tofu plan failed: {result.stderr.strip()[-2000:]}')
- shown = cloud.tofu(args.root, 'show', '-json', planfile)
- if shown.returncode != 0:
- raise Refused(f'tofu show failed: {shown.stderr.strip()}')
- plan = first_json(shown.stdout, 'resource_changes')
- reason = plan_refusal(plan, args.tg_address, step.attribute, live[step.attribute], step.value)
+ record_dir, root = Path(args.record_dir), Path(args.root)
+ for d, flag in ((record_dir, '--record-dir'), (root, '--root')):
+ if not d.is_dir():
+ raise Refused(f'{flag} {d} is not a directory')
+ targets = target_list(args.targets)
+ paths = split(args.probe_records) if args.probe_records else None
+ if step.forward and not paths:
+ raise Refused(f'forward step {args.step} needs --probe-records, one per NLB address: apply goes on into convergence')
+ with locked(root, record_dir):
+ # Before anything else: the address names the target group we were given.
+ check_state_address(cloud, args)
+ cloud.target_group(args.tg_arn, args.nlb_arn, args.port)
+ live = cloud.attributes(args.tg_arn)
+ reason = step_refusal(args.step, live)
+ if reason:
+ raise Refused(reason + pending_intent(record_dir, args.step))
+ reason = chain_refusal(args.step, record_dir, args.nlb_arn)
if reason:
raise Refused(reason)
- except BaseException:
- tfvars.write_bytes(original)
- remove_quietly(Path(args.root) / planfile)
- raise
- # From here the file keeps the new value: if the apply fails part way,
- # the attribute may already have changed, and a file put back would ask
- # the next ordinary plan to undo it.
- applied_at = now_iso()
- result = cloud.tofu(args.root, 'apply', '-input=false', planfile)
- remove_quietly(Path(args.root) / planfile)
- if result.returncode != 0:
- raise Refused(f'tofu apply failed; {tfvars.name} keeps the new value; read the live attributes '
- f'before anything else: {result.stderr.strip()[-2000:]}')
- supersede(record_dir, SUPERSEDES.get(args.step), applied_at)
- write_record(record_dir / f'{args.step}-applied.json', {
- 'nlb_arn': args.nlb_arn, 'port': args.port, 'step': args.step, 'applied_at': applied_at,
- 'tg_arn': args.tg_arn, 'tg_address': args.tg_address, 'targets': targets,
- 'from': step.source, 'to': step.target, 'baseline': baseline})
- print(f'{args.step} applied to {args.tg_address} at {applied_at}: {step.source} to {step.target}. '
- f'Now run the probes on both NLB addresses and `converge`.')
- return 0
+ if paths:
+ public = prereq_for(record_dir, args.nlb_arn)['public_addresses']
+ if len(paths) != len(public):
+ raise Refused(f'--probe-records needs one record per NLB address ({len(public)}: {", ".join(public)})')
+ reasons = registered_refusals(cloud.health(args.tg_arn), targets)
+ if step.forward and reasons:
+ raise Refused('every target must be registered and healthy: ' + '; '.join(reasons))
+ baseline_at = cloud.clock.time()
+ try:
+ baseline = cloud.trust(targets)
+ except Refused as err:
+ if step.forward:
+ raise
+ # Rollback is the safe direction and is most needed when boxes are unwell.
+ baseline = {iid: f'trust-status not collected: {err}' for iid in targets}
+ if step.forward:
+ for iid in targets:
+ status = baseline[iid]
+ if isinstance(status, str):
+ raise Refused(status)
+ if not status['armed']:
+ raise Refused(f'{iid} is not armed')
+ # In S0 and S1 no client is trusted, so an A step is allowed behind a
+ # barrier: it is the way forward again after an S3 incident (spec 6.5).
+ if status['barrier'] and step.attribute == 'preserve_client_ip':
+ raise Refused(f'the trust barrier is up on {iid}; no B step while it is up (spec 4.7)')
+ tfvars = root / TFVARS_FILE
+ try:
+ original = tfvars.read_bytes()
+ doc = json.loads(original)
+ except (OSError, ValueError) as err:
+ raise Refused(f'cannot read {tfvars}: {err}')
+ reason = tfvars_check(doc, args.port, live)
+ if reason:
+ raise Refused(reason + pending_intent(record_dir, args.step))
+ doc[TFVARS_KEY[step.attribute]][args.port] = step.value
+ edited = (json.dumps(doc, indent=2) + '\n').encode()
+ planfile = f'.ppv2-{args.step}-{os.getpid()}-{secrets.token_hex(4)}.tfplan'
+ intent_path = record_dir / f'{args.step}-intent.json'
+ PHASE['name'] = 'pre-apply'
+ try:
+ atomic_write(tfvars, edited)
+ result = cloud.tofu(root, 'plan', '-input=false', '-lock=true', f'-target={args.tg_address}',
+ f'-out={planfile}')
+ if result.returncode != 0:
+ raise Refused(f'tofu plan failed: {one_line(result.stderr)[-2000:]}')
+ shown = cloud.tofu(root, 'show', '-json', planfile)
+ if shown.returncode != 0:
+ raise Refused(f'tofu show failed: {one_line(shown.stderr)}')
+ plan = first_json(shown.stdout, 'resource_changes')
+ reason = plan_refusal(plan, args.tg_address, step.attribute, live[step.attribute], step.value)
+ if reason:
+ raise Refused(reason)
+ intent = {'step': args.step, 'nlb_arn': args.nlb_arn, 'port': args.port, 'tg_arn': args.tg_arn,
+ 'tg_address': args.tg_address, 'attribute': step.attribute, 'before': live[step.attribute],
+ 'after': step.value, 'from': step.source, 'to': step.target, 'started_at': iso(cloud.clock.time()),
+ 'planfile': planfile, 'tfvars_before': original.decode(), 'tfvars_after': edited.decode()}
+ write_record(intent_path, intent)
+ PHASE['name'] = 'apply'
+ except BaseException as err:
+ PHASE['name'] = 'restore' # a second signal must not cut the restore short
+ try:
+ restore(tfvars, original)
+ remove_quietly(root / planfile)
+ finally:
+ PHASE['name'] = 'idle'
+ if isinstance(err, Interrupted):
+ raise Interrupted(f'{err} before tofu apply; {TFVARS_FILE} restored; nothing applied') from None
+ raise
+ # From here the file keeps the new value and the intent stays: once tofu
+ # apply has started the attribute may have changed, and a file put back
+ # would ask the next ordinary plan to undo it.
+ try:
+ result = cloud.tofu(root, 'apply', '-input=false', planfile)
+ finally:
+ PHASE['name'] = 'idle'
+ remove_quietly(root / planfile)
+ applied_at = cloud.clock.time()
+ if result.returncode != 0:
+ raise Refused(
+ f'tofu apply of {args.step} failed after it started. {TFVARS_FILE} keeps {step.attribute}='
+ f'{norm(step.value)} and {intent_path.name} records the attempt; no {args.step}-applied.json was '
+ f'written. Read the live attributes now: in {step.target}, the change happened; still in '
+ f'{step.source}, put {TFVARS_FILE} back from the intent\'s tfvars_before before any other plan. '
+ f'tofu: {one_line(result.stderr)[-1500:]}')
+ supersede(record_dir, SUPERSEDES.get(args.step), iso(applied_at))
+ applied = {
+ 'nlb_arn': args.nlb_arn, 'port': args.port, 'step': args.step, 'applied_at': iso(applied_at),
+ 'tg_arn': args.tg_arn, 'tg_address': args.tg_address, 'targets': targets,
+ 'from': step.source, 'to': step.target, 'baseline': baseline, 'baseline_at': iso(baseline_at),
+ 'intent_started_at': intent['started_at']}
+ write_record(record_dir / f'{args.step}-applied.json', applied)
+ print(f'{args.step} applied to {args.tg_address} at {iso(applied_at)}: {step.source} to {step.target}.')
+ if PHASE['pending']:
+ raise Interrupted(f"{PHASE['pending']} during tofu apply; {args.step} is applied; resume with converge")
+ if not paths:
+ return 0
+ print(f'Converging: start the probes on {len(paths)} NLB addresses now; waiting for {", ".join(paths)}.')
+ return converge(cloud, record_dir, applied, paths, args.timeout)
+
+
+def restore(path, original):
+ try:
+ if path.read_bytes() == original:
+ return
+ except OSError:
+ pass
+ atomic_write(path, original)
def supersede(record_dir, forward, applied_at):
@@ -462,238 +702,397 @@ def supersede(record_dir, forward, applied_at):
os.replace(path, record_dir / name.replace('.json', f'.superseded-{stamp}.json'))
-def remove_quietly(path):
- try:
- path.unlink()
- except FileNotFoundError:
- pass
+class PollLog:
+ """Every observation for one apply, appended as it is made, so an
+ interrupted run's polls (and any failure they saw) survive into a resume."""
+ def __init__(self, path, applied_at):
+ self.path, self.applied_at = path, applied_at
-def split(text):
- items = [t.strip() for t in text.split(',') if t.strip()]
- if not items or len(set(items)) != len(items):
- raise Refused(f'a comma-separated list without repeats is required, not {text!r}')
- return items
+ def read(self):
+ try:
+ lines = self.path.read_text().splitlines()
+ except FileNotFoundError:
+ return []
+ out = []
+ for line in lines:
+ try:
+ entry = json.loads(line)
+ except ValueError:
+ continue # a line cut short by a kill
+ if entry.get('applied_at') == self.applied_at:
+ out.append(entry)
+ return out
+ def add(self, entry):
+ entry = dict(entry, applied_at=self.applied_at)
+ with open(self.path, 'a') as f:
+ f.write(json.dumps(entry, sort_keys=True) + '\n')
+ f.flush()
+ os.fsync(f.fileno())
+ return entry
-def probe_findings(paths, applied, step):
- """(reasons, summaries) for the two probe records against the applied record."""
- reasons, summaries, addresses = [], [], []
- expect = PROBE_EXPECT[step[0]]
- applied_at = parse_time(applied['applied_at'])
+
+class TrustJob:
+ """One trust-status poll that does not block the health schedule."""
+
+ def __init__(self, cloud, targets):
+ self.cloud, self.targets = cloud, targets
+ self.started = cloud.clock.time()
+ self.results, self.error = {}, None
+ try:
+ self.cid = cloud.send(targets, TRUST_STATUS)
+ except Refused as err:
+ self.cid, self.error = None, str(err)
+
+ def check(self):
+ """True once every target answered (or the poll cannot go on)."""
+ if self.cid is None:
+ return True
+ try:
+ for iid, (status, code, stdout, stderr) in self.cloud.invocations(self.cid).items():
+ if iid in self.targets and status in TERMINAL and iid not in self.results:
+ self.results[iid] = trust_of(iid, code, stdout, stderr)
+ except Refused:
+ pass
+ return len(self.results) == len(self.targets) or self.cloud.clock.time() - self.started > SSM_BOUND
+
+ def entry(self):
+ status = {iid: self.results.get(iid, self.error or f'{iid}: no trust-status within {SSM_BOUND:g} s')
+ for iid in self.targets}
+ return {'kind': 'trust', 'at': iso(self.started), 'done_at': iso(self.cloud.clock.time()), 'status': status}
+
+
+def load_probes(paths):
+ docs = []
for path in paths:
try:
doc = json.loads(Path(path).read_text())
+ docs.append((str(path), doc if isinstance(doc, dict) else None))
except (OSError, ValueError):
- reasons.append(f'probe record {Path(path).name} did not arrive or is not JSON')
- continue
+ docs.append((str(path), None))
+ return docs
+
+
+def probes_ready(paths, clock):
+ """Every record is in, and the clock is past every probe's finish."""
+ docs = load_probes(paths)
+ if any(doc is None for _, doc in docs):
+ return False
+ finishes = [epoch(doc.get('finished_at')) for _, doc in docs]
+ return all(f is None or clock.time() >= f for f in finishes)
+
+
+def converge(cloud, record_dir, applied, paths, timeout):
+ """Polls until the probe records are in, then writes <step>.json. Returns the exit code."""
+ step, clock = applied['step'], cloud.clock
+ prereq = prereq_for(record_dir, applied['nlb_arn'])
+ if len(paths) != len(prereq['public_addresses']):
+ raise Refused(f"converge needs one probe record per NLB address ({len(prereq['public_addresses'])}: "
+ f"{', '.join(prereq['public_addresses'])})")
+ prior = load_record(record_dir / f'{step}.json')
+ if prior and prior.get('applied_at') == applied['applied_at'] and prior.get('passed') is True:
+ raise Refused(f'{step}.json already passed for the apply at {applied["applied_at"]}; nothing to resume')
+ log = PollLog(record_dir / f'{step}-polls.jsonl', applied['applied_at'])
+ targets = applied['targets']
+
+ def poll_health():
+ t = clock.time()
+ try:
+ log.add({'kind': 'health', 'at': iso(t), 'health': cloud.health(applied['tg_arn'])})
+ except Refused as err:
+ log.add({'kind': 'health', 'at': iso(t), 'error': str(err)})
+
+ def poll_state():
+ t = clock.time()
+ try:
+ live = cloud.attributes(applied['tg_arn'])
+ log.add({'kind': 'state', 'at': iso(t), 'state': state_of(live['preserve_client_ip'], live['proxy_protocol_v2'])})
+ except Refused as err:
+ log.add({'kind': 'state', 'at': iso(t), 'error': str(err)})
+
+ deadline = clock.time() + timeout
+ next_health = next_trust = clock.time()
+ job = None
+ try:
+ while True:
+ now = clock.time()
+ if now >= next_health:
+ poll_health()
+ next_health = now + HEALTH_EVERY
+ if job is None and now >= next_trust:
+ job = TrustJob(cloud, targets)
+ if job is not None and job.check():
+ log.add(job.entry())
+ next_trust, job = job.started + TRUST_EVERY, None
+ if probes_ready(paths, clock) or clock.time() >= deadline:
+ break
+ clock.sleep(TICK)
+ # The last look, after the probes finished: health, the counters
+ # (retried, since this one is required), and the target group's state.
+ poll_health()
+ for _ in range(3):
+ job = TrustJob(cloud, targets)
+ while not job.check():
+ clock.sleep(2)
+ entry = log.add(job.entry())
+ if all(isinstance(s, dict) for s in entry['status'].values()):
+ break
+ poll_state()
+ except Interrupted as err:
+ raise Interrupted(f'{err} during convergence of {step}; no verdict written; the polls so far are kept in '
+ f'{log.path.name}; resume with converge')
+ reasons, summary = evaluate(step, applied, log.read(), load_probes(paths), prereq, prior)
+ passed = not reasons
+ record = dict(summary, nlb_arn=applied['nlb_arn'], port=applied['port'], step=step, tg_arn=applied['tg_arn'],
+ applied_at=applied['applied_at'], converged_at=iso(clock.time()), passed=passed, reasons=reasons,
+ targets=targets, polls=log.path.name,
+ proxied_scope='proxied_by_node sums both listeners (:80 and :443)')
+ write_record(record_dir / f'{step}.json', record)
+ if passed:
+ print(f'{step} converged; {step}.json passed')
+ return 0
+ for reason in reasons:
+ print(f'not converged: {reason}', file=sys.stderr)
+ return 1
+
+
+def probe_findings(docs, applied, step, public):
+ """(reasons, summaries, window) for the probe records against the apply and the NLB."""
+ reasons, summaries, starts, finishes, addresses = [], [], [], [], []
+ expect = PROBE_EXPECT[step[0]]
+ applied_at = epoch(applied['applied_at'])
+ for path, doc in docs:
name = Path(path).name
+ if doc is None:
+ reasons.append(f'probe record {name} did not arrive or is not JSON')
+ continue
addresses.append(doc.get('nlb_ip'))
+ if doc.get('nlb_ip') not in public:
+ reasons.append(f"probe record {name} names {doc.get('nlb_ip')}, which is not an address of this NLB "
+ f"({', '.join(public)})")
if str(doc.get('port')) != applied['port']:
reasons.append(f"probe record {name} is for port {doc.get('port')}, not {applied['port']}")
if doc.get('expect') != expect:
reasons.append(f"probe record {name} expected {doc.get('expect')}; step {step} needs {expect}")
- try:
- started = parse_time(doc['started_at'])
- except (KeyError, TypeError, ValueError):
- started = None
+ started, finished = epoch(doc.get('started_at')), epoch(doc.get('finished_at'))
if started is None or started <= applied_at:
reasons.append(f"probe record {name} started before the apply ({doc.get('started_at')})")
+ if finished is None or (started is not None and finished < started):
+ reasons.append(f"probe record {name} has no usable finished_at ({doc.get('finished_at')})")
+ if started is not None:
+ starts.append(started)
+ if finished is not None:
+ finishes.append(finished)
if doc.get('passed') is not True:
reasons.append(f"probe record {name} did not pass: {doc.get('reason')}")
- summaries.append({'record': str(path), 'nlb_ip': doc.get('nlb_ip'), 'port': doc.get('port'),
+ summaries.append({'record': path, 'nlb_ip': doc.get('nlb_ip'), 'port': doc.get('port'),
'started_at': doc.get('started_at'), 'finished_at': doc.get('finished_at'),
'passed': doc.get('passed'), 'attempts': len(doc.get('attempts') or []),
'propagation_s': propagation(doc, applied_at)})
- if len(addresses) == 2 and (addresses[0] == addresses[1] or None in addresses):
- reasons.append(f'the probe records must cover both NLB addresses; got {addresses[0]} and {addresses[1]}')
- return reasons, summaries
+ for address in sorted(set(public) - set(addresses)):
+ reasons.append(f'no probe record covers NLB address {address}; the records must cover both NLB addresses')
+ if len(addresses) != len(set(addresses)):
+ reasons.append(f'two probe records name the same address; the records must cover both NLB addresses')
+ window = (min(starts), max(finishes)) if starts and finishes else None
+ return reasons, summaries, window
def propagation(doc, applied_at):
"""Seconds from the apply to the start of the final run of matching attempts."""
- attempts = doc.get('attempts') or []
start = None
- for attempt in attempts:
+ for attempt in doc.get('attempts') or []:
if attempt.get('verdict') == 'match':
start = start or attempt
else:
start = None
- try:
- return round((parse_time(start['at']) - applied_at).total_seconds(), 3) if start else None
- except (KeyError, TypeError, ValueError):
- return None
+ t = epoch(start.get('at')) if start else None
+ return round(t - applied_at, 3) if t is not None and applied_at is not None else None
+
+
+def coverage_reasons(times, window, gap, what):
+ """The observations in times must start before the window, end after it, and
+ (with gap) never leave more than gap seconds unobserved inside it."""
+ if window is None:
+ return []
+ start, end = window
+ times = sorted(times)
+ before = [t for t in times if t <= start]
+ after = [t for t in times if t >= end]
+ reasons = []
+ if not before:
+ reasons.append(f'{what} was not observed before the earliest probe started ({iso(start)})')
+ if not after:
+ reasons.append(f'{what} was not observed after the latest probe finished ({iso(end)})')
+ if gap is not None and before and after:
+ span = [t for t in times if before[-1] <= t <= after[0]]
+ for a, b in zip(span, span[1:]):
+ if b - a > gap:
+ reasons.append(f'{what} was not observed for {b - a:.0f} s, from {iso(a)} to {iso(b)} '
+ f'(at most {gap:g} s allowed)')
+ return reasons
-def trust_findings(poll, baseline, targets):
+def trust_findings(status, base, iid, step):
+ if isinstance(status, str):
+ return []
reasons = []
- for iid in targets:
- status, base = poll.get(iid), baseline.get(iid)
- if isinstance(status, str) or status is None:
- reasons.append(status or f'{iid}: no trust-status')
- continue
- if not status['armed']:
- reasons.append(f'{iid} is not armed')
- if status['barrier']:
- reasons.append(f'{iid}: barrier is up')
- if not isinstance(base, dict) or 'counters' not in base:
- reasons.append(f'{iid}: the apply recorded no baseline')
- continue
- for counter in STILL:
- if status['counters'][counter] != base['counters'][counter]:
- reasons.append(f"{iid}: {counter} moved from {base['counters'][counter]} to {status['counters'][counter]}")
+ if not status['armed']:
+ reasons.append(f'{iid} is not armed')
+ if status['barrier'] and step.startswith('B'):
+ reasons.append(f'{iid}: barrier is up')
+ if not isinstance(base, dict):
+ return reasons + [f'{iid}: the apply recorded no baseline ({base})']
+ for counter in COUNTERS:
+ if status['counters'][counter] < base['counters'][counter]:
+ reasons.append(f"{iid}: {counter} fell from {base['counters'][counter]} to {status['counters'][counter]}: "
+ 'the edge restarted during the step')
+ for counter in STILL:
+ if status['counters'][counter] > base['counters'][counter]:
+ reasons.append(f"{iid}: {counter} moved from {base['counters'][counter]} to {status['counters'][counter]}")
return reasons
-def cmd_converge(args, cloud, clock=time.monotonic, sleep=time.sleep):
+def evaluate(step, applied, polls, docs, prereq, prior):
+ """(reasons, summary): the whole verdict, from the apply, every poll and the probe records."""
+ reasons = []
+ if prior and prior.get('applied_at') == applied['applied_at'] and prior.get('passed') is False:
+ reasons.extend(r if r.startswith('earlier run: ') else f'earlier run: {r}' for r in prior.get('reasons') or [])
+ targets, baseline = applied['targets'], applied.get('baseline') or {}
+ if set(baseline) != set(targets):
+ reasons.append(f'the apply recorded baselines for {", ".join(sorted(baseline))}, not {", ".join(targets)}')
+ probe_reasons, probes, window = probe_findings(docs, applied, step, prereq['public_addresses'])
+ reasons.extend(probe_reasons)
+ health = [p for p in polls if p['kind'] == 'health']
+ trust = [p for p in polls if p['kind'] == 'trust']
+ states = [p for p in polls if p['kind'] == 'state']
+ for poll in health:
+ if 'health' in poll:
+ reasons.extend(f"health poll at {poll['at']}: {r}" for r in registered_refusals(poll['health'], targets))
+ reasons.extend(coverage_reasons([epoch(p['at']) for p in health if 'health' in p], window, HEALTH_GAP_MAX, 'target health'))
+ for poll in trust:
+ for iid in targets:
+ for r in trust_findings(poll['status'].get(iid, ''), baseline.get(iid), iid, step):
+ reasons.append(f"trust poll at {poll['at']}: {r}")
+ complete = [p for p in trust if all(isinstance(p['status'].get(i), dict) for i in targets)]
+ trust_times = [epoch(p['at']) for p in complete]
+ if all(isinstance(baseline.get(i), dict) for i in targets) and applied.get('baseline_at'):
+ trust_times.append(epoch(applied['baseline_at']))
+ reasons.extend(coverage_reasons(trust_times, window, None, 'trust-status on every target'))
+ final = max(trust, key=lambda p: p['at']) if trust else None
+ if final is None:
+ reasons.append('no trust-status poll was made')
+ else:
+ reasons.extend(f'final trust poll: {s}' for s in final['status'].values() if isinstance(s, str))
+ if step.startswith('B') and final is not None:
+ for iid in targets:
+ status, base = final['status'].get(iid), baseline.get(iid)
+ if not isinstance(status, dict) or not isinstance(base, dict):
+ continue
+ for node in prereq['sources']:
+ was, now = base['proxied_by_node'].get(node, 0), status['proxied_by_node'].get(node, 0)
+ if now <= was:
+ reasons.append(f'{iid}: proxied from node {node} did not rise ({was} to {now})')
+ last_state = max(states, key=lambda p: p['at']) if states else None
+ if last_state is None or 'state' not in last_state:
+ reasons.append(f"the target group's state was not read: {(last_state or {}).get('error')}")
+ elif last_state['state'] != STEPS[step].target:
+ reasons.append(f"the target group is in {last_state['state']}, not {STEPS[step].target}")
+ unique = list(dict.fromkeys(reasons))
+ summary = {'probes': probes, 'health_polls': len(health), 'trust_polls': len(trust),
+ 'window': [iso(window[0]), iso(window[1])] if window else None}
+ return unique, summary
+
+
+def cmd_converge(args, cloud):
record_dir = Path(args.record_dir)
paths = split(args.probe_records)
- if len(paths) != 2:
- raise Refused('converge needs exactly two probe records, one per NLB address')
- targets = split(args.targets)
- applied = load_record(record_dir / f'{args.step}-applied.json')
- if applied is None:
- raise Refused(f'no {args.step}-applied.json in {record_dir}; run apply first')
- if applied.get('step') != args.step or applied.get('tg_arn') != args.tg_arn:
- raise Refused(f'{args.step}-applied.json is for {applied.get("step")} on {applied.get("tg_arn")}')
- baseline = applied.get('baseline') or {}
- health_polls, trust_polls, reasons = [], [], []
-
- def poll_health():
- at = now_iso()
- try:
- health = cloud.health(args.tg_arn)
- bad = registered_refusals(health, targets)
- except Refused as err:
- health, bad = {}, [str(err)]
- health_polls.append({'at': at, 'health': health})
- reasons.extend(f'health poll at {at}: {r}' for r in bad)
-
- def poll_trust():
- at = now_iso()
- try:
- poll = cloud.trust(targets)
- except Refused as err:
- poll = {t: str(err) for t in targets}
- trust_polls.append({'at': at, 'status': poll})
- reasons.extend(f'trust poll at {at}: {r}' for r in trust_findings(poll, baseline, targets))
- return poll
-
- def arrived():
- return all(Path(p).exists() for p in paths)
-
- deadline = clock() + args.timeout
- next_health = next_trust = clock()
- while True:
- if clock() >= next_health:
- poll_health()
- next_health = clock() + HEALTH_EVERY
- if clock() >= next_trust:
- poll_trust()
- next_trust = clock() + TRUST_EVERY
- if arrived() or clock() >= deadline:
- break
- sleep(1)
- # A last look at both, after the probes finished.
- poll_health()
- final = poll_trust()
- # The evidence is for the state the step made; the target group must still be in it.
- try:
- live = cloud.attributes(args.tg_arn)
- state = state_of(live['preserve_client_ip'], live['proxy_protocol_v2'])
- except Refused as err:
- state = None
- reasons.append(str(err))
- if state is not None and state != STEPS[args.step].target:
- reasons.append(f'the target group is in {state}, not {STEPS[args.step].target}')
- probe_reasons, probes = probe_findings(paths, applied, args.step)
- reasons.extend(probe_reasons)
- if args.step.startswith('B'):
- prereq = load_record(record_dir / 'prereq.json')
- nodes = (prereq or {}).get('sources')
- if not prereq or prereq.get('nlb_arn') != applied.get('nlb_arn') or not nodes:
- reasons.append('prereq.json for this load balancer, naming its node addresses, is needed to check proxied rose')
- else:
- for iid in targets:
- status, base = final.get(iid), baseline.get(iid)
- if not isinstance(status, dict) or not isinstance(base, dict):
- continue
- for node in nodes:
- was, now = base.get('proxied_by_node', {}).get(node, 0), status['proxied_by_node'].get(node, 0)
- if now <= was:
- reasons.append(f'{iid}: proxied from node {node} did not rise ({was} to {now})')
- passed = not reasons
- write_record(record_dir / f'{args.step}.json', {
- 'nlb_arn': applied.get('nlb_arn'), 'port': applied.get('port'), 'step': args.step,
- 'tg_arn': args.tg_arn, 'applied_at': applied.get('applied_at'), 'converged_at': now_iso(),
- 'state': state, 'passed': passed, 'reasons': reasons, 'probes': probes, 'targets': targets,
- 'health_polls': health_polls, 'trust_polls': trust_polls})
- if passed:
- print(f'{args.step} converged; {args.step}.json passed')
- return 0
- for reason in reasons:
- print(f'not converged: {reason}', file=sys.stderr)
- return 1
+ targets = target_list(args.targets)
+ with locked(record_dir):
+ applied = load_record(record_dir / f'{args.step}-applied.json')
+ if applied is None:
+ raise Refused(f'no {args.step}-applied.json in {record_dir}; run apply first')
+ if applied.get('step') != args.step or applied.get('tg_arn') != args.tg_arn:
+ raise Refused(f'{args.step}-applied.json is for {applied.get("step")} on {applied.get("tg_arn")}')
+ if sorted(targets) != sorted(applied.get('targets') or []):
+ raise Refused(f"--targets must be the apply's targets ({', '.join(applied.get('targets') or [])}); "
+ 'a target cannot leave a step before it converges')
+ return converge(cloud, record_dir, applied, paths, args.timeout)
def cmd_prereq(args, cloud):
record_dir = Path(args.record_dir)
if not record_dir.is_dir():
raise Refused(f'--record-dir {record_dir} is not a directory')
- targets = split(args.targets)
+ targets = target_list(args.targets)
sources = sorted(split(args.sources))
- reasons, groups = [], {}
- for port, tg_arn in (('80', args.tg_arn_80), ('443', args.tg_arn_443)):
- try:
- cloud.target_group(tg_arn, args.nlb_arn, port)
- live = cloud.attributes(tg_arn)
- state = state_of(live['preserve_client_ip'], live['proxy_protocol_v2'])
- groups[port] = {'tg_arn': tg_arn, 'state': state}
- if state != 'S0':
- reasons.append(f'target group {tg_arn} is in {state}, not S0')
- reasons.extend(f'{tg_arn}: {r}' for r in registered_refusals(cloud.health(tg_arn), targets))
- except Refused as err:
- reasons.append(str(err))
- status = cloud.trust(targets)
- for iid in targets:
- s = status[iid]
- if isinstance(s, str):
- reasons.append(s)
- elif not s['armed']:
- reasons.append(f'{iid} is not armed')
- elif s['barrier']:
- reasons.append(f'the trust barrier is up on {iid}')
- lines = {}
- for iid, (code, stdout, _) in cloud.ssm(targets, JOURNAL).items():
- match = ARMED_RE.search(stdout or '')
- lines[iid] = stdout.strip()
- if code != 0 or not match:
- reasons.append(f'{iid}: no armed line in the carlos-edge journal')
- elif sorted(match.group(1).split(',')) != sources:
- reasons.append(f"{iid} trusts {match.group(1)}, not {','.join(sources)}")
- alarms = cloud.aws('cloudwatch', 'describe-alarms', '--alarm-names', args.alarm).get('MetricAlarms') or []
- alarm = [a for a in alarms if a.get('AlarmName') == args.alarm]
- if not alarm:
- reasons.append(f'alarm {args.alarm} not found')
- elif alarm[0].get('StateValue') != 'OK':
- reasons.append(f"alarm {args.alarm} is {alarm[0].get('StateValue')}, not OK")
- passed = not reasons
- write_record(record_dir / 'prereq.json', {
- 'nlb_arn': args.nlb_arn, 'sources': sources, 'targets': targets, 'target_groups': groups,
- 'alarm': args.alarm, 'checked_at': now_iso(), 'passed': passed, 'reasons': reasons,
- 'trust_status': status, 'armed_lines': lines})
+ with locked(record_dir):
+ reasons, groups = [], {}
+ nodes = cloud.interfaces(args.nlb_arn)
+ private = sorted(p for p, _ in nodes if p)
+ public = sorted(a for _, a in nodes if a)
+ if not nodes:
+ reasons.append(f'no network interfaces found for {args.nlb_arn}')
+ if any(a is None for _, a in nodes):
+ reasons.append('an NLB interface has no public address; the probes need one per node')
+ if sources != private:
+ reasons.append(f"--sources {','.join(sources)} are not the NLB's node addresses ({','.join(private)})")
+ for port, tg_arn in (('80', args.tg_arn_80), ('443', args.tg_arn_443)):
+ try:
+ cloud.target_group(tg_arn, args.nlb_arn, port)
+ live = cloud.attributes(tg_arn)
+ state = state_of(live['preserve_client_ip'], live['proxy_protocol_v2'])
+ groups[port] = {'tg_arn': tg_arn, 'state': state}
+ if state != 'S0':
+ reasons.append(f'target group {tg_arn} is in {state}, not S0')
+ reasons.extend(f'{tg_arn}: {r}' for r in registered_refusals(cloud.health(tg_arn), targets))
+ except Refused as err:
+ reasons.append(str(err))
+ status = cloud.trust(targets)
+ for iid in targets:
+ s = status[iid]
+ if isinstance(s, str):
+ reasons.append(s)
+ elif not s['armed']:
+ reasons.append(f'{iid} is not armed')
+ elif s['barrier']:
+ reasons.append(f'the trust barrier is up on {iid}')
+ lines = {}
+ for iid, (code, stdout, _) in cloud.ssm(targets, JOURNAL).items():
+ match = ARMED_RE.search(stdout or '')
+ lines[iid] = stdout.strip()
+ if code != 0 or not match:
+ reasons.append(f'{iid}: no armed line in the carlos-edge journal')
+ elif sorted(match.group(1).split(',')) != private:
+ reasons.append(f"{iid} trusts {match.group(1)}, not the NLB's node addresses {','.join(private)}")
+ alarms = cloud.aws('cloudwatch', 'describe-alarms', '--alarm-names', args.alarm).get('MetricAlarms') or []
+ alarm = [a for a in alarms if a.get('AlarmName') == args.alarm]
+ if not alarm:
+ reasons.append(f'alarm {args.alarm} not found')
+ elif alarm[0].get('StateValue') != 'OK':
+ reasons.append(f"alarm {args.alarm} is {alarm[0].get('StateValue')}, not OK")
+ passed = not reasons
+ write_record(record_dir / 'prereq.json', {
+ 'nlb_arn': args.nlb_arn, 'sources': sources, 'public_addresses': public,
+ 'interfaces': [{'private': p, 'public': a} for p, a in nodes], 'targets': targets,
+ 'target_groups': groups, 'alarm': args.alarm, 'checked_at': iso(cloud.clock.time()), 'passed': passed,
+ 'automated_checks_only': True, 'manual_prerequisites_owed': list(MANUAL_PREREQUISITES),
+ 'reasons': reasons, 'trust_status': status, 'armed_lines': lines})
+ owed = '; '.join(MANUAL_PREREQUISITES)
if passed:
- print('prerequisites hold; prereq.json passed')
+ print(f'automated prerequisite checks passed (automated checks only); prereq.json written. '
+ f'Still owed, checked by hand before A80: {owed}')
return 0
for reason in reasons:
print(f'refused: {reason}', file=sys.stderr)
+ print(f'(automated checks only; also owed by hand: {owed})', file=sys.stderr)
return 1
def parser():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = p.add_subparsers(dest='command', required=True)
- a = sub.add_parser('apply', help='make one step on one target group')
+ a = sub.add_parser('apply', help='make one step on one target group, then converge')
a.add_argument('--root', required=True, help='the tofu root directory holding ppv2.auto.tfvars.json')
a.add_argument('--nlb-arn', required=True)
a.add_argument('--tg-arn', required=True)
@@ -701,13 +1100,16 @@ def parser():
a.add_argument('--port', required=True, choices=['80', '443'])
a.add_argument('--step', required=True, choices=list(STEPS))
a.add_argument('--record-dir', required=True)
- c = sub.add_parser('converge', help='gather convergence evidence after apply')
+ a.add_argument('--probe-records', help='one probe record path per NLB address, comma-separated '
+ '(required for forward steps; for R steps, converge only when given)')
+ c = sub.add_parser('converge', help='resume the convergence of the latest apply of a step')
c.add_argument('--step', required=True, choices=list(STEPS))
c.add_argument('--record-dir', required=True)
- c.add_argument('--probe-records', required=True, help='two probe record paths, comma-separated')
+ c.add_argument('--probe-records', required=True, help='one probe record path per NLB address, comma-separated')
c.add_argument('--tg-arn', required=True)
- c.add_argument('--timeout', type=float, default=1800.0, help='seconds to wait for the probe records')
- r = sub.add_parser('prereq', help='check the prerequisites and write prereq.json')
+ for s in (a, c):
+ s.add_argument('--timeout', type=float, default=1800.0, help='seconds to wait for the probe records')
+ r = sub.add_parser('prereq', help='the automated prerequisite checks; writes prereq.json')
r.add_argument('--nlb-arn', required=True)
r.add_argument('--tg-arn-80', required=True)
r.add_argument('--tg-arn-443', required=True)
@@ -723,6 +1125,8 @@ def parser():
def main(argv=None):
args = parser().parse_args(argv)
+ for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
+ signal.signal(sig, on_signal)
cloud = Cloud(args.profile, args.region)
try:
if args.command == 'apply':
@@ -731,7 +1135,13 @@ def main(argv=None):
return cmd_converge(args, cloud)
return cmd_prereq(args, cloud)
except Refused as err:
- print(f'refused: {err}', file=sys.stderr)
+ print(f'refused: {one_line(err)}', file=sys.stderr)
+ return 1
+ except Interrupted as err:
+ print(f'interrupted: {one_line(err)}', file=sys.stderr)
+ return 130
+ except Exception as err: # one line, never a traceback
+ print(f'error: {type(err).__name__}: {one_line(err)}', file=sys.stderr)
return 1
diff --git a/scripts/ppv2_probe_test.py b/scripts/ppv2_probe_test.py
index 75d8684da..598cd2869 100644
--- a/scripts/ppv2_probe_test.py
+++ b/scripts/ppv2_probe_test.py
@@ -7,10 +7,13 @@ import importlib.util
import ipaddress
import json
from pathlib import Path
+import socket
import ssl
import struct
import subprocess
import sys
+import threading
+import time
import unittest
SCRIPT = Path(__file__).with_name('ppv2-probe.py')
@@ -130,6 +133,11 @@ class ProbeTests(unittest.TestCase):
verdict, reason = probe.judge(expect, 443, recorded('echo-200'), recorded('echo-forged-chain'), CLIENT)
self.assertEqual('fail', verdict)
self.assertIn('forged', reason)
+ # An echo in another format (JSON here) still fails as a forgery, not
+ # merely as a wrong client, so the S3 reason is kept.
+ verdict, reason = probe.judge(expect, 443, recorded('echo-200'), recorded('echo-forged-json'), CLIENT)
+ self.assertEqual('fail', verdict)
+ self.assertIn('forged', reason)
record, calls = run([('echo-200', 'tls-alert')] * 5 + [('echo-200', 'echo-forged')] + [('echo-200', 'tls-alert')] * 40)
self.assertFalse(record['passed'])
self.assertEqual(6, len(record['attempts']))
@@ -176,5 +184,73 @@ class ProbeTests(unittest.TestCase):
self.assertEqual(2, result.returncode)
+class ConnectorTests(unittest.TestCase):
+ """The socket layer against a server on 127.0.0.1 only (no other network)."""
+
+ def serve(self, handler, connections):
+ srv = socket.socket()
+ srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ srv.bind(('127.0.0.1', 0))
+ srv.listen(8)
+ self.addCleanup(srv.close)
+ seen = []
+
+ def loop():
+ for _ in range(connections):
+ conn, peer = srv.accept()
+ with conn:
+ data = b''
+ # The header and request may come in two reads, and the PPv2
+ # signature itself starts with a blank line: read to the request's end.
+ while not (b'GET ' in data and data.endswith(b'\r\n\r\n')):
+ chunk = conn.recv(4096)
+ if not chunk:
+ break
+ data += chunk
+ seen.append((peer[1], data))
+ handler(conn, data)
+ thread = threading.Thread(target=loop, daemon=True)
+ thread.start()
+ return srv.getsockname()[1], seen, thread
+
+ def test_marker_first_and_ports_from_range(self):
+ def answer(conn, data):
+ if data.startswith(probe.SIGNATURE):
+ conn.sendall(b'HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n400 Bad Request')
+ else:
+ conn.sendall(b'HTTP/1.1 302 Found\r\nLocation: https://echo.example.com/xff\r\nContent-Length: 0\r\n\r\n')
+ port, seen, thread = self.serve(answer, 2)
+ lo = 47100
+ connector = probe.Connector('127.0.0.1', port, 'echo.example.com', '/xff', (lo, lo + 63))
+ plain, marker = connector.attempt()
+ thread.join(5)
+ self.assertEqual(('answer', 302), (plain['kind'], plain['status']))
+ self.assertEqual(("answer", 400), (marker["kind"], marker.get("status")), marker)
+ (plain_port, plain_bytes), (marker_port, marker_bytes) = seen
+ self.assertTrue(lo <= plain_port <= lo + 63 and lo <= marker_port <= lo + 63, seen)
+ self.assertNotEqual(plain_port, marker_port)
+ self.assertTrue(plain_bytes.startswith(b'GET /xff HTTP/1.1\r\nHost: echo.example.com\r\n'))
+ self.assertEqual(probe.marker_header('127.0.0.1', port, marker_port), marker_bytes[:28])
+ self.assertEqual(plain_bytes, marker_bytes[28:])
+
+ def test_dripping_peer_is_cut_off(self):
+ def drip(conn, data):
+ conn.sendall(b'HTTP/1.1 200 OK\r\n')
+ try:
+ for _ in range(50):
+ time.sleep(0.1)
+ conn.sendall(b'X')
+ except OSError:
+ pass
+ port, seen, thread = self.serve(drip, 1)
+ connector = probe.Connector('127.0.0.1', port, 'echo.example.com', '/xff', (47200, 47263))
+ old, probe.EXCHANGE_BOUND = probe.EXCHANGE_BOUND, 1.0
+ self.addCleanup(setattr, probe, 'EXCHANGE_BOUND', old)
+ began = time.monotonic()
+ outcome = connector.exchange(False)
+ self.assertLess(time.monotonic() - began, 3.0)
+ self.assertNotEqual(200, outcome.get('status'))
+
+
if __name__ == '__main__':
unittest.main()
diff --git a/scripts/ppv2_step_test.py b/scripts/ppv2_step_test.py
index 1203b194f..936b7b903 100644
--- a/scripts/ppv2_step_test.py
+++ b/scripts/ppv2_step_test.py
@@ -1,39 +1,52 @@
"""Tests for scripts/ppv2-step.py, the PPv2 cutover step gate (edge PPv2 spec 6.2-6.4).
-Every AWS and tofu call goes to fake `aws` and `tofu` executables on PATH that
-answer from a JSON world file and log their argv; nothing reaches AWS or tofu.
+Two harnesses, neither reaching AWS or tofu:
+- the script as a subprocess, with fake `aws` and `tofu` executables on PATH
+ that answer from a JSON world file and log their argv;
+- convergence in-process, with a fake clock and a fake cloud, so the 10 s and
+ 30 s schedules, slow SSM and late probe records are exercised exactly.
Run from the repo root: python3 -m unittest scripts/ppv2_step_test.py
"""
+import contextlib
import copy
+import fcntl
import importlib.util
+import io
import json
import os
from pathlib import Path
+import signal
import subprocess
import sys
import tempfile
+import threading
+import time
import unittest
SCRIPT = Path(__file__).with_name('ppv2-step.py')
DATA = Path(__file__).parent / 'testdata' / 'ppv2'
NLB = 'arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/carlos-dev-ie/0123456789abcdef'
+NLB_SUFFIX = 'net/carlos-dev-ie/0123456789abcdef'
OTHER_NLB = 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/carlos-dev-us/fedcba9876543210'
TG = {'80': 'arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/carlos-dev-ie-80/1111111111111111',
'443': 'arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/carlos-dev-ie-443/2222222222222222'}
ADDR = {port: f'module.ingress_ie.aws_lb_target_group.target["{port}"]' for port in TG}
TARGETS = ['i-0aaaaaaaaaaaaaaa1', 'i-0bbbbbbbbbbbbbbb2']
SOURCES = ['172.31.11.189', '172.31.29.110']
+PUBLIC = ['54.77.110.223', '54.77.110.224']
+INTERFACES = [{'private': SOURCES[0], 'public': PUBLIC[0]}, {'private': SOURCES[1], 'public': PUBLIC[1]}]
ALARM = 'carlos-dev-ie-proxy-trust'
APPLIED_AT = '2026-11-12T10:00:00.000000Z'
STATES = {'S0': ('true', 'false'), 'S1': ('true', 'true'), 'S2': ('false', 'true'), 'S3': ('false', 'false')}
+EXPECT = {'A': 's1', 'B': 's2', 'R': 's1'}
# The tfvars file as an operator might have formatted it: the restore must
# give these exact bytes back, not a re-serialisation.
TFVARS = (b'{ "ppv2_preserve_client_ip": {"80": true, "443": true},\n'
b' "ppv2_proxy_protocol_v2": {"80": false, "443": false} }\n')
FAKE = r'''
-import json, os, sys
+import json, os, sys, time
from pathlib import Path
name = Path(sys.argv[0]).name
@@ -43,6 +56,7 @@ world = json.loads(world_path.read_text())
seq_path = world_path.with_suffix('.seq')
seq = json.loads(seq_path.read_text()) if seq_path.exists() else {}
entry = {'cli': name, 'args': args}
+MARK = '----------ERROR-------'
def save():
seq_path.write_text(json.dumps(seq))
@@ -65,14 +79,27 @@ def many(flag):
out.append(a)
return out
-def done(code=0, out=None, err=''):
+def log():
with open(os.environ['PPV2_FAKE_CALLS'], 'a') as f:
f.write(json.dumps(entry) + '\n')
+
+def done(code=0, out=None, err=''):
+ log()
if out is not None:
sys.stdout.write(out if isinstance(out, str) else json.dumps(out))
sys.stderr.write(err)
sys.exit(code)
+def invocation(iid, text):
+ if 'trust-status' in text:
+ sample = nxt('trust:' + iid, world['trust'][iid])
+ if 'rc' in sample:
+ return [iid, 'Failed', sample['rc'], '\n' + MARK + '\n' + sample['stderr']]
+ return [iid, 'Success', 0, json.dumps(sample) + '\n']
+ if 'journalctl' in text:
+ return [iid, 'Success', 0, world['journal'][iid] + '\n']
+ return [iid, 'Failed', 1, MARK + 'unknown command']
+
if name == 'aws':
i = 0
rest = []
@@ -97,32 +124,42 @@ if name == 'aws':
done(out={'TargetGroups': [dict(tg, TargetGroupArn=arn)]})
if op == 'describe-target-health':
arn = opt('--target-group-arn')
+ if world.get('health_malformed'):
+ done(out={'TargetHealthDescriptions': [{'Target': {}}]})
rows = nxt('health:' + arn, world['health'][arn])
done(out={'TargetHealthDescriptions': [
{'Target': {'Id': iid, 'Port': 80}, 'TargetHealth': {'State': state}} for iid, state in rows]})
+ if op == 'describe-network-interfaces':
+ want = json.loads(opt('--filters'))[0]['Values'][0]
+ rows = world['interfaces'] if want == 'ELB ' + world['nlb_suffix'] else []
+ done(out={'NetworkInterfaces': [dict({'PrivateIpAddress': r['private']},
+ **({'Association': {'PublicIp': r['public']}} if r.get('public') else {}))
+ for r in rows]})
if op == 'send-command':
+ if world.get('ssm_fail'):
+ done(255, err='An error occurred (InvalidInstanceId) when calling the SendCommand operation')
n = seq.get('commands', 0) + 1
seq['commands'] = n
cid = 'cmd-%d' % n
seq['text:' + cid] = json.loads(opt('--parameters'))['commands'][0]
+ seq['inst:' + cid] = many('--instance-ids')
save()
entry['instances'] = many('--instance-ids')
entry['document'] = opt('--document-name')
done(out={'Command': {'CommandId': cid}})
- if op == 'get-command-invocation':
- cid, iid = opt('--command-id'), opt('--instance-id')
+ if op == 'list-command-invocations':
+ cid = opt('--command-id')
text = seq['text:' + cid]
- if 'trust-status' in text:
- sample = nxt('trust:' + iid, world['trust'][iid])
- if 'rc' in sample:
- done(out={'Status': 'Failed', 'ResponseCode': sample['rc'],
- 'StandardOutputContent': '', 'StandardErrorContent': sample['stderr']})
- done(out={'Status': 'Success', 'ResponseCode': 0,
- 'StandardOutputContent': json.dumps(sample) + '\n', 'StandardErrorContent': ''})
- if 'journalctl' in text:
- done(out={'Status': 'Success', 'ResponseCode': 0,
- 'StandardOutputContent': world['journal'][iid] + '\n', 'StandardErrorContent': ''})
- done(1, err='unknown command ' + text)
+ rows = []
+ for iid in seq['inst:' + cid]:
+ key = 'res:%s:%s' % (cid, iid)
+ if key not in seq:
+ seq[key] = invocation(iid, text)
+ save()
+ iid, status, rc, output = seq[key]
+ rows.append({'InstanceId': iid, 'Status': status,
+ 'CommandPlugins': [{'Name': 'aws:runShellScript', 'ResponseCode': rc, 'Output': output}]})
+ done(out={'CommandInvocations': rows})
if op == 'describe-alarms':
names = many('--alarm-names')
done(out={'MetricAlarms': [{'AlarmName': n, 'StateValue': world['alarms'][n]}
@@ -145,10 +182,18 @@ if name == 'tofu':
entry['tfvars'] = (Path(chdir) / 'ppv2.auto.tfvars.json').read_text()
out = [a for a in args if a.startswith('-out=')][0][len('-out='):]
Path(chdir, out).write_text('fake plan')
+ if world.get('plan_sleep'):
+ log()
+ Path(world['plan_marker']).write_text('planning')
+ time.sleep(world['plan_sleep'])
+ sys.exit(0)
done(world.get('plan_rc', 0))
if args[:2] == ['show', '-json']:
done(out=world['plan'])
if args[0] == 'apply':
+ if world.get('on_apply') and not world.get('apply_rc'):
+ world['attributes'].update(world['on_apply'])
+ world_path.write_text(json.dumps(world))
done(world.get('apply_rc', 0))
done(1, err='fake tofu: unhandled ' + ' '.join(args))
'''
@@ -161,6 +206,9 @@ def load_script():
return module
+gate = load_script()
+
+
def trust(name):
return copy.deepcopy(json.loads((DATA / 'trust-status.json').read_text())[name])
@@ -190,6 +238,7 @@ STEP_PLAN = {
{'preserve_client_ip': 'true', 'proxy_protocol_v2': True}),
}
STEP_FROM = {'A80': 'S0', 'A443': 'S0', 'B80': 'S1', 'B443': 'S1', 'R80': 'S2', 'R443': 'S2'}
+STEP_TO = {'A80': 'S1', 'A443': 'S1', 'B80': 'S2', 'B443': 'S2', 'R80': 'S1', 'R443': 'S1'}
def plan_for_step(step):
@@ -212,6 +261,25 @@ def tfvars_for(states):
}) + '\n').encode()
+def attributes(state):
+ preserve, ppv2 = STATES[state]
+ return {'deregistration_delay.timeout_seconds': '30', 'preserve_client_ip.enabled': preserve,
+ 'proxy_protocol_v2.enabled': ppv2, 'stickiness.enabled': 'false'}
+
+
+def probe_doc(nlb_ip, port, expect, started, finished, passed=True):
+ attempts = [{'at': gate.iso(started + 2 * i), 'verdict': 'match'} for i in range(30)]
+ return {'nlb_ip': nlb_ip, 'port': int(port), 'expect': expect, 'started_at': gate.iso(started),
+ 'finished_at': gate.iso(finished), 'passed': passed, 'reason': None if passed else 'marker answered 200',
+ 'attempts': attempts}
+
+
+def write_prereq(records, nlb=NLB, passed=True):
+ (records / 'prereq.json').write_text(json.dumps({
+ 'nlb_arn': nlb, 'passed': passed, 'sources': SOURCES, 'public_addresses': PUBLIC, 'targets': TARGETS,
+ 'checked_at': '2026-11-12T09:00:00.000000Z', 'automated_checks_only': True}))
+
+
class Harness(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR'))
@@ -240,27 +308,33 @@ class Harness(unittest.TestCase):
'journal': {t: 'edge: proxy protocol: armed on :80 and :443, trusting 172.31.11.189,172.31.29.110, barrier down'
for t in TARGETS},
'alarms': {ALARM: 'OK'},
+ 'interfaces': copy.deepcopy(INTERFACES),
+ 'nlb_suffix': NLB_SUFFIX,
'state': {ADDR[p]: state_output(p) for p in TG},
'plan': None,
}
self.live({'80': 'S0', '443': 'S0'})
- def live(self, states):
+ def live(self, states, tfvars=True):
for port, state in states.items():
- preserve, ppv2 = STATES[state]
- self.world['attributes'][TG[port]] = {
- 'deregistration_delay.timeout_seconds': '30', 'preserve_client_ip.enabled': preserve,
- 'proxy_protocol_v2.enabled': ppv2, 'stickiness.enabled': 'false'}
- self.tfvars.write_bytes(tfvars_for(states))
+ self.world['attributes'][TG[port]] = attributes(state)
+ if tfvars:
+ current = {p: gate.state_of(self.world['attributes'][TG[p]]['preserve_client_ip.enabled'] == 'true',
+ self.world['attributes'][TG[p]]['proxy_protocol_v2.enabled'] == 'true')
+ for p in TG}
+ self.tfvars.write_bytes(tfvars_for(current))
- def run_step(self, *args, expect=None):
+ def env(self):
self.world_path.write_text(json.dumps(self.world))
- env = dict(os.environ, PATH=str(self.bin) + os.pathsep + os.environ['PATH'],
- PPV2_FAKE_WORLD=str(self.world_path), PPV2_FAKE_CALLS=str(self.calls_path))
- result = subprocess.run([sys.executable, str(SCRIPT), *args], env=env, text=True,
- capture_output=True, timeout=60, stdin=subprocess.DEVNULL)
+ return dict(os.environ, PATH=str(self.bin) + os.pathsep + os.environ['PATH'],
+ PPV2_FAKE_WORLD=str(self.world_path), PPV2_FAKE_CALLS=str(self.calls_path))
+
+ def run_step(self, *args, expect=None):
+ result = subprocess.run([sys.executable, str(SCRIPT), *args], env=self.env(), text=True,
+ capture_output=True, timeout=120, stdin=subprocess.DEVNULL)
if expect is not None:
self.assertEqual(expect, result.returncode, result.stdout + result.stderr)
+ self.assertNotIn('Traceback', result.stderr)
return result
def calls(self):
@@ -271,42 +345,77 @@ class Harness(unittest.TestCase):
def ops(self):
return [c.get('op') or ' '.join(c['args'][:2]) for c in self.calls()]
- def apply(self, step, port=None, expect=None, targets=None, nlb=NLB):
- port = port or STEP_PLAN[step][0]
- return self.run_step('apply', '--root', str(self.root), '--profile', 'kass', '--region', 'eu-west-1',
- '--nlb-arn', nlb, '--tg-arn', TG[port], '--tg-address', ADDR[port],
- '--port', port, '--step', step, '--targets', ','.join(targets or TARGETS),
- '--record-dir', str(self.records), expect=expect)
+ def apply_args(self, step, port=None, targets=None, nlb=NLB, probes=None, timeout='60'):
+ port = port or STEP_PLAN.get(step, ('80',))[0]
+ args = ['apply', '--root', str(self.root), '--profile', 'kass', '--region', 'eu-west-1',
+ '--nlb-arn', nlb, '--tg-arn', TG[port], '--tg-address', ADDR[port],
+ '--port', port, '--step', step, '--targets', ','.join(targets or TARGETS),
+ '--record-dir', str(self.records), '--timeout', timeout]
+ if probes is None:
+ probes = not step.startswith('R')
+ if probes:
+ args += ['--probe-records', ','.join(str(self.probes / n) for n in ('a.json', 'b.json'))]
+ return args
+
+ def apply(self, step, expect=None, **kw):
+ return self.run_step(*self.apply_args(step, **kw), expect=expect)
+
+ def apply_converging(self, step, expect=0, **kw):
+ """apply, with both probes started once the apply is in, as an operator would."""
+ port = STEP_PLAN[step][0]
+ applied = self.records / f'{step}-applied.json'
+ stop = threading.Event()
+
+ def writer():
+ while not applied.exists():
+ if stop.wait(0.02):
+ return
+ start = time.time() + 1.0
+ for name, ip in zip(('a.json', 'b.json'), PUBLIC):
+ (self.probes / name).write_text(json.dumps(probe_doc(ip, port, EXPECT[step[0]], start, start + 0.2)))
+ thread = threading.Thread(target=writer)
+ thread.start()
+ try:
+ return self.apply(step, expect=expect, probes=True, **kw)
+ finally:
+ stop.set()
+ thread.join()
def record(self, name, **values):
- doc = dict(values)
- (self.records / (name + '.json')).write_text(json.dumps(doc))
+ (self.records / (name + '.json')).write_text(json.dumps(values))
def prereq(self, nlb=NLB, passed=True):
- self.record('prereq', nlb_arn=nlb, passed=passed, sources=SOURCES, targets=TARGETS,
- checked_at='2026-11-12T09:00:00.000000Z')
+ write_prereq(self.records, nlb, passed)
def converged(self, step, nlb=NLB, passed=True, applied_at=APPLIED_AT):
port = STEP_PLAN[step][0]
self.record(step + '-applied', nlb_arn=nlb, port=port, step=step, applied_at=applied_at,
- tg_arn=TG[port], baseline={})
+ tg_arn=TG[port], baseline={}, targets=TARGETS)
self.record(step, nlb_arn=nlb, port=port, step=step, applied_at=applied_at, passed=passed)
def assert_refused(self, result, text):
self.assertEqual(1, result.returncode, result.stdout + result.stderr)
self.assertIn(text, result.stderr)
+ def tofu_ops(self):
+ return [c['args'][0] for c in self.calls() if c['cli'] == 'tofu']
+
def assert_not_changed(self, original):
self.assertEqual(original, self.tfvars.read_bytes())
- self.assertNotIn('apply', [c['args'][0] for c in self.calls() if c['cli'] == 'tofu'])
+ self.assertNotIn('apply', self.tofu_ops())
def ready_for(self, step):
- """World and records in which `step` is allowed."""
+ """World and records in which `step` is allowed and converges."""
port = STEP_PLAN[step][0]
other = '443' if port == '80' else '80'
before = {'A80': 'S0', 'A443': 'S1', 'B80': 'S1', 'B443': 'S2', 'R443': 'S2', 'R80': 'S1'}[step]
self.live({port: STEP_FROM[step], other: before})
self.world['plan'] = plan_for_step(step)
+ self.world['on_apply'] = {TG[port]: attributes(STEP_TO[step])}
+ if step.startswith('B'):
+ self.world['trust'] = {t: [trust('before_b'), trust('b_both_nodes')] for t in TARGETS}
+ else:
+ self.world['trust'] = {t: [trust('baseline'), trust('after_a')] for t in TARGETS}
self.prereq()
for pred in {'A443': ['A80'], 'B80': ['A80', 'A443'], 'B443': ['A80', 'A443', 'B80']}.get(step, []):
self.converged(pred)
@@ -314,14 +423,16 @@ class Harness(unittest.TestCase):
class StepGateTests(Harness):
def test_allowed_moves(self):
- gate = load_script()
self.assertEqual({('S0', 'S1'), ('S1', 'S2'), ('S2', 'S1')}, set(gate.ALLOWED))
for step in ('A80', 'A443', 'B80', 'B443', 'R443', 'R80'):
with self.subTest(step=step):
self.setUp()
self.ready_for(step)
original = self.tfvars.read_bytes()
- result = self.apply(step, expect=0)
+ if step.startswith('R'):
+ result = self.apply(step, expect=0)
+ else:
+ result = self.apply_converging(step)
port, attribute = STEP_PLAN[step][:2]
# Exactly one key moved in the file, the plan saw it, and the saved plan was applied.
before, after = json.loads(original), json.loads(self.tfvars.read_text())
@@ -337,14 +448,20 @@ class StepGateTests(Harness):
self.assertEqual(1, len(applies))
planfile = [a for a in plans[0]['args'] if a.startswith('-out=')][0][len('-out='):]
self.assertEqual(planfile, applies[0]['args'][-1])
+ self.assertFalse((self.root / planfile).exists())
record = json.loads((self.records / (step + '-applied.json')).read_text())
- self.assertEqual((NLB, port, step, TG[port]),
- (record['nlb_arn'], record['port'], record['step'], record['tg_arn']))
- self.assertIn('applied_at', record)
+ self.assertEqual((NLB, port, step, TG[port], TARGETS),
+ (record['nlb_arn'], record['port'], record['step'], record['tg_arn'], record['targets']))
self.assertEqual(sorted(TARGETS), sorted(record['baseline']))
- self.assertEqual(trust('baseline'), record['baseline'][TARGETS[0]])
+ intent = json.loads((self.records / (step + '-intent.json')).read_text())
+ self.assertEqual(intent['started_at'], record['intent_started_at'])
self.assertIn('applied', result.stdout)
- # Every aws call named the profile and region.
+ if not step.startswith('R'):
+ # apply went straight on into convergence (spec 6.3) and wrote the evidence.
+ converged = json.loads((self.records / (step + '.json')).read_text())
+ self.assertTrue(converged['passed'], converged['reasons'])
+ self.assertEqual(record['applied_at'], converged['applied_at'])
+ self.assertEqual(sorted(PUBLIC), sorted(p['nlb_ip'] for p in converged['probes']))
for call in self.calls():
if call['cli'] == 'aws':
self.assertEqual(('kass', 'eu-west-1'), (call['profile'], call['region']))
@@ -354,14 +471,12 @@ class StepGateTests(Harness):
self.assertEqual(sorted(TARGETS), sorted(sent[0]['instances']))
def test_refused_moves(self):
- gate = load_script()
for current, target in [('S0', 'S2'), ('S2', 'S0'), ('S1', 'S0'), ('S3', 'S0'), ('S3', 'S1'),
('S3', 'S2'), ('S0', 'S3'), ('S1', 'S3'), ('S2', 'S3'), ('S0', 'S0')]:
with self.subTest(move=(current, target)):
self.assertIsNotNone(gate.move_refusal(current, target))
for current, target in gate.ALLOWED:
self.assertIsNone(gate.move_refusal(current, target))
- # Through the script: each step from a state it must not leave that way.
cases = [
('B80', 'S0', 'S0 to S3'), # preservation off with PPv2 off: S3
('R80', 'S1', 'no change'), # nothing to do; never a way to S0
@@ -379,54 +494,53 @@ class StepGateTests(Harness):
original = self.tfvars.read_bytes()
self.assert_refused(self.apply(step), text)
self.assert_not_changed(original)
- self.assertNotIn('plan', [c['args'][0] for c in self.calls() if c['cli'] == 'tofu'])
- # A step for one port refused against the other port's target group.
+ self.assertNotIn('plan', self.tofu_ops())
self.setUp()
self.ready_for('A80')
- result = self.run_step('apply', '--root', str(self.root), '--profile', 'kass', '--region', 'eu-west-1',
- '--nlb-arn', NLB, '--tg-arn', TG['443'], '--tg-address', ADDR['443'],
- '--port', '443', '--step', 'A80', '--targets', ','.join(TARGETS),
- '--record-dir', str(self.records))
- self.assert_refused(result, 'step A80 is for port 80')
+ args = self.apply_args('A80', port='443')
+ self.assert_refused(self.run_step(*args), 'step A80 is for port 80')
# No step turns PPv2 off: the choices stop at argparse.
- self.assertEqual(2, self.apply('X80', port='80').returncode)
+ self.assertEqual(2, subprocess.run([sys.executable, str(SCRIPT), *self.apply_args('X80', port='80')],
+ capture_output=True).returncode)
for step, (port, attribute, before, after) in STEP_PLAN.items():
- self.assertFalse(after['proxy_protocol_v2'] is False and attribute == 'proxy_protocol_v2')
+ self.assertTrue(after['proxy_protocol_v2'])
self.assertEqual(attribute, gate.STEPS[step].attribute)
def test_predecessor_map(self):
- gate = load_script()
self.assertEqual({'A80': 'prereq', 'A443': 'A80', 'B80': 'A443', 'B443': 'B80', 'R443': None, 'R80': None},
gate.PREDECESSOR)
- for step, pred in [('A80', 'prereq'), ('A443', 'A80'), ('B80', 'A443'), ('B443', 'B80')]:
+ # (step, faulted record): the immediate predecessor, and further back down
+ # the chain: B80 needs its own port's A80, B443 its own port's A443.
+ for step, pred in [('A80', 'prereq'), ('A443', 'A80'), ('B80', 'A443'), ('B443', 'B80'),
+ ('B80', 'A80'), ('B443', 'A443'), ('B443', 'prereq')]:
for fault in ('missing', 'not passed', 'other NLB', 'stale'):
if pred == 'prereq' and fault == 'stale':
continue
- with self.subTest(step=step, fault=fault):
+ with self.subTest(step=step, record=pred, fault=fault):
self.setUp()
self.ready_for(step)
original = self.tfvars.read_bytes()
path = self.records / (pred + '.json')
if fault == 'missing':
path.unlink()
- text = pred + '.json'
+ text = pred + '.json is missing'
elif fault == 'not passed':
doc = json.loads(path.read_text())
doc['passed'] = False
path.write_text(json.dumps(doc))
- text = 'did not pass'
+ text = pred + '.json did not pass'
elif fault == 'other NLB':
doc = json.loads(path.read_text())
doc['nlb_arn'] = OTHER_NLB
path.write_text(json.dumps(doc))
text = 'another load balancer'
else:
- # A later apply of the predecessor that has not converged yet.
+ # A later apply of that step whose convergence is not in.
applied = self.records / (pred + '-applied.json')
doc = json.loads(applied.read_text())
doc['applied_at'] = '2026-11-12T11:00:00.000000Z'
applied.write_text(json.dumps(doc))
- text = 'not for its latest apply'
+ text = pred + '.json is not for its latest apply'
self.assert_refused(self.apply(step), text)
self.assert_not_changed(original)
self.assertNotIn('ssm send-command', self.ops())
@@ -470,14 +584,12 @@ class StepGateTests(Harness):
self.assert_not_changed(original)
# Checked before anything else: no AWS call at all.
self.assertEqual([], [c for c in self.calls() if c['cli'] == 'aws'])
- # The target group must belong to the named load balancer and port.
self.setUp()
self.ready_for('A80')
self.world['target_groups'][TG['80']]['LoadBalancerArns'] = [OTHER_NLB]
self.assert_refused(self.apply('A80'), 'not attached to')
def test_plan_must_change_one_attribute(self):
- gate = load_script()
good = plan_for_step('A80')
self.assertIsNone(gate.plan_refusal(good, ADDR['80'], 'proxy_protocol_v2', False, True))
two_attributes = copy.deepcopy(good)
@@ -499,6 +611,10 @@ class StepGateTests(Harness):
other_attribute['resource_changes'][0]['address'] = ADDR['80']
nothing = copy.deepcopy(good)
nothing['resource_changes'] = [good['resource_changes'][1]]
+ errored = copy.deepcopy(good)
+ errored['errored'] = True
+ other_type = copy.deepcopy(good)
+ other_type['resource_changes'][0]['type'] = 'aws_lb_listener'
cases = {'two attributes': (two_attributes, 'deregistration_delay'),
'two resources': (two_resources, '2 resource changes'),
'another address': (other_address, ADDR['443']),
@@ -506,7 +622,9 @@ class StepGateTests(Harness):
'unknown': (unknown, 'arn'),
'PPv2 off': (wrong_way, 'proxy_protocol_v2'),
'another attribute': (other_attribute, 'preserve_client_ip'),
- 'no change': (nothing, '0 resource changes')}
+ 'no change': (nothing, '0 resource changes'),
+ 'errored': (errored, 'errored'),
+ 'another type': (other_type, 'aws_lb_listener')}
for name, (plan, text) in cases.items():
with self.subTest(case=name):
self.assertIsNotNone(gate.plan_refusal(plan, ADDR['80'], 'proxy_protocol_v2', False, True))
@@ -517,8 +635,16 @@ class StepGateTests(Harness):
result = self.apply('A80')
self.assert_refused(result, text)
# The plan ran on the edited file, then the file came back byte for byte.
- self.assertIn('plan', [c['args'][0] for c in self.calls() if c['cli'] == 'tofu'])
+ self.assertIn('plan', self.tofu_ops())
self.assert_not_changed(TFVARS)
+ self.assertEqual([], list(self.root.glob('*.tfplan')))
+ self.assertFalse((self.records / 'A80-intent.json').exists())
+ # A preservation step whose plan has PPv2 off on both sides: refused
+ # (defence in depth; the tfvars agreement would also catch it).
+ ppv2_off = plan_for_step('B80')
+ for side in ('before', 'after'):
+ ppv2_off['resource_changes'][0]['change'][side]['proxy_protocol_v2'] = False
+ self.assertIn('needs it on', gate.plan_refusal(ppv2_off, ADDR['80'], 'preserve_client_ip', True, False))
# A plan that fails also restores the file.
self.setUp()
self.ready_for('A80')
@@ -535,7 +661,8 @@ class StepGateTests(Harness):
self.assert_not_changed(drift)
def test_barrier_up_refuses(self):
- for step in ('A80', 'B80'):
+ # B steps refuse while any barrier is up (spec 4.7).
+ for step in ('B80', 'B443'):
with self.subTest(step=step):
self.setUp()
self.ready_for(step)
@@ -543,6 +670,15 @@ class StepGateTests(Harness):
original = self.tfvars.read_bytes()
self.assert_refused(self.apply(step), 'barrier is up on ' + TARGETS[1])
self.assert_not_changed(original)
+ # A steps are allowed behind a barrier: in S0 and S1 no client is
+ # trusted, and this is the way forward after an S3 incident.
+ for step in ('A80', 'A443'):
+ with self.subTest(step=step):
+ self.setUp()
+ self.ready_for(step)
+ self.world['trust'][TARGETS[1]] = [trust('barrier_up')]
+ self.apply_converging(step)
+ self.assertTrue(json.loads((self.records / (step + '.json')).read_text())['passed'])
# Rollback is the safe direction; a raised barrier does not hold it.
self.setUp()
self.ready_for('R80')
@@ -550,15 +686,23 @@ class StepGateTests(Harness):
self.apply('R80', expect=0)
def test_unarmed_target_refuses(self):
- self.ready_for('A80')
- self.world['trust'][TARGETS[0]] = [trust('not_armed')]
- original = self.tfvars.read_bytes()
- self.assert_refused(self.apply('A80'), TARGETS[0] + ' is not armed')
- self.assert_not_changed(original)
+ for step in ('A80', 'B80'):
+ with self.subTest(step=step):
+ self.setUp()
+ self.ready_for(step)
+ self.world['trust'][TARGETS[0]] = [trust('not_armed')]
+ original = self.tfvars.read_bytes()
+ self.assert_refused(self.apply(step), TARGETS[0] + ' is not armed')
+ self.assert_not_changed(original)
# A target missing from --targets is refused too: the gate must see every target.
self.setUp()
self.ready_for('A80')
self.assert_refused(self.apply('A80', targets=TARGETS[:1]), TARGETS[1])
+ # Unhealthy at a forward apply: refused.
+ self.setUp()
+ self.ready_for('A80')
+ self.world['health'][TG['80']] = [[[TARGETS[0], 'healthy'], [TARGETS[1], 'unhealthy']]]
+ self.assert_refused(self.apply('A80'), TARGETS[1] + ' is unhealthy')
# An answer that is not a trust-status line is refused, never read as armed.
self.setUp()
self.ready_for('A80')
@@ -566,158 +710,485 @@ class StepGateTests(Harness):
del partial['counters']['marker_trusted']
self.world['trust'][TARGETS[0]] = [partial]
self.assert_refused(self.apply('A80'), 'trust-status')
+ # Instance ids are checked before they reach an aws argument list.
+ self.setUp()
+ self.ready_for('A80')
+ self.assert_refused(self.apply('A80', targets=[TARGETS[0], 'i-x;reboot']), 'is not an instance id')
+ self.assertEqual([], self.calls())
+ def test_reverse_steps_never_refuse_on_trust(self):
+ # Unarmed, barrier up (above) or no answer at all: R steps record it and go on.
+ for fault in ('not armed', 'ssm error'):
+ with self.subTest(fault=fault):
+ self.setUp()
+ self.ready_for('R80')
+ if fault == 'not armed':
+ self.world['trust'][TARGETS[0]] = [trust('not_armed')]
+ else:
+ self.world['ssm_fail'] = True
+ self.apply('R80', expect=0)
+ baseline = json.loads((self.records / 'R80-applied.json').read_text())['baseline']
+ self.assertIsInstance(baseline[TARGETS[0]], str)
+ self.assertIn('not armed' if fault == 'not armed' else 'not collected', baseline[TARGETS[0]])
+ self.assertIn('apply', self.tofu_ops())
+ # The same SSM error refuses every forward step.
+ for step in ('A80', 'B80'):
+ with self.subTest(step=step):
+ self.setUp()
+ self.ready_for(step)
+ self.world['ssm_fail'] = True
+ original = self.tfvars.read_bytes()
+ self.assert_refused(self.apply(step), 'send-command failed')
+ self.assert_not_changed(original)
-class ConvergeTests(Harness):
+ def test_apply_failure_contract(self):
+ # Once tofu apply has started: the edit and the intent stay, and the
+ # message says what to read and what to do.
+ self.ready_for('A80')
+ self.tfvars.write_bytes(TFVARS)
+ self.world['apply_rc'] = 1
+ result = self.apply('A80')
+ self.assert_refused(result, 'failed after it started')
+ self.assertIn('A80-intent.json', result.stderr)
+ self.assertEqual(1, len(result.stderr.strip().splitlines()))
+ self.assertTrue(json.loads(self.tfvars.read_text())['ppv2_proxy_protocol_v2']['80'])
+ intent = json.loads((self.records / 'A80-intent.json').read_text())
+ self.assertEqual(('A80', NLB, '80', 'proxy_protocol_v2', False, True),
+ (intent['step'], intent['nlb_arn'], intent['port'], intent['attribute'],
+ intent['before'], intent['after']))
+ self.assertEqual(TFVARS.decode(), intent['tfvars_before'])
+ self.assertIn('started_at', intent)
+ self.assertFalse((self.records / 'A80-applied.json').exists())
+ # Live unchanged: the next run refuses on the disagreeing file and names the intent.
+ self.world['apply_rc'] = 0
+ result = self.apply('A80')
+ self.assert_refused(result, 'disagrees with the live')
+ self.assertIn('A80-intent.json', result.stderr)
+ # Live changed (the apply got through before it failed): no change, and the intent named.
+ self.live({'80': 'S1'}, tfvars=False)
+ result = self.apply('A80')
+ self.assert_refused(result, 'no change')
+ self.assertIn('A80-intent.json', result.stderr)
+
+ # A signal before tofu apply: the file comes back byte for byte.
+ self.setUp()
+ self.ready_for('A80')
+ self.tfvars.write_bytes(TFVARS)
+ marker = Path(self.tmp.name) / 'planning'
+ self.world.update(plan_sleep=30, plan_marker=str(marker))
+ proc = subprocess.Popen([sys.executable, str(SCRIPT), *self.apply_args('A80')], env=self.env(),
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, stdin=subprocess.DEVNULL)
+ deadline = time.time() + 30
+ while not marker.exists() and time.time() < deadline:
+ time.sleep(0.05)
+ self.assertTrue(marker.exists())
+ self.assertNotEqual(TFVARS, self.tfvars.read_bytes()) # mid-plan, the edit is in place
+ proc.send_signal(signal.SIGTERM)
+ out, err = proc.communicate(timeout=60)
+ self.assertEqual(130, proc.returncode, err)
+ self.assertIn('restored', err)
+ self.assertNotIn('Traceback', err)
+ self.assertEqual(TFVARS, self.tfvars.read_bytes())
+ self.assertFalse((self.records / 'A80-intent.json').exists())
+ self.assertEqual([], list(self.root.glob('*.tfplan')))
+
+ # The edit itself cannot be written: refused, file untouched, one line.
+ self.setUp()
+ self.ready_for('A80')
+ self.tfvars.write_bytes(TFVARS)
+ (self.root / '.ppv2-step.lock').touch()
+ self.root.chmod(0o555)
+ self.addCleanup(self.root.chmod, 0o755)
+ result = self.apply('A80')
+ self.assertEqual(1, result.returncode)
+ self.assertIn('PermissionError', result.stderr)
+ self.assertEqual(1, len(result.stderr.strip().splitlines()))
+ self.assertEqual(TFVARS, self.tfvars.read_bytes())
+ self.assertNotIn('plan', self.tofu_ops())
+ self.root.chmod(0o755)
+
+ # Anything unexpected: one line and a non-zero exit, never a traceback.
+ self.setUp()
+ self.ready_for('A80')
+ self.world['health_malformed'] = True
+ result = self.apply('A80')
+ self.assertEqual(1, result.returncode)
+ self.assertIn('error: KeyError', result.stderr)
+ self.assertEqual(1, len(result.stderr.strip().splitlines()))
+
+ def test_overlapping_runs_lock(self):
+ # A run in progress holds the root: a second refuses before reading
+ # anything, and cannot put back the bytes the first one replaced.
+ self.ready_for('A80')
+ marker = Path(self.tmp.name) / 'planning'
+ self.world.update(plan_sleep=3, plan_marker=str(marker))
+ first = subprocess.Popen([sys.executable, str(SCRIPT), *self.apply_args('A80', timeout='0')], env=self.env(),
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, stdin=subprocess.DEVNULL)
+ deadline = time.time() + 30
+ while not marker.exists() and time.time() < deadline:
+ time.sleep(0.05)
+ self.assertTrue(marker.exists())
+ tofu_before = len([c for c in self.calls() if c['cli'] == 'tofu'])
+ second = subprocess.run([sys.executable, str(SCRIPT), *self.apply_args('A80')], env=dict(
+ os.environ, PATH=str(self.bin) + os.pathsep + os.environ['PATH'], PPV2_FAKE_WORLD=str(self.world_path),
+ PPV2_FAKE_CALLS=str(self.calls_path)), text=True, capture_output=True, timeout=60)
+ self.assert_refused(second, 'another ppv2-step run holds')
+ self.assertEqual(tofu_before, len([c for c in self.calls() if c['cli'] == 'tofu']))
+ first.communicate(timeout=60)
+ self.assertTrue((self.records / 'A80-applied.json').exists())
+ self.assertTrue(json.loads(self.tfvars.read_text())['ppv2_proxy_protocol_v2']['80'])
+ # The record directory is held too: converge refuses while a run holds it.
+ with open(self.records / '.ppv2-step.lock', 'a') as held:
+ fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ result = self.run_step('converge', '--step', 'A80', '--record-dir', str(self.records),
+ '--probe-records', 'a.json,b.json', '--targets', ','.join(TARGETS),
+ '--profile', 'kass', '--region', 'eu-west-1', '--tg-arn', TG['80'])
+ self.assert_refused(result, 'another ppv2-step run holds')
+ # Every run plans into its own file.
+ names = set()
+ for _ in range(2):
+ self.setUp()
+ self.ready_for('A80')
+ self.world['plan_rc'] = 1
+ self.apply('A80')
+ plan = [c for c in self.calls() if c['cli'] == 'tofu' and c['args'][0] == 'plan'][0]
+ names.add([a for a in plan['args'] if a.startswith('-out=')][0])
+ self.assertEqual(2, len(names))
+ self.assertTrue(all(n.startswith('-out=.ppv2-A80-') for n in names))
+
+ def test_standalone_converge_resumes(self):
+ # A rollback without probes, then its convergence resumed by hand.
+ self.ready_for('R80')
+ self.apply('R80', expect=0)
+ self.world = json.loads(self.world_path.read_text()) # the fake apply moved the target group to S1
+ self.assertFalse((self.records / 'R80.json').exists())
+ start = time.time() + 1.5
+ for name, ip in zip(('a.json', 'b.json'), PUBLIC):
+ (self.probes / name).write_text(json.dumps(probe_doc(ip, 80, 's1', start, start + 0.2)))
+ args = ['converge', '--step', 'R80', '--record-dir', str(self.records),
+ '--probe-records', ','.join(str(self.probes / n) for n in ('a.json', 'b.json')),
+ '--profile', 'kass', '--region', 'eu-west-1', '--tg-arn', TG['80']]
+ # The targets must be the apply's: a shortened list is refused.
+ self.assert_refused(self.run_step(*args, '--targets', TARGETS[0]), "must be the apply's targets")
+ self.run_step(*args, '--targets', ','.join(TARGETS), expect=0)
+ self.assertTrue(json.loads((self.records / 'R80.json').read_text())['passed'])
+ # Nothing to resume once it passed.
+ self.assert_refused(self.run_step(*args, '--targets', ','.join(TARGETS)), 'already passed')
+
+
+class FakeClock:
+ def __init__(self, t):
+ self.t = t
+ self.events = []
+
+ def time(self):
+ return self.t
+
+ def at(self, t, fn):
+ self.events.append((t, fn))
+
+ def sleep(self, seconds):
+ self.t += seconds
+ for event in sorted(self.events, key=lambda e: e[0]):
+ if self.t >= event[0]:
+ self.events.remove(event)
+ event[1]()
+
+
+T0 = gate.epoch(APPLIED_AT)
+
+
+class FakeCloud:
+ """The calls converge makes, answered from a timeline relative to the apply (T0)."""
+
+ def __init__(self, clock, step):
+ self.clock = clock
+ self.unhealthy = [] # (from s, to s, instance)
+ self.registered = list(TARGETS)
+ self.trust_delay = 0.0 # seconds SSM takes to answer
+ self.samples = {t: [(0, 'b_both_nodes' if step.startswith('B') else 'after_a')] for t in TARGETS}
+ self.override = {} # instance -> trust-status dict, whatever the time
+ self.state = STEP_TO[step]
+ self.health_cost = {} # health call number -> seconds it takes
+ self.health_calls, self.jobs = [], {}
+
+ def health(self, tg):
+ n = len(self.health_calls)
+ self.health_calls.append(self.clock.t - T0)
+ self.clock.t += self.health_cost.get(n, 0)
+ rel = self.clock.t - T0
+ return {iid: 'unhealthy' if any(lo <= rel < hi and who == iid for lo, hi, who in self.unhealthy) else 'healthy'
+ for iid in self.registered}
+
+ def send(self, targets, command):
+ cid = 'c%d' % len(self.jobs)
+ self.jobs[cid] = (self.clock.t, list(targets))
+ return cid
+
+ def invocations(self, cid):
+ sent, targets = self.jobs[cid]
+ if self.clock.t < sent + self.trust_delay:
+ return {iid: ('InProgress', -1, '', '') for iid in targets}
+ out = {}
+ for iid in targets:
+ name = [n for since, n in self.samples[iid] if since <= sent - T0][-1]
+ out[iid] = ('Success', 0, json.dumps(self.override.get(iid) or trust(name)) + '\n', '')
+ return out
+
+ def attributes(self, tg):
+ preserve, ppv2 = STATES[self.state]
+ return {'preserve_client_ip': preserve == 'true', 'proxy_protocol_v2': ppv2 == 'true'}
+
+
+class ConvergeTests(unittest.TestCase):
def setUp(self):
- super().setUp()
- self.prereq()
+ self.tmp = tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR'))
+ self.addCleanup(self.tmp.cleanup)
+ self.n = 0
- def applied(self, step, baseline='baseline'):
+ def fresh(self, step='A80'):
+ """A new record directory, apply record, clock and cloud for `step`."""
+ self.n += 1
+ self.records = Path(self.tmp.name) / ('records%d' % self.n)
+ self.records.mkdir()
+ write_prereq(self.records)
port = STEP_PLAN[step][0]
- self.live({port: {'A': 'S1', 'B': 'S2', 'R': 'S1'}[step[0]]})
- self.record(step + '-applied', nlb_arn=NLB, port=port, step=step, applied_at=APPLIED_AT,
- tg_arn=TG[port], tg_address=ADDR[port],
- baseline={t: trust(baseline) for t in TARGETS})
-
- def probe(self, name, nlb_ip, port, expect, passed=True, started_at='2026-11-12T10:00:05.000000Z'):
- attempts = [{'at': '2026-11-12T10:00:%02d.000000Z' % (5 + 2 * i), 'verdict': 'match'} for i in range(30)]
- doc = {'nlb_ip': nlb_ip, 'port': int(port), 'expect': expect, 'started_at': started_at,
- 'finished_at': '2026-11-12T10:01:05.000000Z', 'passed': passed, 'attempts': attempts}
- path = self.probes / name
- path.write_text(json.dumps(doc))
- return path
-
- def converge(self, step, probes, expect=None):
- return self.run_step('converge', '--step', step, '--record-dir', str(self.records),
- '--probe-records', ','.join(str(p) for p in probes),
- '--targets', ','.join(TARGETS), '--profile', 'kass', '--region', 'eu-west-1',
- '--tg-arn', TG[STEP_PLAN[step][0]], '--timeout', '0', expect=expect)
-
- def result(self, step):
- return json.loads((self.records / (step + '.json')).read_text())
+ baseline = 'before_b' if step.startswith('B') else 'baseline'
+ self.applied = {'nlb_arn': NLB, 'port': port, 'step': step, 'applied_at': APPLIED_AT, 'tg_arn': TG[port],
+ 'targets': list(TARGETS), 'baseline': {t: trust(baseline) for t in TARGETS},
+ 'baseline_at': gate.iso(T0 - 5)}
+ self.clock = FakeClock(T0 + 1)
+ self.cloud = FakeCloud(self.clock, step)
+ self.paths = [str(self.records / 'a.json'), str(self.records / 'b.json')]
+ self.step = step
+
+ def probes(self, at=T0 + 70, started=T0 + 5, finished=T0 + 65, docs=None):
+ """Probe records that arrive at `at` (None: already there)."""
+ expect = EXPECT[self.step[0]]
+ port = STEP_PLAN[self.step][0]
+ docs = docs or [probe_doc(ip, port, expect, started, finished) for ip in PUBLIC]
+
+ def write():
+ for path, doc in zip(self.paths, docs):
+ if doc is not None:
+ Path(path).write_text(json.dumps(doc))
+ if at is None:
+ write()
+ else:
+ self.clock.at(at, write)
+
+ def run_converge(self, timeout=600, paths=None):
+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
+ code = gate.converge(self.cloud, self.records, self.applied, paths or self.paths, timeout)
+ return code, json.loads((self.records / f'{self.step}.json').read_text())
+
+ def assert_reason(self, record, *texts, passed=False):
+ self.assertEqual(passed, record['passed'], record['reasons'])
+ for text in texts:
+ self.assertTrue(any(text in r for r in record['reasons']), (text, record['reasons']))
def test_converge_needs_both_probe_records(self):
- a = lambda **kw: self.probe('a.json', '54.77.110.223', 80, 's1', **kw)
- b = lambda **kw: self.probe('b.json', '54.77.110.224', 80, 's1', **kw)
- self.applied('A80')
- self.world['trust'] = {t: [trust('after_a')] for t in TARGETS}
- # The good case first.
- self.converge('A80', [a(), b()], expect=0)
- record = self.result('A80')
+ self.fresh()
+ self.probes()
+ code, record = self.run_converge()
+ self.assertEqual(0, code, record['reasons'])
self.assertTrue(record['passed'])
self.assertEqual((NLB, '80', 'A80', APPLIED_AT),
(record['nlb_arn'], record['port'], record['step'], record['applied_at']))
- self.assertEqual(['54.77.110.223', '54.77.110.224'], sorted(p['nlb_ip'] for p in record['probes']))
+ self.assertEqual(sorted(PUBLIC), sorted(p['nlb_ip'] for p in record['probes']))
self.assertTrue(all(p['propagation_s'] == 5.0 for p in record['probes']))
- # The target group must still be in the state the step made.
- self.live({'80': 'S0'})
- self.assertEqual(1, self.converge('A80', [a(), b()]).returncode)
- self.assertIn('the target group is in S0, not S1', self.result('A80')['reasons'])
- self.live({'80': 'S1'})
- # One record only: refused outright.
- self.assert_refused(self.converge('A80', [a()]), 'two probe records')
- # Each case writes its records when it runs, so no case sees another's files.
+ # One record for a two-address NLB: refused outright.
+ self.fresh()
+ with self.assertRaisesRegex(gate.Refused, 'one probe record per NLB address'):
+ gate.converge(self.cloud, self.records, self.applied, self.paths[:1], 600)
+ port, s1 = 80, 's1'
+ good = lambda ip: probe_doc(ip, port, s1, T0 + 5, T0 + 65)
cases = {
- 'same address': (lambda: [a(), self.probe('c.json', '54.77.110.223', 80, 's1')], 'both NLB addresses'),
- 'one failed': (lambda: [a(), b(passed=False)], 'did not pass'),
- 'started before apply': (lambda: [a(), b(started_at='2026-11-12T09:59:59.000000Z')], 'before the apply'),
- 'other port': (lambda: [a(), self.probe('c.json', '54.77.110.224', 443, 's1')], 'port 443'),
- 'other expectation': (lambda: [a(), self.probe('c.json', '54.77.110.224', 80, 's0')], 'expected s0'),
- 'missing': (lambda: [a(), self.probes / 'never.json'], 'never.json'),
+ 'same address': ([good(PUBLIC[0]), good(PUBLIC[0])], 'both NLB addresses'),
+ 'foreign address': ([good(PUBLIC[0]), good('203.0.113.50')], 'not an address of this NLB'),
+ 'another NLB, both': ([good('203.0.113.50'), good('203.0.113.51')], 'no probe record covers NLB address'),
+ 'one failed': ([good(PUBLIC[0]), probe_doc(PUBLIC[1], port, s1, T0 + 5, T0 + 65, passed=False)], 'did not pass'),
+ 'started before apply': ([good(PUBLIC[0]), probe_doc(PUBLIC[1], port, s1, T0 - 1, T0 + 65)], 'before the apply'),
+ 'other port': ([good(PUBLIC[0]), probe_doc(PUBLIC[1], 443, s1, T0 + 5, T0 + 65)], 'port 443'),
+ 'other expectation': ([good(PUBLIC[0]), probe_doc(PUBLIC[1], port, 's0', T0 + 5, T0 + 65)], 'expected s0'),
+ 'missing': ([good(PUBLIC[0]), None], 'b.json did not arrive'),
}
- for name, (paths, text) in cases.items():
+ for name, (docs, text) in cases.items():
with self.subTest(case=name):
- result = self.converge('A80', paths())
- self.assertEqual(1, result.returncode, result.stderr)
- record = self.result('A80')
- self.assertFalse(record['passed'])
- self.assertTrue(any(text in reason for reason in record['reasons']), record['reasons'])
- # No applied record: nothing to converge.
- (self.records / 'A80-applied.json').unlink()
- self.assert_refused(self.converge('A80', [a(), b()]), 'A80-applied.json')
+ self.fresh()
+ self.probes(docs=docs)
+ code, record = self.run_converge(timeout=120)
+ self.assertEqual(1, code)
+ self.assert_reason(record, text)
def test_converge_fails_on_counter_move(self):
- for sample, counter in [('malformed_moved', 'malformed'), ('marker_trusted_moved', 'marker_trusted'),
- ('no_client_refused_moved', 'no_client_refused'), ('barrier_up', 'barrier')]:
- with self.subTest(counter=counter):
- self.setUp()
- self.applied('A443')
- self.world['trust'][TARGETS[1]] = [trust('after_a'), trust(sample)]
- result = self.converge('A443', [self.probe('a.json', '54.77.110.223', 443, 's1'),
- self.probe('b.json', '54.77.110.224', 443, 's1')])
- self.assertEqual(1, result.returncode)
- record = self.result('A443')
- self.assertFalse(record['passed'])
- self.assertTrue(any(counter in r and TARGETS[1] in r for r in record['reasons']), record['reasons'])
- # Counters that may move (proxied, no_client, ignored) do not fail it.
- self.setUp()
- self.applied('A443')
- self.world['trust'] = {t: [trust('after_a')] for t in TARGETS}
- self.converge('A443', [self.probe('a.json', '54.77.110.223', 443, 's1'),
- self.probe('b.json', '54.77.110.224', 443, 's1')], expect=0)
+ for sample, text in [('malformed_moved', 'malformed moved'), ('marker_trusted_moved', 'marker_trusted moved'),
+ ('no_client_refused_moved', 'no_client_refused moved'),
+ ('restarted', 'the edge restarted')]:
+ with self.subTest(sample=sample):
+ self.fresh('A443')
+ self.cloud.samples[TARGETS[1]] = [(0, 'after_a'), (20, sample)]
+ self.probes()
+ code, record = self.run_converge()
+ self.assertEqual(1, code)
+ self.assert_reason(record, text, TARGETS[1])
+ # Counters that may move (proxied, no_client, ignored) do not fail it,
+ # and a barrier does not fail an A step.
+ self.fresh('A443')
+ self.cloud.samples[TARGETS[1]] = [(0, 'after_a'), (20, 'barrier_up')]
+ self.probes()
+ self.assertEqual(0, self.run_converge()[0])
+ # A barrier fails a B step's convergence.
+ self.fresh('B80')
+ barrier = trust('b_both_nodes')
+ barrier['barrier'] = True
+ self.cloud.override[TARGETS[1]] = barrier
+ self.probes()
+ code, record = self.run_converge()
+ self.assert_reason(record, TARGETS[1] + ': barrier is up')
def test_converge_fails_on_unhealthy_poll(self):
- for rows, text in [([[TARGETS[0], 'healthy'], [TARGETS[1], 'unhealthy']], 'unhealthy'),
- ([[TARGETS[0], 'healthy']], 'not registered'),
- ([[TARGETS[0], 'healthy'], [TARGETS[1], 'healthy'], ['i-0ccccccccccccccc3', 'healthy']],
- 'i-0ccccccccccccccc3')]:
- with self.subTest(rows=rows):
- self.setUp()
- self.applied('A80')
- self.world['trust'] = {t: [trust('after_a')] for t in TARGETS}
- # The bad poll is the first one; the last poll is healthy again.
- self.world['health'][TG['80']] = [rows, [[t, 'healthy'] for t in TARGETS]]
- result = self.converge('A80', [self.probe('a.json', '54.77.110.223', 80, 's1'),
- self.probe('b.json', '54.77.110.224', 80, 's1')])
- self.assertEqual(1, result.returncode)
- record = self.result('A80')
- self.assertFalse(record['passed'])
- self.assertTrue(any(text in r for r in record['reasons']), record['reasons'])
- self.assertGreaterEqual(len(record['health_polls']), 2)
+ for setup, text in [(lambda c: c.unhealthy.append((15, 28, TARGETS[1])), TARGETS[1] + ' is unhealthy'),
+ (lambda c: setattr(c, 'registered', TARGETS[:1]), TARGETS[1] + ' is not registered'),
+ (lambda c: c.registered.append('i-0ccccccccccccccc3'), 'i-0ccccccccccccccc3')]:
+ with self.subTest(text=text):
+ self.fresh()
+ setup(self.cloud)
+ self.probes()
+ code, record = self.run_converge()
+ self.assertEqual(1, code)
+ self.assert_reason(record, text)
+ self.assertGreaterEqual(record['health_polls'], 7)
+
+ def test_health_polled_while_ssm_slow(self):
+ # SSM answers 40 s late; a target is unhealthy from 10 s to 30 s. The
+ # health schedule must not wait for SSM, so the unhealthy spell is seen.
+ self.fresh()
+ self.cloud.trust_delay = 40
+ self.cloud.unhealthy.append((10, 30, TARGETS[1]))
+ self.probes()
+ code, record = self.run_converge()
+ self.assertEqual(1, code)
+ self.assert_reason(record, TARGETS[1] + ' is unhealthy')
+ self.assertFalse(any('was not observed' in r for r in record['reasons']), record['reasons'])
+ polled = [round(t) for t in self.cloud.health_calls]
+ for t in (11, 21):
+ self.assertIn(t, polled)
+
+ def test_missed_health_observation_refuses(self):
+ # One health call that hangs for 25 s leaves 25 s unobserved inside
+ # the probes' window: refused even though every answer was healthy.
+ self.fresh()
+ self.cloud.health_cost = {2: 25}
+ self.probes(at=T0 + 100, finished=T0 + 95)
+ code, record = self.run_converge()
+ self.assertEqual(1, code)
+ self.assert_reason(record, 'target health was not observed for')
def test_b_convergence_needs_both_nodes(self):
- probes = lambda: [self.probe('a.json', '54.77.110.223', 80, 's2'),
- self.probe('b.json', '54.77.110.224', 80, 's2')]
- self.applied('B80', baseline='before_b')
- self.world['trust'] = {TARGETS[0]: [trust('b_both_nodes')], TARGETS[1]: [trust('b_one_node')]}
- result = self.converge('B80', probes())
- self.assertEqual(1, result.returncode)
- record = self.result('B80')
- self.assertFalse(record['passed'])
- self.assertTrue(any(TARGETS[1] in r and '172.31.11.189' in r for r in record['reasons']), record['reasons'])
+ self.fresh('B80')
+ self.cloud.samples[TARGETS[1]] = [(0, 'b_one_node')]
+ self.probes()
+ code, record = self.run_converge()
+ self.assertEqual(1, code)
+ self.assert_reason(record, TARGETS[1] + ': proxied from node 172.31.11.189 did not rise')
self.assertFalse(any(TARGETS[0] in r for r in record['reasons']), record['reasons'])
# Both nodes on every target: passed.
- self.setUp()
- self.applied('B80', baseline='before_b')
- self.world['trust'] = {t: [trust('b_both_nodes')] for t in TARGETS}
- self.converge('B80', probes(), expect=0)
- self.assertTrue(self.result('B80')['passed'])
- # The node addresses come from prereq.json; without it B cannot converge.
+ self.fresh('B80')
+ self.probes()
+ self.assertEqual(0, self.run_converge()[0])
+ # The node and public addresses come from prereq.json; without it nothing converges.
+ self.fresh('B80')
(self.records / 'prereq.json').unlink()
- result = self.converge('B80', probes())
- self.assertEqual(1, result.returncode)
- self.assertTrue(any('prereq.json' in r for r in self.result('B80')['reasons']))
- # A steps do not need the nodes to rise.
- self.setUp()
- self.applied('A80')
- self.world['trust'] = {t: [trust('after_a')] for t in TARGETS}
- self.converge('A80', [self.probe('a.json', '54.77.110.223', 80, 's1'),
- self.probe('b.json', '54.77.110.224', 80, 's1')], expect=0)
+ with self.assertRaisesRegex(gate.Refused, 'prereq.json'):
+ gate.converge(self.cloud, self.records, self.applied, self.paths, 600)
+
+ def test_records_arrive_mid_loop(self):
+ # The probes finish at 65 s and their records land at 70 s: the loop
+ # polls all along, then takes its last look.
+ self.fresh()
+ self.probes(at=T0 + 70)
+ code, record = self.run_converge()
+ self.assertEqual(0, code, record['reasons'])
+ self.assertGreaterEqual(record['health_polls'], 8)
+ self.assertGreaterEqual(record['trust_polls'], 3)
+ self.assertEqual([gate.iso(T0 + 5), gate.iso(T0 + 65)], record['window'])
+ self.assertGreater(max(self.cloud.health_calls), 65)
+ # Records already there, from probes that ran before anything watched
+ # health: an after-the-fact converge cannot pass.
+ self.fresh()
+ self.clock.t = T0 + 90
+ self.probes(at=None)
+ code, record = self.run_converge()
+ self.assertEqual(1, code)
+ self.assert_reason(record, 'target health was not observed before the earliest probe started')
+
+ def test_rerun_cannot_launder(self):
+ # A failed run, then a clean re-run for the same apply: still failed.
+ self.fresh()
+ self.cloud.unhealthy.append((10, 30, TARGETS[1]))
+ self.probes()
+ self.assertEqual(1, self.run_converge()[0])
+ self.clock = FakeClock(T0 + 100)
+ self.cloud = FakeCloud(self.clock, 'A80')
+ start = T0 + 105
+ self.probes(at=start + 70, started=start, finished=start + 60)
+ code, record = self.run_converge()
+ self.assertEqual(1, code)
+ self.assert_reason(record, 'earlier run: ', TARGETS[1] + ' is unhealthy')
+ # An interrupted run writes no verdict, but its polls stay: the resume sees them.
+ self.fresh()
+ self.cloud.unhealthy.append((10, 30, TARGETS[1]))
+
+ def interrupt():
+ raise gate.Interrupted('SIGTERM')
+ self.clock.at(T0 + 35, interrupt)
+ with self.assertRaisesRegex(gate.Interrupted, 'no verdict written'):
+ self.run_converge()
+ self.assertFalse((self.records / 'A80.json').exists())
+ self.cloud.unhealthy = []
+ self.probes(at=T0 + 110, started=T0 + 40, finished=T0 + 100)
+ code, record = self.run_converge()
+ self.assertEqual(1, code)
+ self.assert_reason(record, TARGETS[1] + ' is unhealthy')
+ # A passed record is final: there is nothing to resume.
+ self.fresh()
+ self.probes()
+ self.assertEqual(0, self.run_converge()[0])
+ with self.assertRaisesRegex(gate.Refused, 'already passed'):
+ self.run_converge()
+
+ def test_converge_targets_must_match_apply(self):
+ # A target deregistered during the step is not dropped: it is still checked.
+ self.fresh()
+ self.cloud.registered = TARGETS[:1]
+ self.probes()
+ code, record = self.run_converge()
+ self.assert_reason(record, TARGETS[1] + ' is not registered')
+ # A baseline that does not cover every target cannot pass.
+ self.fresh()
+ del self.applied['baseline'][TARGETS[1]]
+ self.probes()
+ code, record = self.run_converge()
+ self.assert_reason(record, 'recorded baselines for')
class PrereqTests(Harness):
- def run_prereq(self, expect=None):
+ def run_prereq(self, expect=None, sources=SOURCES):
return self.run_step('prereq', '--profile', 'kass', '--region', 'eu-west-1', '--nlb-arn', NLB,
'--tg-arn-80', TG['80'], '--tg-arn-443', TG['443'],
- '--targets', ','.join(TARGETS), '--sources', ','.join(reversed(SOURCES)),
+ '--targets', ','.join(TARGETS), '--sources', ','.join(reversed(sources)),
'--alarm', ALARM, '--record-dir', str(self.records), expect=expect)
def test_prereq_record(self):
- self.run_prereq(expect=0)
+ result = self.run_prereq(expect=0)
+ self.assertIn('automated checks only', result.stdout)
+ self.assertIn('bootstrap', result.stdout)
record = json.loads((self.records / 'prereq.json').read_text())
self.assertTrue(record['passed'])
- self.assertEqual((NLB, SOURCES), (record['nlb_arn'], record['sources']))
+ self.assertTrue(record['automated_checks_only'])
+ self.assertEqual(4, len(record['manual_prerequisites_owed']))
+ self.assertEqual((NLB, SOURCES, PUBLIC), (record['nlb_arn'], record['sources'], record['public_addresses']))
cases = {
'TG not in S0': (lambda: self.live({'80': 'S1', '443': 'S0'}), 'S1'),
'other addresses': (lambda: self.world['journal'].update(
@@ -730,6 +1201,11 @@ class PrereqTests(Harness):
'alarm missing': (lambda: self.world.update(alarms={}), ALARM),
'unhealthy': (lambda: self.world['health'].update(
{TG['443']: [[[TARGETS[0], 'healthy'], [TARGETS[1], 'draining']]]}), 'draining'),
+ # The node addresses are the NLB's interfaces, not whatever every box was given.
+ 'sources not the interfaces': (lambda: self.world['interfaces'][1].update(private='172.31.40.7'),
+ "are not the NLB's node addresses"),
+ 'no public address': (lambda: self.world['interfaces'][1].pop('public'), 'no public address'),
+ 'no interfaces': (lambda: self.world.update(nlb_suffix='net/other/1'), 'no network interfaces'),
}
for name, (fault, text) in cases.items():
with self.subTest(case=name):
@@ -738,6 +1214,7 @@ class PrereqTests(Harness):
result = self.run_prereq()
self.assertEqual(1, result.returncode, result.stderr)
self.assertIn(text, result.stderr)
+ self.assertIn('automated checks only', result.stderr)
record = json.loads((self.records / 'prereq.json').read_text())
self.assertFalse(record['passed'])
diff --git a/scripts/testdata/ppv2/probe-responses.json b/scripts/testdata/ppv2/probe-responses.json
index f4ad2ede2..a4a8221a6 100644
--- a/scripts/testdata/ppv2/probe-responses.json
+++ b/scripts/testdata/ppv2/probe-responses.json
@@ -14,7 +14,8 @@
"timeout": {"error": "TimeoutError", "detail": "timed out"},
"echo-other-client": {"raw": "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\n198.51.100.7\n"},
"echo-forged": {"raw": "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 10\r\n\r\n192.0.2.1\n"},
- "echo-forged-chain": {"raw": "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 23\r\n\r\n192.0.2.1, 203.0.113.9\n"}
+ "echo-forged-chain": {"raw": "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 23\r\n\r\n192.0.2.1, 203.0.113.9\n"},
+ "echo-forged-json": {"raw": "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 32\r\n\r\n{\"x_forwarded_for\":\"192.0.2.1\"}\n"}
},
"table": [
{"state": "s0", "port": 443, "plain": "echo-200", "marker": "echo-200"},
diff --git a/scripts/testdata/ppv2/trust-status.json b/scripts/testdata/ppv2/trust-status.json
index 615f2476f..317897236 100644
--- a/scripts/testdata/ppv2/trust-status.json
+++ b/scripts/testdata/ppv2/trust-status.json
@@ -8,6 +8,7 @@
"malformed_moved": {"armed": true, "barrier": false, "counters": {"proxied": 0, "no_client": 5180, "no_client_refused": 0, "ignored": 412, "ignored_private": 0, "marker_trusted": 0, "malformed": 1, "timeout": 0}, "proxied_by_node": {}},
"marker_trusted_moved": {"armed": true, "barrier": false, "counters": {"proxied": 0, "no_client": 5180, "no_client_refused": 0, "ignored": 412, "ignored_private": 0, "marker_trusted": 2, "malformed": 0, "timeout": 0}, "proxied_by_node": {}},
"no_client_refused_moved": {"armed": true, "barrier": false, "counters": {"proxied": 0, "no_client": 5180, "no_client_refused": 7, "ignored": 412, "ignored_private": 0, "marker_trusted": 0, "malformed": 0, "timeout": 0}, "proxied_by_node": {}},
+ "restarted": {"armed": true, "barrier": false, "counters": {"proxied": 0, "no_client": 12, "no_client_refused": 0, "ignored": 3, "ignored_private": 0, "marker_trusted": 0, "malformed": 0, "timeout": 0}, "proxied_by_node": {}},
"barrier_up": {"armed": true, "barrier": true, "counters": {"proxied": 0, "no_client": 5120, "no_client_refused": 0, "ignored": 0, "ignored_private": 0, "marker_trusted": 0, "malformed": 0, "timeout": 0}, "proxied_by_node": {}},
"not_armed": {"rc": 2, "stderr": "edge: this box is not armed for PROXY protocol\n"}
}