| index 244de4507..dc4ce944c 100755 |
| --- a/scripts/ppv2-step.py |
| +++ b/scripts/ppv2-step.py |
| @@ -23,9 +23,17 @@ them changes PPv2 while preservation is off, so no node can pass through S3. |
| 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. |
| + 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. |
| + reverify a full fresh convergence window for a step already made: the |
| + target group must already be in the step's target state. It |
| + writes <step>-verified.json (verified_at plays the part of |
| + 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. |
| |
| Steps: A80, A443 (PPv2 on), B80, B443 (preservation off), R443, R80 |
| (preservation back on). Nothing turns PPv2 off; there is no step for it. |
| @@ -36,8 +44,8 @@ in the root directory, which this script owns: |
| "ppv2_proxy_protocol_v2":{"80":false,"443":false}} |
| |
| 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 |
| +tofu apply starts), <step>-applied.json, <step>-verified.json (reverify), |
| +<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, |
| @@ -99,6 +107,8 @@ HEALTH_EVERY = 10.0 |
| # 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 |
| +# The probe host's clock against this host's, in the span checks only. |
| +CLOCK_TOLERANCE = 5.0 |
| TRUST_EVERY = 30.0 |
| SSM_BOUND = 120.0 |
| TICK = 1.0 |
| @@ -477,13 +487,42 @@ def record_refusal(name, record_dir, nlb_arn): |
| 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')})") |
| + latest = latest_anchor(record_dir, name, 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)})") |
| return None |
| |
| |
| +def record_anchor(record): |
| + """The moment a record's evidence counts from: its reverify, else its apply.""" |
| + return record.get('verified_at') or record.get('applied_at') |
| + |
| + |
| +def anchor_kind(record): |
| + return 'reverify' if record.get('verified_at') else 'apply' |
| + |
| + |
| +def latest_anchor(record_dir, step, nlb_arn): |
| + """The later of <step>-applied.json and <step>-verified.json for this NLB, or None.""" |
| + found = [r for r in (load_record(record_dir / f'{step}-applied.json'), |
| + load_record(record_dir / f'{step}-verified.json')) |
| + if r and r.get('nlb_arn') == nlb_arn and record_anchor(r)] |
| + return max(found, key=lambda r: epoch(record_anchor(r)) or 0) if found else None |
| + |
| + |
| +def intent_pending(record_dir, step): |
| + """<step>-intent.json when no apply or reverify record has taken it up yet.""" |
| + intent = load_record(record_dir / f'{step}-intent.json') |
| + if not intent: |
| + return None |
| + for name in (f'{step}-applied.json', f'{step}-verified.json'): |
| + record = load_record(record_dir / name) |
| + if record and record.get('intent_started_at') == intent.get('started_at'): |
| + return None |
| + return intent |
| + |
| + |
| 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] |
| @@ -551,14 +590,101 @@ def target_list(text): |
| |
| |
| 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')): |
| + intent = intent_pending(record_dir, step) |
| + if intent: |
| 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)') |
| + f'{step}-applied.json; see its tfvars_before, or adopt it with reverify if the live attribute changed)') |
| return '' |
| |
| |
| +def collect_baseline(cloud, step, targets): |
| + """(time, {instance: trust-status or why none}), refused by the step kind's rules: |
| + A and B need every target armed, B also every barrier down; R refuses nothing.""" |
| + 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)') |
| + return baseline_at, baseline |
| + |
| + |
| +def cmd_reverify(args, cloud): |
| + """A fresh observation window for a step already made: the target group is |
| + in the step's target state, and its latest evidence failed or is missing |
| + (or tofu apply failed after it changed the attribute, and this adopts it).""" |
| + 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, 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) |
| + with locked(root, record_dir): |
| + check_state_address(cloud, args) |
| + cloud.target_group(args.tg_arn, args.nlb_arn, args.port) |
| + live = cloud.attributes(args.tg_arn) |
| + state = state_of(live['preserve_client_ip'], live['proxy_protocol_v2']) |
| + if state != step.target: |
| + raise Refused(f'reverify {args.step}: the target group is in {state}, not {step.target}; ' |
| + 'reverify only observes a step already made') |
| + reason = chain_refusal(args.step, record_dir, args.nlb_arn) |
| + if reason: |
| + raise Refused(reason) |
| + 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 |
| + 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()): |
| + 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') |
| + try: |
| + doc = json.loads((root / TFVARS_FILE).read_bytes()) |
| + except (OSError, ValueError) as err: |
| + raise Refused(f'cannot read {root / TFVARS_FILE}: {err}') |
| + reason = tfvars_check(doc, args.port, live) |
| + if reason: |
| + raise Refused(reason) |
| + reasons = registered_refusals(cloud.health(args.tg_arn), targets) |
| + if reasons: |
| + raise Refused('every target must be registered and healthy: ' + '; '.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, |
| + '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)} |
| + 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}.") |
| + print(f'Converging: start the probes on {len(paths)} NLB addresses now; waiting for {", ".join(paths)}.') |
| + return converge(cloud, record_dir, verified, paths, args.timeout) |
| + |
| + |
| def cmd_apply(args, cloud): |
| step = STEPS[args.step] |
| if step.port != args.port: |
| @@ -589,25 +715,7 @@ def cmd_apply(args, cloud): |
| 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)') |
| + baseline_at, baseline = collect_baseline(cloud, step, targets) |
| tfvars = root / TFVARS_FILE |
| try: |
| original = tfvars.read_bytes() |
| @@ -696,18 +804,19 @@ 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'): |
| + for name in (f'{forward}.json', f'{forward}-applied.json', f'{forward}-verified.json'): |
| path = record_dir / name |
| if path.exists(): |
| os.replace(path, record_dir / name.replace('.json', f'.superseded-{stamp}.json')) |
| |
| |
| 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.""" |
| + """Every observation for one apply or reverify (its anchor), 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 __init__(self, path, anchor): |
| + self.path, self.anchor = path, anchor |
| |
| def read(self): |
| try: |
| @@ -720,12 +829,12 @@ class PollLog: |
| entry = json.loads(line) |
| except ValueError: |
| continue # a line cut short by a kill |
| - if entry.get('applied_at') == self.applied_at: |
| + if entry.get('anchor') == self.anchor: |
| out.append(entry) |
| return out |
| |
| def add(self, entry): |
| - entry = dict(entry, applied_at=self.applied_at) |
| + entry = dict(entry, anchor=self.anchor) |
| with open(self.path, 'a') as f: |
| f.write(json.dumps(entry, sort_keys=True) + '\n') |
| f.flush() |
| @@ -790,10 +899,11 @@ def converge(cloud, record_dir, applied, paths, timeout): |
| 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'])})") |
| + anchor = record_anchor(applied) |
| 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']) |
| + 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) |
| targets = applied['targets'] |
| |
| def poll_health(): |
| @@ -844,8 +954,14 @@ def converge(cloud, record_dir, applied, paths, timeout): |
| f'{log.path.name}; resume with converge') |
| reasons, summary = evaluate(step, applied, log.read(), load_probes(paths), prereq, prior) |
| 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')}) |
| 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, |
| + 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)') |
| write_record(record_dir / f'{step}.json', record) |
| @@ -861,7 +977,8 @@ 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']) |
| + applied_at = epoch(record_anchor(applied)) |
| + kind = anchor_kind(applied) |
| for path, doc in docs: |
| name = Path(path).name |
| if doc is None: |
| @@ -876,8 +993,10 @@ def probe_findings(docs, applied, step, public): |
| if doc.get('expect') != expect: |
| reasons.append(f"probe record {name} expected {doc.get('expect')}; step {step} needs {expect}") |
| started, finished = epoch(doc.get('started_at')), epoch(doc.get('finished_at')) |
| + # Strict, no clock tolerance: in a B step S1 and S2 answer alike, so an |
| + # attempt from before the change could otherwise count as evidence. |
| if started is None or started <= applied_at: |
| - reasons.append(f"probe record {name} started before the apply ({doc.get('started_at')})") |
| + reasons.append(f"probe record {name} started before the {kind} ({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: |
| @@ -917,13 +1036,16 @@ def coverage_reasons(times, window, gap, what): |
| 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] |
| + # The window is in the probe host's clock, the observations in this host's. |
| + before = [t for t in times if t <= start + CLOCK_TOLERANCE] |
| + after = [t for t in times if t >= end - CLOCK_TOLERANCE] |
| reasons = [] |
| if not before: |
| - reasons.append(f'{what} was not observed before the earliest probe started ({iso(start)})') |
| + reasons.append(f'{what} was not observed before the earliest probe started ({iso(start)}, ' |
| + f'{CLOCK_TOLERANCE:g} s clock tolerance)') |
| if not after: |
| - reasons.append(f'{what} was not observed after the latest probe finished ({iso(end)})') |
| + reasons.append(f'{what} was not observed after the latest probe finished ({iso(end)}, ' |
| + f'{CLOCK_TOLERANCE:g} s clock tolerance)') |
| 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:]): |
| @@ -956,7 +1078,7 @@ def trust_findings(status, base, iid, step): |
| 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: |
| + 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 []) |
| targets, baseline = applied['targets'], applied.get('baseline') or {} |
| if set(baseline) != set(targets): |
| @@ -1000,7 +1122,10 @@ def evaluate(step, applied, polls, docs, prereq, prior): |
| 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} |
| + '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; ' |
| + 'the probe-after-anchor check is strict'} |
| return unique, summary |
| |
| |
| @@ -1009,9 +1134,12 @@ def cmd_converge(args, cloud): |
| paths = split(args.probe_records) |
| targets = target_list(args.targets) |
| with locked(record_dir): |
| - applied = load_record(record_dir / f'{args.step}-applied.json') |
| + # 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'), |
| + load_record(record_dir / f'{args.step}-verified.json')) if r and record_anchor(r)] |
| + 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 in {record_dir}; run apply first') |
| + 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 sorted(targets) != sorted(applied.get('targets') or []): |
| @@ -1107,7 +1235,16 @@ def parser(): |
| 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) |
| - for s in (a, c): |
| + 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('--port', required=True, choices=['80', '443']) |
| + 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') |
| + 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') |
| r.add_argument('--nlb-arn', required=True) |
| @@ -1116,7 +1253,7 @@ def parser(): |
| r.add_argument('--sources', required=True, help='the ingress module\'s proxy_protocol_sources, comma-separated') |
| r.add_argument('--alarm', required=True, help='the proxy trust alarm name') |
| r.add_argument('--record-dir', required=True) |
| - for s in (a, c, r): |
| + for s in (a, c, v, r): |
| s.add_argument('--profile', required=True) |
| s.add_argument('--region', required=True) |
| s.add_argument('--targets', required=True, help='every target instance id, comma-separated') |
| @@ -1133,6 +1270,8 @@ def main(argv=None): |
| return cmd_apply(args, cloud) |
| if args.command == 'converge': |
| return cmd_converge(args, cloud) |
| + if args.command == 'reverify': |
| + return cmd_reverify(args, cloud) |
| return cmd_prereq(args, cloud) |
| except Refused as err: |
| print(f'refused: {one_line(err)}', file=sys.stderr) |