| index dc4ce944c..83ad1bfc2 100755 |
| --- a/scripts/ppv2-step.py |
| +++ b/scripts/ppv2-step.py |
| @@ -32,8 +32,12 @@ them changes PPv2 while preservation is off, so no node can pass through S3. |
| applied_at) and a new <step>.json; earlier verdicts stay in its |
| history. After a failed convergence this is the way on (A steps |
| cannot be undone); after a tofu apply that failed once it had |
| - changed the attribute, it adopts <step>-intent.json. Each step |
| - binds to the latest of its predecessor's apply and reverify. |
| + changed the attribute, it adopts <step>-intent.json. It keeps |
| + the step's own targets, and refuses after an S3 signal |
| + (marker_trusted or no_client_refused moved) unless given |
| + --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. |
| |
| Steps: A80, A443 (PPv2 on), B80, B443 (preservation off), R443, R80 |
| (preservation back on). Nothing turns PPv2 off; there is no step for it. |
| @@ -271,15 +275,27 @@ def parse_trust(text): |
| |
| |
| def trust_of(iid, code, stdout, stderr): |
| - """A target's trust-status answer as a dict, or a string saying why there is none.""" |
| + """A target's trust-status answer: the status line (a dict with counters); |
| + {'armed': False, 'detail': ...} when the box says it is not armed (exit 2), |
| + which is an observation, not a missing one; or a string saying why there |
| + is no answer at all (an SSM or parse failure).""" |
| if code == 2: |
| - return f'{iid} is not armed: {one_line(stderr)}' |
| + return {'armed': False, 'detail': 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 is_status(s): |
| + """A full trust-status line (armed or not, with counters).""" |
| + return isinstance(s, dict) and 'counters' in s |
| + |
| + |
| +def is_unarmed(s): |
| + return isinstance(s, dict) and s.get('armed') is False |
| + |
| + |
| def first_json(stdout, key): |
| """The JSON document in stdout carrying key: the whole output, or one of its lines.""" |
| try: |
| @@ -491,6 +507,13 @@ def record_refusal(name, record_dir, nlb_arn): |
| if latest is None or record_anchor(latest) != record_anchor(record): |
| return (f"{name}.json is not for its latest apply or reverify (latest {record_anchor(latest or {})}, " |
| f"{name}.json {record_anchor(record)})") |
| + # An apply of that step that started after its evidence and wrote no |
| + # -applied.json may have changed the attribute: the evidence is stale |
| + # until a reverify of that step passes. |
| + intent = intent_pending(record_dir, name) |
| + if intent and intent.get('nlb_arn') == nlb_arn and (epoch(intent.get('started_at')) or 0) > (epoch(record_anchor(record)) or 0): |
| + return (f"{name}-intent.json records an apply of {name} started at {intent.get('started_at')}, newer than " |
| + f"{name}.json; reverify {name} first") |
| return None |
| |
| |
| @@ -614,7 +637,7 @@ def collect_baseline(cloud, step, targets): |
| if isinstance(status, str): |
| raise Refused(status) |
| if not status['armed']: |
| - raise Refused(f'{iid} is not armed') |
| + raise Refused(status.get('detail') or 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': |
| @@ -649,16 +672,37 @@ def cmd_reverify(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)})') |
| - made = {'nlb_arn': args.nlb_arn, 'port': args.port, 'tg_arn': args.tg_arn} |
| - applied = load_record(record_dir / f'{args.step}-applied.json') |
| - if applied and any(applied.get(k) != v for k, v in made.items()): |
| - applied = None |
| + made = {'nlb_arn': args.nlb_arn, 'port': args.port, 'tg_arn': args.tg_arn, 'step': args.step} |
| intent = intent_pending(record_dir, args.step) |
| - if intent and any(intent.get(k) != v for k, v in dict(made, step=args.step).items()): |
| + if intent and any(intent.get(k) != v for k, v in made.items()): |
| raise Refused(f'{args.step}-intent.json is not for this step and target group; reconcile it by hand') |
| - if not applied and not intent: |
| - raise Refused(f'nothing to reverify: no {args.step}-applied.json or {args.step}-intent.json for ' |
| - 'this target group') |
| + # What the step was made with: its apply, an earlier reverify (which may |
| + # itself have adopted an intent), or a pending intent. The latest is the basis. |
| + basis = {} |
| + for kind, record in (('applied', load_record(record_dir / f'{args.step}-applied.json')), |
| + ('verified', load_record(record_dir / f'{args.step}-verified.json')), |
| + ('intent', intent)): |
| + if record and all(record.get(k) == v for k, v in made.items()): |
| + basis[kind] = record |
| + if not basis: |
| + raise Refused(f'nothing to reverify: no {args.step}-applied.json, {args.step}-verified.json or ' |
| + f'{args.step}-intent.json for this target group') |
| + when = lambda r: epoch(r.get('started_at') if r is intent else record_anchor(r)) or 0 |
| + latest = max(basis.values(), key=when) |
| + # The step's targets are the ones it was made with; none may leave it unobserved. |
| + made_with = latest.get('targets') |
| + if not made_with: |
| + raise Refused(f'the latest record of {args.step} names no targets; reverify cannot tell what to observe') |
| + if sorted(targets) != sorted(made_with): |
| + raise Refused(f"--targets must be the step's targets ({', '.join(made_with)}); a target cannot leave " |
| + 'a step before it converges') |
| + # A trust-violation signal in this step's evidence is S3 on some node (spec 6.4). |
| + prior = load_record(record_dir / f'{args.step}.json') or {} |
| + signals = [h for h in [prior] + list(prior.get('history') or []) if h.get('s3_signal')] |
| + if signals and not args.incident_cleared: |
| + raise Refused(f'{args.step}.json records an S3 signal (marker_trusted or no_client_refused moved); ' |
| + 'run the S3 incident procedure (runbook) first, then reverify with --incident-cleared') |
| + applied = basis.get('applied') |
| try: |
| doc = json.loads((root / TFVARS_FILE).read_bytes()) |
| except (OSError, ValueError) as err: |
| @@ -676,8 +720,9 @@ def cmd_reverify(args, cloud): |
| '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'), |
| - 'intent_started_at': intent['started_at'] if intent else (applied or {}).get('intent_started_at'), |
| - 'adopted_intent': bool(intent)} |
| + 'intent_started_at': intent['started_at'] if intent else latest.get('intent_started_at'), |
| + 'adopted_intent': bool(intent) or bool(latest.get('adopted_intent')), |
| + 'incident_cleared': bool(signals) and args.incident_cleared} |
| write_record(record_dir / f'{args.step}-verified.json', verified) |
| print(f'{args.step} reverify started at {iso(verified_at)}' |
| f"{' (adopting ' + args.step + '-intent.json)' if intent else ''}: the target group is in {step.target}.") |
| @@ -746,7 +791,8 @@ def cmd_apply(args, cloud): |
| 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()} |
| + 'planfile': planfile, 'tfvars_before': original.decode(), 'tfvars_after': edited.decode(), |
| + 'targets': targets, 'baseline': baseline, 'baseline_at': iso(baseline_at)} |
| write_record(intent_path, intent) |
| PHASE['name'] = 'apply' |
| except BaseException as err: |
| @@ -804,7 +850,7 @@ def supersede(record_dir, forward, applied_at): |
| if not forward: |
| return |
| stamp = re.sub(r'[^0-9]', '', applied_at) |
| - for name in (f'{forward}.json', f'{forward}-applied.json', f'{forward}-verified.json'): |
| + for name in (f'{forward}.json', f'{forward}-applied.json', f'{forward}-verified.json', f'{forward}-intent.json'): |
| path = record_dir / name |
| if path.exists(): |
| os.replace(path, record_dir / name.replace('.json', f'.superseded-{stamp}.json')) |
| @@ -922,15 +968,21 @@ def converge(cloud, record_dir, applied, paths, timeout): |
| log.add({'kind': 'state', 'at': iso(t), 'error': str(err)}) |
| |
| deadline = clock.time() + timeout |
| - next_health = next_trust = clock.time() |
| + 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 |
| + |
| + 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: |
| + health_due() |
| + if job is None and clock.time() >= next_trust: |
| job = TrustJob(cloud, targets) |
| if job is not None and job.check(): |
| log.add(job.entry()) |
| @@ -938,27 +990,32 @@ def converge(cloud, record_dir, applied, paths, timeout): |
| 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() |
| + # The last look, after the probes finished: the counters (retried while |
| + # SSM gives no answer, since this one is required) and the target group's |
| + # state, with health still on its schedule, then health once more. |
| for _ in range(3): |
| job = TrustJob(cloud, targets) |
| while not job.check(): |
| - clock.sleep(2) |
| + health_due() |
| + clock.sleep(TICK) |
| entry = log.add(job.entry()) |
| - if all(isinstance(s, dict) for s in entry['status'].values()): |
| + if not any(isinstance(s, str) for s in entry['status'].values()): |
| break |
| + health_due() |
| poll_state() |
| + poll_health() |
| 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) |
| + published = clock.time() |
| + reasons, summary = evaluate(step, applied, log.read(), load_probes(paths), prereq, prior, published) |
| passed = not reasons |
| # Earlier verdicts for this step (earlier applies or reverifies) are kept, |
| # never cleared; only this anchor's full window decides `passed`. |
| history = list((prior or {}).get('history') or []) |
| if prior and record_anchor(prior) != anchor: |
| - history.append({k: prior.get(k) for k in ('applied_at', 'verified_at', 'converged_at', 'passed', 'reasons')}) |
| + history.append({k: prior.get(k) for k in ('applied_at', 'verified_at', 'converged_at', 'passed', 'reasons', |
| + 's3_signal')}) |
| 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, |
| @@ -1055,15 +1112,38 @@ def coverage_reasons(times, window, gap, what): |
| return reasons |
| |
| |
| +def continuous_reasons(times, start, end, gap, what, start_label): |
| + """Observations (this host's clock) from start to end, never more than gap apart.""" |
| + points = sorted(t for t in times if start <= t <= end) |
| + reasons = [] |
| + edges = [start] + points + [end] |
| + for i, (a, b) in enumerate(zip(edges, edges[1:])): |
| + if b - a > gap: |
| + if i == 0: |
| + reasons.append(f'{what} was not observed for {b - a:.0f} s after the {start_label} at {iso(a)} ' |
| + f'(at most {gap:g} s allowed)') |
| + elif i == len(edges) - 2: |
| + reasons.append(f'{what} was not observed in the last {b - a:.0f} s before the record was written ' |
| + f'(from {iso(a)}; at most {gap:g} s allowed)') |
| + else: |
| + 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(status, base, iid, step): |
| if isinstance(status, str): |
| - return [] |
| + return [] # no answer at all (SSM): not an observation; the final poll must have one |
| reasons = [] |
| - if not status['armed']: |
| - reasons.append(f'{iid} is not armed') |
| - if status['barrier'] and step.startswith('B'): |
| + # A box that says it is not armed, at any poll, fails A and B steps; only |
| + # reverse steps keep their exception (rollback is the safe direction). |
| + if not status['armed'] and not step.startswith('R'): |
| + reasons.append(status.get('detail') or f'{iid} is not armed') |
| + if status.get('barrier') and step.startswith('B'): |
| reasons.append(f'{iid}: barrier is up') |
| - if not isinstance(base, dict): |
| + if not is_status(status): |
| + return reasons |
| + 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]: |
| @@ -1075,8 +1155,9 @@ def trust_findings(status, base, iid, step): |
| return reasons |
| |
| |
| -def evaluate(step, applied, polls, docs, prereq, prior): |
| - """(reasons, summary): the whole verdict, from the apply, every poll and the probe records.""" |
| +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`.""" |
| reasons = [] |
| if prior and record_anchor(prior) == record_anchor(applied) 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 []) |
| @@ -1091,14 +1172,21 @@ def evaluate(step, applied, polls, docs, prereq, prior): |
| 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')) |
| + 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))) |
| 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)] |
| + 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(isinstance(baseline.get(i), dict) for i in targets) and applied.get('baseline_at'): |
| + if all(is_status(baseline.get(i)) 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 |
| @@ -1109,7 +1197,7 @@ def evaluate(step, applied, polls, docs, prereq, prior): |
| 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): |
| + if not is_status(status) or not is_status(base): |
| continue |
| for node in prereq['sources']: |
| was, now = base['proxied_by_node'].get(node, 0), status['proxied_by_node'].get(node, 0) |
| @@ -1121,7 +1209,10 @@ def evaluate(step, applied, polls, docs, prereq, prior): |
| 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), |
| + # A rise of either is S3 on some node (spec 6.4): a reverify then needs the |
| + # 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), |
| '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; ' |
| @@ -1244,6 +1335,8 @@ def parser(): |
| v.add_argument('--step', required=True, choices=list(STEPS)) |
| v.add_argument('--record-dir', required=True) |
| v.add_argument('--probe-records', required=True, help='one probe record path per NLB address, comma-separated') |
| + v.add_argument('--incident-cleared', action='store_true', |
| + 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') |
| r = sub.add_parser('prereq', help='the automated prerequisite checks; writes prereq.json') |