| index 6cb6d47e0..79e7c1478 100755 |
| --- a/scripts/ppv2-step.py |
| +++ b/scripts/ppv2-step.py |
| @@ -15,14 +15,18 @@ them changes PPv2 while preservation is off, so no node can pass through S3. |
| |
| 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 |
| + barrier down, the trust alarm OK, and on every target the |
| + installed guard binary (/opt/carlos/system/guard/carlos) absent |
| + or reporting ingress-proxy-v2. 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. |
| + it polls target health in BOTH target groups every 10 s, from |
| + just after <step>-intent.json is written (before tofu apply |
| + starts) to the verdict, 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 (or reverify) of a |
| step, after an interruption. Polls already made for it count, and |
| a failure already seen is never cleared. |
| @@ -38,6 +42,20 @@ them changes PPv2 while preservation is off, so no node can pass through S3. |
| --incident-cleared. Each step binds to the latest of its |
| predecessor's apply, reverify and intent: an intent newer than |
| the evidence makes it stale until a reverify passes. |
| + sync-tfvars |
| + rewrites ppv2.auto.tfvars.json to both target groups' live |
| + attributes, under the lock: after the S3 incident procedure's |
| + direct preservation-on command, the file disagrees with live and |
| + every step refuses until it matches. Refuses while either group |
| + is in S3. |
| + |
| +Every apply, converge and reverify names both target groups (--tg-arn-80, |
| +--tg-arn-443; each checked against the NLB and its port) and watches both: |
| +an unhealthy target in either group at any poll fails the step (spec 6.4). |
| +A step also fails when a target's edge restarts during it: its trust-status |
| +edge_instance changes, or any counter falls from one poll to the next. B |
| +steps converge on the changed port's own per-listener counts (by_listener), |
| +never on the other listener's traffic. |
| |
| Steps: A80, A443 (PPv2 on), B80, B443 (preservation off), R443, R80 |
| (preservation back on). Nothing turns PPv2 off; there is no step for it. |
| @@ -96,6 +114,15 @@ COUNTERS = ('proxied', 'no_client', 'no_client_refused', 'ignored', 'ignored_pri |
| STILL = ('malformed', 'timeout', 'ignored_private', 'marker_trusted', 'no_client_refused') |
| PROBE_EXPECT = {'A': 's1', 'B': 's2', 'R': 's1'} |
| TRUST_STATUS = '/opt/carlos/carlos system edge trust-status' |
| +LISTENERS = ('80', '443') |
| +TRUST_KEYS = {'armed', 'barrier', 'edge_instance', 'counters', 'proxied_by_node', 'by_listener'} |
| +# The guard binary guard-arm installs; app updates do not refresh it, and an |
| +# old one's `guard-exec recover` has no PPv2 gate (spec 6.1). |
| +GUARD_BINARY = '/opt/carlos/system/guard/carlos' |
| +GUARD_ABSENT = 'ppv2-step: guard binary absent' |
| +GUARD_CHECK = (f'g={GUARD_BINARY}; if [ -e "$g" ] || [ -L "$g" ]; then "$g" version --json; ' |
| + f"else echo '{GUARD_ABSENT}'; fi") |
| +FEATURE = 'ingress-proxy-v2' |
| 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)') |
| @@ -251,8 +278,18 @@ def plan_refusal(plan, address, attribute, before, after): |
| return None |
| |
| |
| +def counts_ok(counters, nodes): |
| + if not isinstance(counters, dict) or set(counters) != set(COUNTERS): |
| + return False |
| + if not all(type(v) is int and v >= 0 for v in counters.values()): |
| + return False |
| + return isinstance(nodes, dict) and all(isinstance(k, str) and type(v) is int and v >= 0 for k, v in nodes.items()) |
| + |
| + |
| def parse_trust(text): |
| - """The trust-status line in text, validated, or None.""" |
| + """The trust-status line in text, validated, or None: every field present, |
| + and armed, a non-empty edge_instance and exactly the two listeners, whose |
| + counts sum to the line's own.""" |
| lines = [line for line in (text or '').splitlines() if line.strip()] |
| if not lines: |
| return None |
| @@ -260,16 +297,30 @@ def parse_trust(text): |
| doc = json.loads(lines[-1]) |
| except ValueError: |
| return None |
| - if not isinstance(doc, dict) or set(doc) != {'armed', 'barrier', 'counters', 'proxied_by_node'}: |
| + if not isinstance(doc, dict) or set(doc) != TRUST_KEYS: |
| return None |
| if not isinstance(doc['armed'], bool) or not isinstance(doc['barrier'], bool): |
| return None |
| - counters, nodes = doc['counters'], doc['proxied_by_node'] |
| - if not isinstance(counters, dict) or set(counters) != set(COUNTERS): |
| + if not counts_ok(doc['counters'], doc['proxied_by_node']): |
| return None |
| - if not all(type(v) is int and v >= 0 for v in counters.values()): |
| + instance, listeners = doc['edge_instance'], doc['by_listener'] |
| + if not isinstance(instance, str) or not isinstance(listeners, dict): |
| return None |
| - if not isinstance(nodes, dict) or not all(isinstance(k, str) and type(v) is int and v >= 0 for k, v in nodes.items()): |
| + if not doc['armed']: |
| + return doc if instance == '' and listeners == {} else None |
| + if not instance or set(listeners) != set(LISTENERS): |
| + return None |
| + for port in LISTENERS: |
| + l = listeners[port] |
| + if not isinstance(l, dict) or set(l) != set(COUNTERS) | {'proxied_by_node'}: |
| + return None |
| + if not counts_ok({c: l[c] for c in COUNTERS}, l['proxied_by_node']): |
| + return None |
| + if any(doc['counters'][c] != sum(listeners[p][c] for p in LISTENERS) for c in COUNTERS): |
| + return None |
| + nodes = set(doc['proxied_by_node']).union(*(listeners[p]['proxied_by_node'] for p in LISTENERS)) |
| + if any(doc['proxied_by_node'].get(n, 0) != sum(listeners[p]['proxied_by_node'].get(n, 0) for p in LISTENERS) |
| + for n in nodes): |
| return None |
| return doc |
| |
| @@ -408,13 +459,22 @@ class Cloud: |
| """{instance: trust-status dict, or a string saying why there is none}.""" |
| return {iid: trust_of(iid, *answer) for iid, answer in self.ssm(targets, TRUST_STATUS).items()} |
| |
| - def tofu(self, root, *args): |
| + def tofu(self, root, *args, tick=None): |
| + """tick, when given, is called about every TICK seconds while tofu runs |
| + (the health watch through tofu apply).""" |
| # 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() |
| + while True: |
| + if tick is not None: |
| + tick() |
| + try: |
| + out, err = proc.communicate(timeout=None if tick is None else TICK) |
| + break |
| + except subprocess.TimeoutExpired: |
| + continue # retrying communicate loses no output |
| except BaseException: |
| proc.send_signal(signal.SIGINT) |
| try: |
| @@ -567,13 +627,23 @@ def prereq_for(record_dir, nlb_arn): |
| return prereq |
| |
| |
| -def tfvars_check(doc, port, live): |
| +def tfvars_shape(doc): |
| + """Why doc is not the file's shape (both keys, true or false for exactly "80" and "443"), or None.""" |
| if not isinstance(doc, dict) or set(doc) != set(TFVARS_KEY.values()): |
| return f'{TFVARS_FILE} must hold exactly {", ".join(sorted(TFVARS_KEY.values()))}' |
| - for attribute, key in TFVARS_KEY.items(): |
| + for key in TFVARS_KEY.values(): |
| values = doc[key] |
| if not isinstance(values, dict) or set(values) != {'80', '443'} or not all(isinstance(v, bool) for v in values.values()): |
| return f'{TFVARS_FILE} {key} must set true or false for exactly "80" and "443"' |
| + return None |
| + |
| + |
| +def tfvars_check(doc, port, live): |
| + reason = tfvars_shape(doc) |
| + if reason: |
| + return reason |
| + for attribute, key in TFVARS_KEY.items(): |
| + values = doc[key] |
| if values[port] != live[attribute]: |
| return (f'{TFVARS_FILE} {key}["{port}"] is {norm(values[port])}, which disagrees with the live ' |
| f'target group ({norm(live[attribute])}); reconcile it before any step') |
| @@ -612,6 +682,28 @@ def target_list(text): |
| return targets |
| |
| |
| +def groups_of(args): |
| + """{'80': arn, '443': arn}: both target groups, which every step watches.""" |
| + groups = {'80': args.tg_arn_80, '443': args.tg_arn_443} |
| + if groups['80'] == groups['443']: |
| + raise Refused('--tg-arn-80 and --tg-arn-443 name the same target group') |
| + return groups |
| + |
| + |
| +def check_groups(cloud, groups, nlb_arn): |
| + """Each group is attached to the NLB, on its own port.""" |
| + for port in LISTENERS: |
| + cloud.target_group(groups[port], nlb_arn, port) |
| + |
| + |
| +def health_refusals(cloud, groups, targets): |
| + """registered_refusals for every target in both groups, each naming its group.""" |
| + reasons = [] |
| + for port in LISTENERS: |
| + reasons.extend(f'in the :{port} target group, {r}' for r in registered_refusals(cloud.health(groups[port]), targets)) |
| + return reasons |
| + |
| + |
| def pending_intent(record_dir, step): |
| intent = intent_pending(record_dir, step) |
| if intent: |
| @@ -656,11 +748,13 @@ def cmd_reverify(args, cloud): |
| for d, flag in ((record_dir, '--record-dir'), (root, '--root')): |
| if not d.is_dir(): |
| raise Refused(f'{flag} {d} is not a directory') |
| + groups = groups_of(args) |
| + args.tg_arn = groups[args.port] |
| targets = target_list(args.targets) |
| paths = split(args.probe_records) |
| with locked(root, record_dir): |
| check_state_address(cloud, args) |
| - cloud.target_group(args.tg_arn, args.nlb_arn, args.port) |
| + check_groups(cloud, groups, args.nlb_arn) |
| live = cloud.attributes(args.tg_arn) |
| state = state_of(live['preserve_client_ip'], live['proxy_protocol_v2']) |
| if state != step.target: |
| @@ -715,13 +809,14 @@ def cmd_reverify(args, cloud): |
| reason = tfvars_check(doc, args.port, live) |
| if reason: |
| raise Refused(reason) |
| - reasons = registered_refusals(cloud.health(args.tg_arn), targets) |
| + reasons = health_refusals(cloud, groups, targets) |
| if reasons: |
| - raise Refused('every target must be registered and healthy: ' + '; '.join(reasons)) |
| + raise Refused('every target must be registered and healthy in both target groups: ' + '; '.join(reasons)) |
| baseline_at, baseline = collect_baseline(cloud, step, targets) |
| verified_at = cloud.clock.time() |
| verified = { |
| - 'nlb_arn': args.nlb_arn, 'port': args.port, 'step': args.step, 'tg_arn': args.tg_arn, |
| + 'nlb_arn': args.nlb_arn, 'port': args.port, 'step': args.step, 'tg_arn': args.tg_arn, 'tg_arns': groups, |
| + 'polls_anchor': iso(verified_at), 'health_from': iso(verified_at), |
| 'tg_address': args.tg_address, 'targets': targets, 'from': step.source, 'to': step.target, |
| 'baseline': baseline, 'baseline_at': iso(baseline_at), 'verified_at': iso(verified_at), |
| 'applied_at': (applied or {}).get('applied_at'), |
| @@ -743,6 +838,8 @@ def cmd_apply(args, cloud): |
| for d, flag in ((record_dir, '--record-dir'), (root, '--root')): |
| if not d.is_dir(): |
| raise Refused(f'{flag} {d} is not a directory') |
| + groups = groups_of(args) |
| + args.tg_arn = groups[args.port] |
| targets = target_list(args.targets) |
| paths = split(args.probe_records) if args.probe_records else None |
| if step.forward and not paths: |
| @@ -750,7 +847,7 @@ def cmd_apply(args, cloud): |
| 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) |
| + check_groups(cloud, groups, args.nlb_arn) |
| live = cloud.attributes(args.tg_arn) |
| reason = step_refusal(args.step, live) |
| if reason: |
| @@ -762,9 +859,9 @@ def cmd_apply(args, cloud): |
| 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) |
| + reasons = health_refusals(cloud, groups, targets) |
| if step.forward and reasons: |
| - raise Refused('every target must be registered and healthy: ' + '; '.join(reasons)) |
| + raise Refused('every target must be registered and healthy in both target groups: ' + '; '.join(reasons)) |
| baseline_at, baseline = collect_baseline(cloud, step, targets) |
| tfvars = root / TFVARS_FILE |
| try: |
| @@ -793,7 +890,7 @@ def cmd_apply(args, cloud): |
| 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, |
| + intent = {'step': args.step, 'nlb_arn': args.nlb_arn, 'port': args.port, 'tg_arn': args.tg_arn, 'tg_arns': groups, |
| '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(), |
| @@ -813,8 +910,14 @@ def cmd_apply(args, cloud): |
| # 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. |
| + # Both groups' health from here (just after the intent's started_at, |
| + # before tofu apply starts) to the verdict, every poll logged under the |
| + # intent's started_at so a resume after any interruption reads them. |
| + log = PollLog(record_dir / f'{args.step}-polls.jsonl', intent['started_at']) |
| + watch = HealthWatch(cloud, log, groups) |
| try: |
| - result = cloud.tofu(root, 'apply', '-input=false', planfile) |
| + watch.due() |
| + result = cloud.tofu(root, 'apply', '-input=false', planfile, tick=watch.due) |
| finally: |
| PHASE['name'] = 'idle' |
| remove_quietly(root / planfile) |
| @@ -829,7 +932,8 @@ def cmd_apply(args, cloud): |
| 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, |
| + 'tg_arn': args.tg_arn, 'tg_arns': groups, 'polls_anchor': intent['started_at'], |
| + 'health_from': intent['started_at'], '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) |
| @@ -839,7 +943,7 @@ def cmd_apply(args, cloud): |
| 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) |
| + return converge(cloud, record_dir, applied, paths, args.timeout, watch=watch) |
| |
| |
| def restore(path, original): |
| @@ -893,6 +997,36 @@ class PollLog: |
| return entry |
| |
| |
| +class HealthWatch: |
| + """Both target groups' health every HEALTH_EVERY seconds (spec 6.4: every |
| + target healthy in both groups from the start of the step until its record |
| + is written), each poll logged as it is made. A poll that fails is logged |
| + as an error, which leaves a gap the verdict refuses; it never raises.""" |
| + |
| + def __init__(self, cloud, log, groups): |
| + self.cloud, self.log, self.groups = cloud, log, groups |
| + self.next = cloud.clock.time() |
| + |
| + def poll(self): |
| + for port in LISTENERS: |
| + t = self.cloud.clock.time() |
| + entry = {'kind': 'health', 'port': port, 'tg_arn': self.groups[port], 'at': iso(t)} |
| + try: |
| + entry['health'] = self.cloud.health(self.groups[port]) |
| + except Refused as err: |
| + entry['error'] = str(err) |
| + except Exception as err: # an observation missed, not a crash mid-apply |
| + entry['error'] = f'{type(err).__name__}: {one_line(err)}' |
| + self.log.add(entry) |
| + |
| + def due(self): |
| + """Health keeps its own 10 s schedule through every wait, until the record is written.""" |
| + now = self.cloud.clock.time() |
| + if now >= self.next: |
| + self.poll() |
| + self.next = now + HEALTH_EVERY |
| + |
| + |
| class TrustJob: |
| """One trust-status poll that does not block the health schedule.""" |
| |
| @@ -943,8 +1077,9 @@ def probes_ready(paths, clock): |
| 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.""" |
| +def converge(cloud, record_dir, applied, paths, timeout, watch=None): |
| + """Polls until the probe records are in, then writes <step>.json. Returns the exit code. |
| + watch is apply's HealthWatch, kept on its schedule; a resume makes its own.""" |
| step, clock = applied['step'], cloud.clock |
| prereq = prereq_for(record_dir, applied['nlb_arn']) |
| if len(paths) != len(prereq['public_addresses']): |
| @@ -954,15 +1089,13 @@ def converge(cloud, record_dir, applied, paths, timeout): |
| prior = load_record(record_dir / f'{step}.json') |
| if prior and record_anchor(prior) == anchor and prior.get('passed') is True: |
| raise Refused(f'{step}.json already passed for the {anchor_kind(applied)} at {anchor}; nothing to resume') |
| - log = PollLog(record_dir / f'{step}-polls.jsonl', anchor) |
| + groups = applied.get('tg_arns') or {} |
| + if set(groups) != set(LISTENERS) or groups.get(applied['port']) != applied['tg_arn']: |
| + raise Refused(f"the {anchor_kind(applied)} record of {step} does not name both target groups; " |
| + 'reverify the step with this version') |
| + log = PollLog(record_dir / f'{step}-polls.jsonl', applied.get('polls_anchor') or anchor) |
| 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)}) |
| + watch = watch or HealthWatch(cloud, log, groups) |
| |
| def poll_state(): |
| t = clock.time() |
| @@ -973,14 +1106,7 @@ def converge(cloud, record_dir, applied, paths, timeout): |
| log.add({'kind': 'state', 'at': iso(t), 'error': str(err)}) |
| |
| deadline = clock.time() + timeout |
| - schedule = {'health': clock.time()} |
| - |
| - def health_due(): |
| - """Health keeps its own 10 s schedule through every wait, until the record is written.""" |
| - now = clock.time() |
| - if now >= schedule['health']: |
| - poll_health() |
| - schedule['health'] = now + HEALTH_EVERY |
| + health_due = watch.due |
| |
| def log_trust(job): |
| """Logs a trust poll with any S3 signal it shows against this run's |
| @@ -1015,7 +1141,7 @@ def converge(cloud, record_dir, applied, paths, timeout): |
| break |
| health_due() |
| poll_state() |
| - poll_health() |
| + watch.poll() |
| 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') |
| @@ -1031,8 +1157,8 @@ def converge(cloud, record_dir, applied, paths, timeout): |
| record = dict(summary, nlb_arn=applied['nlb_arn'], port=applied['port'], step=step, tg_arn=applied['tg_arn'], |
| applied_at=applied.get('applied_at'), verified_at=applied.get('verified_at'), |
| converged_at=iso(clock.time()), passed=passed, reasons=reasons, history=history, |
| - targets=targets, polls=log.path.name, |
| - proxied_scope='proxied_by_node sums both listeners (:80 and :443)') |
| + targets=targets, polls=log.path.name, tg_arns=groups, |
| + proxied_scope=f"B steps converge on by_listener[{applied['port']}].proxied_by_node: the changed port only") |
| write_record(record_dir / f'{step}.json', record) |
| if passed: |
| print(f'{step} converged; {step}.json passed') |
| @@ -1175,7 +1301,36 @@ def continuous_reasons(times, start, end, gap, what, start_label): |
| return reasons |
| |
| |
| -def trust_findings(status, base, iid, step): |
| +def counts_of(status): |
| + """Every count in a status line that only rises while one edge runs: the |
| + sums, each listener's, and each node's proxied count, sum and per listener.""" |
| + out = {(None, c): status['counters'][c] for c in COUNTERS} |
| + out.update({(None, 'node ' + n): v for n, v in status['proxied_by_node'].items()}) |
| + for port, listener in (status.get('by_listener') or {}).items(): |
| + out.update({(port, c): listener[c] for c in COUNTERS}) |
| + out.update({(port, 'node ' + n): v for n, v in listener['proxied_by_node'].items()}) |
| + return out |
| + |
| + |
| +def restart_reasons(iid, before, now, since): |
| + """The edge restarted between two status lines: another edge_instance, or |
| + any count lower than before (a reset to zero that has not caught up).""" |
| + if before.get('edge_instance') != now.get('edge_instance'): |
| + return [f"{iid}: edge_instance changed from {before.get('edge_instance')} to {now.get('edge_instance')} " |
| + f'since {since}: the edge restarted during the step'] |
| + reasons, got = [], counts_of(now) |
| + for (port, name), was in counts_of(before).items(): |
| + if got.get((port, name), 0) < was: |
| + label = f'proxied from {name}' if name.startswith('node ') else name |
| + where = '' if port is None else f' on :{port}' |
| + reasons.append(f'{iid}: {label}{where} fell from {was} to {got.get((port, name), 0)} since {since}: ' |
| + 'the edge restarted during the step') |
| + return reasons |
| + |
| + |
| +def trust_findings(status, base, prev, iid, step): |
| + """One poll's findings for one target, against the run's baseline and the |
| + target's previous status line in this run (prev: (at, status) or None).""" |
| if isinstance(status, str): |
| return [] # no answer at all (SSM): not an observation; the final poll must have one |
| reasons = [] |
| @@ -1187,18 +1342,26 @@ def trust_findings(status, base, iid, step): |
| reasons.append(f'{iid}: barrier is up') |
| if not is_status(status): |
| return reasons |
| + if prev is not None: |
| + reasons.extend(restart_reasons(iid, prev[1], status, f'the poll at {prev[0]}')) |
| if not is_status(base): |
| 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') |
| + reasons.extend(restart_reasons(iid, base, status, 'the baseline')) |
| + port = STEPS[step].port |
| + was_l, now_l = listener_of(base, port), listener_of(status, port) |
| 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 was_l and now_l and now_l[counter] > was_l[counter]: |
| + reasons.append(f'{iid}: {counter} on :{port}, the changed port, moved from {was_l[counter]} to {now_l[counter]}') |
| return reasons |
| |
| |
| +def listener_of(status, port): |
| + """A status line's counts for one listener; None for a line without it (not armed).""" |
| + return (status.get('by_listener') or {}).get(port) |
| + |
| + |
| def evaluate(step, applied, polls, docs, prereq, prior, published): |
| """(reasons, summary): the whole verdict, from the apply, every poll and the probe |
| records, for a record written at `published`.""" |
| @@ -1211,23 +1374,34 @@ def evaluate(step, applied, polls, docs, prereq, prior, published): |
| 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'] |
| + trust = sorted((p for p in polls if p['kind'] == 'trust'), key=lambda p: p['at']) |
| 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)) |
| - health_times = [epoch(p['at']) for p in health if 'health' in p] |
| - reasons.extend(coverage_reasons(health_times, window, HEALTH_GAP_MAX, 'target health')) |
| - # And all along, from the apply (or reverify) to this record (spec 6.4: |
| - # every target healthy from the start of the step until its record is written). |
| - anchor = epoch(record_anchor(applied)) |
| - if anchor is not None: |
| - reasons.extend(continuous_reasons(health_times, anchor, published, HEALTH_GAP_MAX, 'target health', |
| - anchor_kind(applied))) |
| + # Both target groups, every target healthy at every poll and observed all |
| + # along, from the start of the step (the intent's started_at, before tofu |
| + # apply; or the reverify) until this record (spec 6.4). |
| + start = epoch(applied.get('health_from') or record_anchor(applied)) |
| + groups = applied.get('tg_arns') or {} |
| + for port in LISTENERS: |
| + mine = [p for p in health if p.get('port') == port and p.get('tg_arn') == groups.get(port)] |
| + for poll in mine: |
| + if 'health' in poll: |
| + reasons.extend(f"health poll of the :{port} target group at {poll['at']}: {r}" |
| + for r in registered_refusals(poll['health'], targets)) |
| + times = [epoch(p['at']) for p in mine if 'health' in p] |
| + what = f'target health in the :{port} target group' |
| + reasons.extend(coverage_reasons(times, window, HEALTH_GAP_MAX, what)) |
| + if start is not None: |
| + reasons.extend(continuous_reasons(times, start, published, HEALTH_GAP_MAX, what, anchor_kind(applied))) |
| + # Every poll against the baseline and against the target's previous poll: |
| + # an edge restart (another edge_instance, or a count that fell) fails the step. |
| + prev = {} |
| for poll in trust: |
| for iid in targets: |
| - for r in trust_findings(poll['status'].get(iid, ''), baseline.get(iid), iid, step): |
| + status = poll['status'].get(iid, '') |
| + for r in trust_findings(status, baseline.get(iid), prev.get(iid), iid, step): |
| reasons.append(f"trust poll at {poll['at']}: {r}") |
| + if is_status(status): |
| + prev[iid] = (poll['at'], status) |
| complete = [p for p in trust if all(is_status(p['status'].get(i)) for i in targets)] |
| trust_times = [epoch(p['at']) for p in complete] |
| if all(is_status(baseline.get(i)) for i in targets) and applied.get('baseline_at'): |
| @@ -1239,14 +1413,21 @@ def evaluate(step, applied, polls, docs, prereq, prior, published): |
| 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: |
| + # The changed port's own listener: after B80, :80 traffic must not |
| + # stand in for a B443 that has not converged. |
| + port = STEPS[step].port |
| for iid in targets: |
| status, base = final['status'].get(iid), baseline.get(iid) |
| if not is_status(status) or not is_status(base): |
| continue |
| + if not listener_of(base, port) or not listener_of(status, port): |
| + reasons.append(f'{iid}: no :{port} listener counts to converge on') |
| + continue |
| + was_by, now_by = listener_of(base, port)['proxied_by_node'], listener_of(status, port)['proxied_by_node'] |
| for node in prereq['sources']: |
| - was, now = base['proxied_by_node'].get(node, 0), status['proxied_by_node'].get(node, 0) |
| + was, now = was_by.get(node, 0), now_by.get(node, 0) |
| if now <= was: |
| - reasons.append(f'{iid}: proxied from node {node} did not rise ({was} to {now})') |
| + reasons.append(f'{iid}: proxied on :{port} 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')}") |
| @@ -1257,6 +1438,7 @@ def evaluate(step, applied, polls, docs, prereq, prior, published): |
| # incident procedure first. Earlier runs' signals carry forward. |
| s3_signal = any(re.search(r': (marker_trusted|no_client_refused) moved ', r) for r in unique) |
| summary = {'s3_signal': s3_signal, 'probes': probes, 'health_polls': len(health), 'trust_polls': len(trust), |
| + 'health_from': applied.get('health_from') or record_anchor(applied), |
| 'window': [iso(window[0]), iso(window[1])] if window else None, |
| 'clock_tolerance_s': CLOCK_TOLERANCE, |
| 'clock_tolerance': 'span checks only: probe-host times against this host\'s polls; ' |
| @@ -1268,6 +1450,7 @@ def cmd_converge(args, cloud): |
| record_dir = Path(args.record_dir) |
| paths = split(args.probe_records) |
| targets = target_list(args.targets) |
| + groups = groups_of(args) |
| with locked(record_dir): |
| # The latest of the step's apply and reverify: that is what a resume continues. |
| candidates = [r for r in (load_record(record_dir / f'{args.step}-applied.json'), |
| @@ -1275,8 +1458,8 @@ def cmd_converge(args, cloud): |
| applied = max(candidates, key=lambda r: epoch(record_anchor(r)) or 0) if candidates else None |
| if applied is None: |
| raise Refused(f'no {args.step}-applied.json or {args.step}-verified.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 applied.get('step') != args.step or applied.get('tg_arns') != groups: |
| + raise Refused(f'{args.step}-applied.json is for {applied.get("step")} on {applied.get("tg_arns")}') |
| 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') |
| @@ -1328,6 +1511,14 @@ def cmd_prereq(args, cloud): |
| 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)}") |
| + # The installed guard binary: guard-arm copies it, app updates do not |
| + # refresh it, and an old one's guard-exec recover has no PPv2 gate. |
| + guards = {} |
| + for iid, (code, stdout, stderr) in cloud.ssm(targets, GUARD_CHECK).items(): |
| + guards[iid] = one_line(stdout or stderr)[:300] |
| + reason = guard_refusal(iid, code, stdout, stderr) |
| + if reason: |
| + reasons.append(reason) |
| 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: |
| @@ -1340,7 +1531,7 @@ def cmd_prereq(args, cloud): |
| '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}) |
| + 'reasons': reasons, 'trust_status': status, 'armed_lines': lines, 'guard_binaries': guards}) |
| owed = '; '.join(MANUAL_PREREQUISITES) |
| if passed: |
| print(f'automated prerequisite checks passed (automated checks only); prereq.json written. ' |
| @@ -1352,14 +1543,77 @@ def cmd_prereq(args, cloud): |
| return 1 |
| |
| |
| +def guard_refusal(iid, code, stdout, stderr): |
| + """Why the installed guard binary on iid would let a pre-vN predecessor |
| + run (it does not report ingress-proxy-v2), or None (absent, or it does).""" |
| + text = (stdout or '').strip() |
| + if code == 0 and text == GUARD_ABSENT: |
| + return None |
| + if code == 0: |
| + doc = first_json(text, 'features') |
| + if doc and isinstance(doc.get('features'), list) and FEATURE in doc['features']: |
| + return None |
| + said = one_line(text or stderr)[:200] or f'exit {code}' |
| + return (f'{iid}: the installed guard binary {GUARD_BINARY} does not report {FEATURE} ({said}); ' |
| + 'app updates do not refresh it, so its guard-exec recover has no PPv2 gate. Bring it to vN or later ' |
| + 'on this box before the key is published') |
| + |
| + |
| +def cmd_sync_tfvars(args, cloud): |
| + """Rewrite ppv2.auto.tfvars.json to both target groups' live attributes, |
| + after a direct change outside this tool (the S3 incident procedure's |
| + preservation-on command). Never writes S3.""" |
| + 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') |
| + groups = groups_of(args) |
| + with locked(root, record_dir): |
| + check_groups(cloud, groups, args.nlb_arn) |
| + live, states = {}, {} |
| + for port in LISTENERS: |
| + live[port] = cloud.attributes(groups[port]) |
| + states[port] = state_of(live[port]['preserve_client_ip'], live[port]['proxy_protocol_v2']) |
| + if states[port] == 'S3': |
| + raise Refused(f'the :{port} target group is in S3 (forbidden); {TFVARS_FILE} is never written with ' |
| + 'S3. Run the S3 incident procedure (spec 6.5) first') |
| + 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_shape(doc) |
| + if reason: |
| + raise Refused(reason + '; fix its shape by hand') |
| + new = {key: {port: live[port][attribute] for port in LISTENERS} for attribute, key in TFVARS_KEY.items()} |
| + for port in LISTENERS: |
| + if state_of(new[TFVARS_KEY['preserve_client_ip']][port], new[TFVARS_KEY['proxy_protocol_v2']][port]) == 'S3': |
| + raise Refused(f'{TFVARS_FILE} would describe S3 on :{port}; not written') |
| + changes = [f'{key}["{port}"] {norm(doc[key][port])} to {norm(new[key][port])}' |
| + for key in sorted(new) for port in LISTENERS if doc[key][port] != new[key][port]] |
| + if not changes: |
| + print(f'{TFVARS_FILE} already matches the live target groups (:80 {states["80"]}, :443 {states["443"]}); ' |
| + 'nothing written') |
| + return 0 |
| + edited = (json.dumps(new, indent=2) + '\n').encode() |
| + synced_at = iso(cloud.clock.time()) |
| + write_record(record_dir / f"sync-tfvars-{re.sub(r'[^0-9]', '', synced_at)}.json", { |
| + 'nlb_arn': args.nlb_arn, 'tg_arns': groups, 'synced_at': synced_at, 'live': states, 'changes': changes, |
| + 'tfvars_before': original.decode(), 'tfvars_after': edited.decode()}) |
| + atomic_write(tfvars, edited) |
| + print(f'{TFVARS_FILE} now matches the live target groups (:80 {states["80"]}, :443 {states["443"]}): ' |
| + + '; '.join(changes)) |
| + return 0 |
| + |
| + |
| 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, 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) |
| - a.add_argument('--tg-address', required=True, help='the target group\'s tofu address') |
| + a.add_argument('--tg-address', required=True, help='the stepped target group\'s tofu address') |
| 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) |
| @@ -1369,12 +1623,10 @@ def parser(): |
| c.add_argument('--step', required=True, choices=list(STEPS)) |
| c.add_argument('--record-dir', required=True) |
| c.add_argument('--probe-records', required=True, help='one probe record path per NLB address, comma-separated') |
| - c.add_argument('--tg-arn', required=True) |
| v = sub.add_parser('reverify', help='a fresh convergence window for a step already made') |
| v.add_argument('--root', required=True, help='the tofu root directory holding ppv2.auto.tfvars.json') |
| v.add_argument('--nlb-arn', required=True) |
| - v.add_argument('--tg-arn', required=True) |
| - v.add_argument('--tg-address', required=True, help='the target group\'s tofu address') |
| + v.add_argument('--tg-address', required=True, help='the stepped target group\'s tofu address') |
| v.add_argument('--port', required=True, choices=['80', '443']) |
| v.add_argument('--step', required=True, choices=list(STEPS)) |
| v.add_argument('--record-dir', required=True) |
| @@ -1383,6 +1635,16 @@ def parser(): |
| help='the S3 incident procedure has been run for an S3 signal this step recorded') |
| for s in (a, c, v): |
| s.add_argument('--timeout', type=float, default=1800.0, help='seconds to wait for the probe records') |
| + s.add_argument('--tg-arn-80', required=True, help='the :80 target group (watched in every step)') |
| + s.add_argument('--tg-arn-443', required=True, help='the :443 target group (watched in every step)') |
| + y = sub.add_parser('sync-tfvars', help='rewrite ppv2.auto.tfvars.json to the live attributes (after an incident)') |
| + y.add_argument('--root', required=True, help='the tofu root directory holding ppv2.auto.tfvars.json') |
| + y.add_argument('--nlb-arn', required=True) |
| + y.add_argument('--tg-arn-80', required=True) |
| + y.add_argument('--tg-arn-443', required=True) |
| + y.add_argument('--record-dir', required=True) |
| + y.add_argument('--profile', required=True) |
| + y.add_argument('--region', required=True) |
| 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) |
| @@ -1409,6 +1671,8 @@ def main(argv=None): |
| return cmd_converge(args, cloud) |
| if args.command == 'reverify': |
| return cmd_reverify(args, cloud) |
| + if args.command == 'sync-tfvars': |
| + return cmd_sync_tfvars(args, cloud) |
| return cmd_prereq(args, cloud) |
| except Refused as err: |
| print(f'refused: {one_line(err)}', file=sys.stderr) |