scripts: G2 drill probe with lock reader and budget (T1)
scripts/region-ha-g2/g2-probe.py+445 −0scripts/region_ha_g2_probe_test.py+350 −0
Intent
<task-notification> <task-id>bwf3hb15u</task-id> <tool-use-id>toolu_01FnKS2sEktCp2p7qQ9hu8RD</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/bwf3hb15u.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 7 fix round" completed (exit code 0)</summary> </task-notification>
<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="2060f6f4-6ff9-4f64-84de-9efc176cd65b"> Agent manager 8a3d302: P3b-2 ops merged c151e84; v0.34.6 (dev-only) is being cut now by agent 3c38111. Please reconcile G2-CARD's release labels with the final order: fixed boxes and console on v0.34.6, window A boots the group on v0.34.6, window B rolls to v0.34.7, G0 re-pins to v0.34.7, then the dev promote freeze until G2 cleanup. Your remaining scripts can ride v0.34.7 if they need to be on the boxes. </paseo-system>
diff --git a/scripts/region-ha-g2/g2-probe.py b/scripts/region-ha-g2/g2-probe.py| new file mode 100755 |
| index 000000000..d9b3e14e8 |
| --- /dev/null |
| +++ b/scripts/region-ha-g2/g2-probe.py |
| @@ -0,0 +1,445 @@ |
| +#!/usr/bin/env python3 |
| +# Operator copy is pending the controller's post-report review. |
| +import argparse |
| +from collections import Counter |
| +from datetime import datetime, timezone |
| +import ipaddress |
| +import json |
| +import math |
| +import os |
| +from pathlib import Path |
| +import re |
| +import subprocess |
| +import sys |
| +import threading |
| +import time |
| +import uuid |
| + |
| + |
| +TEXT = { |
| + 'budget': 'Lock GET budget exceeded.', |
| + 'cap': 'Lock reader stopped at the cap.', |
| + 'aws': 'Only an S3 copy to standard output is allowed.', |
| + 'scope': 'Name at least one fixture and one entry.', |
| + 'entry': 'Each entry must have a unique name and a literal IP address.', |
| + 'arguments': 'Check the fixture, write entry, duration and lock budget arguments.', |
| + 'evidence': 'Evidence files already exist or could not be opened.', |
| + 'ranges': 'Supply valid ranges for every fixture in the acknowledgement file.', |
| + 'worker': 'A probe worker failed. The evidence is incomplete.', |
| + 'interrupted': 'The probe was interrupted. Available evidence has been saved.', |
| +} |
| +OWNER = re.compile(r'box/v1;ref=(?P<ref>[^;=]+);(?:iid=(?P<iid>[^;=]+);)?pid=(?P<pid>[1-9][0-9]*);ha=1') |
| +RELEASED = re.compile(r'released/v1;ref=(?P<ref>[^;=]+);iid=(?P<iid>[^;=]+)') |
| +RFC3339 = re.compile(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})') |
| +HOST = re.compile(r'(?=.{1,253}\Z)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)*[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?') |
| +NAME = re.compile(r'[A-Za-z0-9][A-Za-z0-9._-]*') |
| + |
| + |
| +class Clock: |
| + monotonic = staticmethod(time.monotonic) |
| + sleep = staticmethod(time.sleep) |
| + |
| + @staticmethod |
| + def now(): |
| + return datetime.now(timezone.utc) |
| + |
| + |
| +def timestamp(value): |
| + if not isinstance(value, str) or not RFC3339.fullmatch(value): |
| + raise ValueError() |
| + parsed = datetime.fromisoformat(value.replace('Z', '+00:00')) |
| + if parsed.year == 1: |
| + raise ValueError() |
| + return parsed |
| + |
| + |
| +def classify_lock(body, now): |
| + # Keep the state decisions aligned with region-ha-g3/pool-readiness.py. |
| + # Both copies are witnessed by scripts/testdata/region-ha-locks.json. |
| + result = dict(state='lock_absent', generation=None, expires_at=None, |
| + iid=None, ref=None, marker='absent') |
| + if body is None: |
| + return result |
| + try: |
| + lock = json.loads(body) |
| + if not isinstance(lock, dict): |
| + raise ValueError() |
| + expires = timestamp(lock.get('expires_at')) |
| + owner = lock.get('owner', '') |
| + generation = lock.get('generation', 0) |
| + if (not isinstance(owner, str) or type(generation) is not int |
| + or not -(2 ** 63) <= generation < 2 ** 63): |
| + raise ValueError() |
| + release = lock.get('carlos_release') |
| + if release is not None or owner.startswith('released/v1;'): |
| + if (not isinstance(release, dict) or type(release.get('v')) is not int |
| + or release['v'] != 1 or type(release.get('clean')) is not bool): |
| + raise ValueError() |
| + for field in ('box', 'iid', 'lifetime', 'files_gen'): |
| + if not isinstance(release.get(field, ''), str): |
| + raise ValueError() |
| + txid = release.get('txid', 0) |
| + if type(txid) is not int or not 0 <= txid < 2 ** 64: |
| + raise ValueError() |
| + timestamp(release.get('at')) |
| + result['marker'] = 'clean' if release['clean'] else 'unclean' |
| + result['state'] = 'marker_' + result['marker'] |
| + parsed = RELEASED.fullmatch(owner) |
| + else: |
| + parsed = OWNER.fullmatch(owner) |
| + if (parsed is None or not parsed.group('iid') or len(parsed.group('pid')) > 19 |
| + or int(parsed.group('pid')) >= 2 ** 63): |
| + result['state'] = 'lock_old_format' |
| + else: |
| + result['state'] = 'awake' if expires > now else 'lock_expired_unreleased' |
| + if parsed: |
| + result.update(iid=parsed.group('iid'), ref=parsed.group('ref')) |
| + result.update(generation=lock.get('generation'), expires_at=lock['expires_at']) |
| + except (ValueError, TypeError, UnicodeError): |
| + result.update(state='lock_invalid', marker=None) |
| + return result |
| + |
| + |
| +class ReadError(Exception): |
| + pass |
| + |
| + |
| +class AWSRunner: |
| + def __init__(self, profile, region, runner=None): |
| + self.profile, self.region = profile, region |
| + self.runner = runner or subprocess.run |
| + |
| + def __call__(self, verb, source, destination): |
| + if (verb != 'cp' or destination != '-' |
| + or not re.fullmatch(r's3://[A-Za-z0-9][A-Za-z0-9.-]*/[^\s]+', source)): |
| + raise ValueError(TEXT['aws']) |
| + command = ['aws', '--profile', self.profile, '--region', self.region, |
| + '--no-cli-pager', '--cli-connect-timeout', '2', '--cli-read-timeout', '5', |
| + 's3', verb, source, destination] |
| + env = dict(os.environ, AWS_MAX_ATTEMPTS='1', AWS_RETRY_MODE='standard', |
| + AWS_EC2_METADATA_DISABLED='true', AWS_PAGER='') |
| + try: |
| + result = self.runner(command, stdin=subprocess.DEVNULL, capture_output=True, |
| + text=True, timeout=10, check=False, env=env) |
| + except (OSError, subprocess.SubprocessError) as exc: |
| + raise ReadError() from exc |
| + if result.returncode: |
| + if '(NoSuchKey)' in result.stderr: |
| + return None |
| + raise ReadError() |
| + return result.stdout |
| + |
| + |
| +def base_record(kind, fixture, entry, clock): |
| + return dict(t=clock.now().isoformat().replace('+00:00', 'Z'), kind=kind, |
| + fixture=fixture, entry=entry, rid=None, rid_echo=None, status=None, |
| + box=None, hits=None, max=None, ms=None, err=None) |
| + |
| + |
| +def http_record(fixture, entry, ip, *, n=None, runner=None, clock=None): |
| + runner, clock = runner or subprocess.run, clock or Clock() |
| + row = base_record('get' if n is None else 'write', fixture, entry, clock) |
| + row.update(rid=str(uuid.uuid4()), rid_echo=False) |
| + if n is not None: |
| + row['n'] = n |
| + address = '[' + ip + ']' if ':' in ip else ip |
| + command = ['curl', '-q', '-sS', '-o', '-', '-w', |
| + '\n{"http_code":"%{http_code}","time_total":%{time_total}}', |
| + '--resolve', f'{fixture}:443:{address}', '--max-time', '5', |
| + '--noproxy', '*', '-H', 'X-Request-Id: ' + row['rid']] |
| + if n is not None: |
| + command.extend(['-X', 'POST']) |
| + command.append(f'https://{fixture}/' + (f'write?n={n}' if n is not None else '')) |
| + start = clock.monotonic() |
| + try: |
| + response = runner(command, stdin=subprocess.DEVNULL, capture_output=True, |
| + text=True, timeout=6, check=False) |
| + except (OSError, subprocess.SubprocessError) as exc: |
| + row.update(ms=(clock.monotonic() - start) * 1000, |
| + err='timeout' if isinstance(exc, subprocess.TimeoutExpired) else 'process_error') |
| + return row |
| + row['ms'] = (clock.monotonic() - start) * 1000 |
| + try: |
| + body, metadata = response.stdout.rsplit('\n', 1) |
| + meta = json.loads(metadata) |
| + code, elapsed = meta['http_code'], meta['time_total'] |
| + if isinstance(code, str) and re.fullmatch('[0-9]{3}', code): |
| + code = int(code) |
| + if (type(code) is not int or not (code == 0 or 100 <= code <= 599) |
| + or type(elapsed) not in (float, int) or not math.isfinite(elapsed) or elapsed < 0): |
| + raise ValueError() |
| + row.update(status=code or None, ms=elapsed * 1000) |
| + if body.startswith('g2fixture '): |
| + fields = dict(re.findall(r'\b(box|hits|max|rid)=([^\s]+)', body)) |
| + row['box'] = fields.get('box') |
| + for field in ('hits', 'max'): |
| + value = fields.get(field, '') |
| + row[field] = int(value) if re.fullmatch('[0-9]{1,19}', value) else None |
| + row['rid_echo'] = fields.get('rid') == row['rid'] |
| + except (ValueError, TypeError, KeyError): |
| + row.update(status=None, err='invalid_response') |
| + if response.returncode: |
| + row.update(status=None, err='timeout' if response.returncode == 28 else 'curl_error') |
| + return row |
| + |
| + |
| +def lock_record(fixture, bucket, prefix, *, aws, clock): |
| + row = base_record('lock', fixture, None, clock) |
| + start = clock.monotonic() |
| + try: |
| + body = aws('cp', f's3://{bucket}/{prefix}/{fixture}/lock.json', '-') |
| + row.update(classify_lock(body, clock.now())) |
| + if row['state'] == 'lock_invalid': |
| + row['err'] = 'lock_invalid' |
| + except ReadError: |
| + row.update(classify_lock(None, clock.now())) |
| + row.update(state='read_error', err='read_error', marker=None) |
| + row['ms'] = (clock.monotonic() - start) * 1000 |
| + return row |
| + |
| + |
| +class Budget: |
| + def __init__(self, cap, out): |
| + self.cap, self.out, self.used = cap, out, 0 |
| + self.lock = threading.Lock() |
| + self.announced = False |
| + |
| + def take(self): |
| + with self.lock: |
| + allowed = self.used < self.cap |
| + if allowed: |
| + self.used += 1 |
| + if self.used >= self.cap and not self.announced: |
| + print(TEXT['cap'], file=self.out, flush=True) |
| + self.announced = True |
| + return allowed |
| + |
| + |
| +class Summary: |
| + def __init__(self, fixtures): |
| + self.rows = {} |
| + self.acks = {fixture: set() for fixture in fixtures} |
| + |
| + def add(self, row): |
| + if row['kind'] == 'lock': |
| + return |
| + key = row['fixture'], row['entry'], row['kind'] |
| + item = self.rows.setdefault(key, dict(status=Counter(), boxes=Counter(), run=0, longest=0)) |
| + item['status'][str(row['status']) if row['status'] is not None else 'none'] += 1 |
| + item['boxes'][row['box'] or 'unknown'] += 1 |
| + item['run'] = 0 if row['status'] == 200 else item['run'] + 1 |
| + item['longest'] = max(item['longest'], item['run']) |
| + if (row['kind'] == 'write' and row['status'] == 200 and row['rid_echo'] |
| + and row['err'] is None): |
| + self.acks[row['fixture']].add(row['n']) |
| + |
| + def print(self, out): |
| + for (fixture, entry, kind), item in sorted(self.rows.items()): |
| + print(f'Summary for {fixture} through {entry} ({kind}).', file=out) |
| + print('Counts by status: ' + json.dumps(item['status'], sort_keys=True) + '.', file=out) |
| + print('Counts by serving box: ' + json.dumps(item['boxes'], sort_keys=True) + '.', file=out) |
| + print(f'Longest run of non-200 responses: {item["longest"]}.', file=out) |
| + |
| + |
| +class Parser(argparse.ArgumentParser): |
| + def error(self, message): |
| + raise ValueError(message.rstrip('.') + '.') |
| + |
| + |
| +def parse_args(argv): |
| + parser = Parser(description='Collect drill evidence or compare saved acknowledgements with ranges.') |
| + parser.add_argument('--fixture', action='append', default=[]) |
| + parser.add_argument('--entry', action='append', default=[]) |
| + parser.add_argument('--write-entry') |
| + parser.add_argument('--bucket') |
| + parser.add_argument('--prefix', default='instances') |
| + parser.add_argument('--profile') |
| + parser.add_argument('--region') |
| + parser.add_argument('--lock-every', type=float, default=5) |
| + parser.add_argument('--max-lock-gets', type=int, default=20000) |
| + parser.add_argument('--duration', type=float) |
| + parser.add_argument('--out', required=True) |
| + parser.add_argument('--compare', metavar='RANGES_FILE', |
| + help='Compare saved acknowledgements without making requests.') |
| + args = parser.parse_args(argv) |
| + if args.compare: |
| + if args.fixture or args.entry or args.duration is not None: |
| + raise ValueError(TEXT['ranges']) |
| + return args |
| + if not args.fixture or not args.entry: |
| + raise ValueError(TEXT['scope']) |
| + args.entries = {} |
| + for entry in args.entry: |
| + name, sep, address = entry.partition('=') |
| + try: |
| + ipaddress.ip_address(address) |
| + except ValueError: |
| + raise ValueError(TEXT['entry']) from None |
| + if not sep or not NAME.fullmatch(name) or name in args.entries or '%' in address: |
| + raise ValueError(TEXT['entry']) |
| + args.entries[name] = address |
| + if (len(set(args.fixture)) != len(args.fixture) |
| + or any(not HOST.fullmatch(host) for host in args.fixture) |
| + or args.write_entry not in args.entries |
| + or args.duration is None or not math.isfinite(args.duration) or args.duration <= 0 |
| + or not math.isfinite(args.lock_every) or args.lock_every <= 0 |
| + or args.max_lock_gets < 0 or not args.bucket or not args.profile or not args.region |
| + or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.-]*', args.bucket) |
| + or not re.fullmatch(r'[A-Za-z0-9._/-]+', args.prefix) |
| + or args.prefix.startswith('/') or args.prefix.endswith('/') |
| + or '..' in args.prefix.split('/')): |
| + raise ValueError(TEXT['arguments']) |
| + if len(args.fixture) * args.duration / args.lock_every > args.max_lock_gets: |
| + raise ValueError(TEXT['budget']) |
| + return args |
| + |
| + |
| +class Probe: |
| + def __init__(self, args, *, runner=None, clock=None, out=None): |
| + self.args, self.runner, self.clock = args, runner, clock or Clock() |
| + self.out = out if out is not None else sys.stdout |
| + self.aws = AWSRunner(args.profile, args.region, runner=runner) |
| + self.budget = Budget(args.max_lock_gets, self.out) |
| + self.summary = Summary(args.fixture) |
| + self.mutex = threading.Lock() |
| + self.stop = threading.Event() |
| + self.failures = [] |
| + |
| + def record(self, row): |
| + with self.mutex: |
| + self.evidence.write(json.dumps(row, allow_nan=False) + '\n') |
| + self.evidence.flush() |
| + self.summary.add(row) |
| + |
| + def periodic(self, interval, action): |
| + tick = 0.0 |
| + while tick < self.args.duration and not self.stop.is_set(): |
| + delay = self.start + tick - self.clock.monotonic() |
| + if delay > 0: |
| + self.clock.sleep(delay) |
| + if self.stop.is_set() or self.clock.monotonic() >= self.end: |
| + return |
| + if action() is False: |
| + return |
| + # Skip missed slots after a slow request; never send a catch-up burst. |
| + elapsed = self.clock.monotonic() - self.start |
| + tick = max(tick + interval, math.ceil(elapsed / interval) * interval) |
| + |
| + def http_loop(self, fixture, entry, write=False): |
| + seq = 0 |
| + |
| + def request(): |
| + nonlocal seq |
| + seq += 1 |
| + self.record(http_record(fixture, entry, self.args.entries[entry], |
| + n=seq if write else None, runner=self.runner, clock=self.clock)) |
| + self.periodic(1, request) |
| + |
| + def lock_loop(self, fixture): |
| + def request(): |
| + if not self.budget.take(): |
| + return False |
| + self.record(lock_record(fixture, self.args.bucket, self.args.prefix, |
| + aws=self.aws, clock=self.clock)) |
| + self.periodic(self.args.lock_every, request) |
| + |
| + def worker(self, action, *args): |
| + try: |
| + action(*args) |
| + except Exception as exc: |
| + with self.mutex: |
| + self.failures.append(type(exc).__name__) |
| + self.stop.set() |
| + |
| + def run(self): |
| + # Reserve both paths before starting any request. The 'x' mode uses O_EXCL. |
| + with open(self.args.out, 'x', encoding='utf-8') as evidence: |
| + with open(self.args.out + '.acks', 'x', encoding='utf-8') as ack_file: |
| + self.evidence = evidence |
| + self.start = self.clock.monotonic() |
| + self.end = self.start + self.args.duration |
| + threads = [] |
| + interrupted = False |
| + try: |
| + for fixture in self.args.fixture: |
| + jobs = [(self.http_loop, (fixture, entry)) for entry in self.args.entries] |
| + jobs += [(self.http_loop, (fixture, self.args.write_entry, True)), |
| + (self.lock_loop, (fixture,))] |
| + for action, params in jobs: |
| + thread = threading.Thread(target=self.worker, args=(action, *params)) |
| + thread.start() |
| + threads.append(thread) |
| + for thread in threads: |
| + thread.join() |
| + except KeyboardInterrupt: |
| + interrupted = True |
| + finally: |
| + self.stop.set() |
| + for thread in threads: |
| + thread.join() |
| + json.dump({host: sorted(values) for host, values in self.summary.acks.items()}, ack_file) |
| + ack_file.write('\n') |
| + ack_file.flush() |
| + self.summary.print(self.out) |
| + if interrupted: |
| + print(TEXT['interrupted'], file=self.out) |
| + return 130 |
| + if self.failures: |
| + print(TEXT['worker'], file=self.out) |
| + return 2 |
| + return 0 |
| + |
| + |
| +def lost_acks(acks, body): |
| + ranges = [] |
| + for part in body.strip().split(',') if body.strip() else []: |
| + if not re.fullmatch(r'[1-9][0-9]{0,18}(?:-[1-9][0-9]{0,18})?', part): |
| + raise ValueError(TEXT['ranges']) |
| + pair = part.split('-') |
| + lo, hi = int(pair[0]), int(pair[-1]) |
| + if hi < lo or hi >= 2 ** 63: |
| + raise ValueError(TEXT['ranges']) |
| + ranges.append((lo, hi)) |
| + return sorted(n for n in set(acks) if not any(lo <= n <= hi for lo, hi in ranges)) |
| + |
| + |
| +def compare(args, out): |
| + acks = json.loads(Path(args.out + '.acks').read_text()) |
| + if (not isinstance(acks, dict) or not acks or any( |
| + not HOST.fullmatch(host) or not isinstance(values, list) |
| + or any(type(n) is not int or not 0 < n < 2 ** 63 for n in values) |
| + for host, values in acks.items())): |
| + raise ValueError(TEXT['ranges']) |
| + body = Path(args.compare).read_text() |
| + if body.lstrip().startswith('{'): |
| + bodies = json.loads(body) |
| + elif len(acks) == 1: |
| + bodies = {next(iter(acks)): body} |
| + else: |
| + raise ValueError(TEXT['ranges']) |
| + if (not isinstance(bodies, dict) or set(bodies) != set(acks) |
| + or any(not isinstance(value, str) for value in bodies.values())): |
| + raise ValueError(TEXT['ranges']) |
| + losses = {host: lost_acks(values, bodies[host]) for host, values in acks.items()} |
| + for host, missing in sorted(losses.items()): |
| + print(f'Lost acknowledged writes for {host}: {json.dumps(missing)}.', file=out) |
| + return 0 |
| + |
| + |
| +def main(argv=None, *, runner=None, clock=None, out=None): |
| + out = out if out is not None else sys.stdout |
| + try: |
| + args = parse_args(argv) |
| + if args.compare: |
| + return compare(args, out) |
| + return Probe(args, runner=runner, clock=clock, out=out).run() |
| + except OSError: |
| + print(TEXT['evidence'], file=out) |
| + return 2 |
| + except (ValueError, UnicodeError) as exc: |
| + print(str(exc) or TEXT['arguments'], file=out) |
| + return 2 |
| + |
| + |
| +if __name__ == '__main__': |
| + sys.exit(main()) |
diff --git a/scripts/region_ha_g2_probe_test.py b/scripts/region_ha_g2_probe_test.py| new file mode 100644 |
| index 000000000..db814c9fa |
| --- /dev/null |
| +++ b/scripts/region_ha_g2_probe_test.py |
| @@ -0,0 +1,350 @@ |
| +"""Offline witnesses for the G2 drill probe.""" |
| +from datetime import datetime, timedelta |
| +import importlib.util |
| +import io |
| +import json |
| +import os |
| +from pathlib import Path |
| +import re |
| +import subprocess |
| +import sys |
| +import tempfile |
| +import threading |
| +import unittest |
| +from unittest.mock import patch |
| + |
| +RUN_PROCESS = subprocess.run |
| +SCRIPT = Path(__file__).parent / 'region-ha-g2/g2-probe.py' |
| +SPEC = importlib.util.spec_from_file_location('g2_probe', SCRIPT) |
| +probe = importlib.util.module_from_spec(SPEC) |
| +SPEC.loader.exec_module(probe) |
| +FIXTURES = json.loads((Path(__file__).parent / 'testdata/region-ha-locks.json').read_text()) |
| +NOW = datetime.fromisoformat(FIXTURES['now'].replace('Z', '+00:00')) |
| +SOURCE = (SCRIPT.parent / 'fixture/main.go').read_text() |
| +FORMAT = json.loads(re.search(r'ResponseFormat\s*=\s*("[^"\n]*")', SOURCE)[1]) |
| +RANGES_FORMAT = json.loads(re.search(r'RangesFormat\s*=\s*("[^"\n]*")', SOURCE)[1]) |
| +KEYS = {'t', 'kind', 'fixture', 'entry', 'rid', 'rid_echo', 'status', |
| + 'box', 'hits', 'max', 'ms', 'err'} |
| + |
| + |
| +class FakeClock: |
| + def __init__(self): |
| + self.local = threading.local() |
| + |
| + def monotonic(self): |
| + return getattr(self.local, 't', 0.0) |
| + |
| + def sleep(self, seconds): |
| + self.local.t = self.monotonic() + seconds |
| + |
| + def now(self): |
| + return NOW + timedelta(seconds=self.monotonic()) |
| + |
| + |
| +class FakeRunner: |
| + def __init__(self): |
| + self.calls = [] |
| + self.response = None |
| + self.lock = FIXTURES['locks']['held'] |
| + |
| + def __call__(self, command, **kwargs): |
| + self.calls.append((command, kwargs)) |
| + if self.response is not None: |
| + return self.response |
| + if command[0] == 'curl': |
| + rid = command[command.index('-H') + 1].split(': ', 1)[1] |
| + body = FORMAT % ('fixture-box', 3, 4, rid) |
| + return subprocess.CompletedProcess(command, 0, body + '\n' + json.dumps( |
| + {'http_code': 200, 'time_total': 0.025}), '') |
| + assert command[0] == 'aws', command |
| + return subprocess.CompletedProcess(command, 0, json.dumps(self.lock), '') |
| + |
| + |
| +class ProbeTests(unittest.TestCase): |
| + def setUp(self): |
| + self.fake = FakeRunner() |
| + self.clock = FakeClock() |
| + self.stdout = io.StringIO() |
| + root = os.environ.get('TMPDIR') or str(Path.home() / '.cache') |
| + Path(root).mkdir(parents=True, exist_ok=True) |
| + self.tmp = tempfile.TemporaryDirectory(prefix='g2-probe-test-', dir=root) |
| + self.addCleanup(self.tmp.cleanup) |
| + self.out = Path(self.tmp.name) / 'run.jsonl' |
| + self.args = ['--fixture', 'example.com', '--entry', 'nlb-a=192.0.2.10', |
| + '--write-entry', 'nlb-a', '--bucket', 'example-data', |
| + '--profile', 'example', '--region', 'eu-west-1', |
| + '--duration', '3', '--out', str(self.out)] |
| + self.block = patch.object(probe.subprocess, 'run', side_effect=AssertionError('Real process used.')) |
| + self.block.start() |
| + self.addCleanup(self.block.stop) |
| + |
| + def http(self, **kw): |
| + return probe.http_record('example.com', 'nlb-a', '192.0.2.10', |
| + runner=self.fake, clock=self.clock, **kw) |
| + |
| + def test_schema_and_timeout(self): |
| + self.fake.response = subprocess.CompletedProcess([], 28, '\n{"http_code":0,"time_total":5}', 'Timed out.') |
| + row = self.http() |
| + self.assertEqual(set(row), KEYS) |
| + self.assertIsNone(row['status']) |
| + self.assertEqual(row['err'], 'timeout') |
| + self.assertIsNone(row['box']) |
| + self.assertFalse(row['rid_echo']) |
| + self.assertEqual(row['ms'], 5000) |
| + self.assertEqual(len(self.fake.calls), 1) |
| + |
| + def test_curl_zero_code_and_process_timeout(self): |
| + self.fake.response = subprocess.CompletedProcess([], 28, '\n{"http_code":"000","time_total":5.001}', '') |
| + row = self.http() |
| + self.assertIsNone(row['status']) |
| + self.assertEqual(row['ms'], 5001) |
| + self.assertEqual(row['err'], 'timeout') |
| + def timed_out(*args, **kwargs): |
| + raise subprocess.TimeoutExpired('curl', 6) |
| + row = probe.http_record('example.com', 'nlb-a', '192.0.2.10', |
| + runner=timed_out, clock=self.clock) |
| + self.assertIsNone(row['status']) |
| + self.assertEqual(row['err'], 'timeout') |
| + |
| + def test_slow_requests_skip_missed_slots(self): |
| + config = probe.parse_args(self.args + ['--duration', '8']) |
| + job = probe.Probe(config, runner=self.fake, clock=self.clock, out=self.stdout) |
| + job.start, job.end = 0, 8 |
| + starts = [] |
| + |
| + def slow_request(): |
| + starts.append(self.clock.monotonic()) |
| + self.clock.sleep(2.2) |
| + job.periodic(1, slow_request) |
| + self.assertEqual(starts, [0, 3, 6]) |
| + |
| + def test_get_write_schema_and_echo(self): |
| + for n in (None, 9): |
| + row = self.http(n=n) |
| + self.assertEqual(set(row), KEYS | ({'n'} if n is not None else set())) |
| + self.assertEqual(row['kind'], 'write' if n else 'get') |
| + self.assertTrue(row['rid_echo']) |
| + self.assertEqual((row['box'], row['hits'], row['max']), ('fixture-box', 3, 4)) |
| + self.assertEqual(row['ms'], 25) |
| + self.assertEqual(row['status'], 200) |
| + self.assertIsNone(row['err']) |
| + self.fake.response = subprocess.CompletedProcess([], 0, FORMAT % ('fixture-box', 3, 4, 'wrong') + |
| + '\n{"http_code":200,"time_total":0.1}', '') |
| + self.assertFalse(self.http()['rid_echo']) |
| + |
| + def test_missing_fields_are_null(self): |
| + self.fake.response = subprocess.CompletedProcess([], 0, 'g2fixture rid=wrong\n\n{"http_code":503,"time_total":0.1}', '') |
| + row = self.http() |
| + for key in ('box', 'hits', 'max'): |
| + self.assertIsNone(row[key]) |
| + self.assertEqual(row['status'], 503) |
| + |
| + def test_curl_is_one_pinned_request_without_retries(self): |
| + self.http(n=7) |
| + command, opts = self.fake.calls[0] |
| + self.assertEqual(command[:2], ['curl', '-q']) |
| + self.assertNotIn('--retry', command) |
| + self.assertNotIn('-L', command) |
| + self.assertEqual(command[command.index('--noproxy') + 1], '*') |
| + self.assertEqual(command[command.index('--resolve') + 1], 'example.com:443:192.0.2.10') |
| + self.assertEqual(command[command.index('--max-time') + 1], '5') |
| + self.assertEqual(command[command.index('-X') + 1], 'POST') |
| + self.assertEqual(command[-1], 'https://example.com/write?n=7') |
| + self.assertRegex(command[command.index('-H') + 1], r'^X-Request-Id: [0-9a-f-]{36}$') |
| + self.assertGreaterEqual(opts['timeout'], 5) |
| + probe.http_record('example.com', 'v6', '2001:db8::1', runner=self.fake, clock=self.clock) |
| + self.assertIn('example.com:443:[2001:db8::1]', self.fake.calls[-1][0]) |
| + |
| + def test_shared_lock_classifier_and_schema(self): |
| + expected = {'absent': 'lock_absent', 'legacy': 'lock_old_format', |
| + 'marker_clean': 'marker_clean', 'marker_unclean': 'marker_unclean', |
| + 'held': 'awake', 'expired': 'lock_expired_unreleased', 'no_iid': 'lock_old_format'} |
| + self.assertEqual(set(expected), set(FIXTURES['locks'])) |
| + for name, state in expected.items(): |
| + value = FIXTURES['locks'][name] |
| + result = probe.classify_lock(None if value is None else json.dumps(value), NOW) |
| + self.assertEqual(result['state'], state, name) |
| + self.assertEqual(result['generation'], None if value is None else value['generation']) |
| + self.assertEqual(result['expires_at'], None if value is None else value['expires_at']) |
| + if name in ('held', 'expired', 'marker_clean', 'marker_unclean'): |
| + self.assertEqual(result['iid'], 'i-0123456789abcdef0') |
| + self.assertEqual(result['ref'], 'fixture-box') |
| + self.assertEqual(result['marker'], {'marker_clean': 'clean', 'marker_unclean': 'unclean'}.get(name, 'absent')) |
| + aws = probe.AWSRunner('example', 'eu-west-1', runner=self.fake) |
| + row = probe.lock_record('example.com', 'example-data', 'instances', aws=aws, clock=self.clock) |
| + self.assertEqual(set(row), KEYS | {'state', 'generation', 'expires_at', 'iid', 'ref', 'marker'}) |
| + self.assertEqual(row['kind'], 'lock') |
| + self.assertIsNone(row['status']) |
| + self.assertEqual(row['state'], 'awake') |
| + |
| + def test_lock_errors_are_not_absence(self): |
| + aws = probe.AWSRunner('example', 'eu-west-1', runner=self.fake) |
| + for body in ('null', '[]', '{}', '{', '{"generation":true}', '{"expires_at":false}'): |
| + self.assertEqual(probe.classify_lock(body, NOW)['state'], 'lock_invalid') |
| + for stderr, state in [('(NoSuchKey)', 'lock_absent'), ('(AccessDenied)', 'read_error'), |
| + ('(NoSuchBucket)', 'read_error'), ('connect timeout', 'read_error')]: |
| + self.fake.response = subprocess.CompletedProcess([], 1, '', stderr) |
| + row = probe.lock_record('example.com', 'example-data', 'instances', aws=aws, clock=self.clock) |
| + self.assertEqual(row['state'], state) |
| + self.assertEqual(row['err'], None if state == 'lock_absent' else 'read_error') |
| + |
| + def test_aws_runner_refuses_other_verbs_and_destinations(self): |
| + aws = probe.AWSRunner('example', 'eu-west-1', runner=self.fake) |
| + for verb, source, dest in [('rm', 's3://example-data/lock.json', '-'), |
| + ('cp', '-', 's3://example-data/lock.json'), |
| + ('cp', 's3://example-data/lock.json', 'file'), |
| + ('sync', 's3://example-data/', '-')]: |
| + with self.assertRaises(ValueError): |
| + aws(verb, source, dest) |
| + self.assertEqual(self.fake.calls, []) |
| + aws('cp', 's3://example-data/instances/example.com/lock.json', '-') |
| + command, opts = self.fake.calls[0] |
| + self.assertEqual(command[-4:], ['s3', 'cp', 's3://example-data/instances/example.com/lock.json', '-']) |
| + self.assertEqual(opts['env']['AWS_MAX_ATTEMPTS'], '1') |
| + self.assertEqual(opts['env']['AWS_EC2_METADATA_DISABLED'], 'true') |
| + |
| + def test_scope_and_arguments_refuse(self): |
| + for flag in ('--fixture', '--entry'): |
| + args = self.args.copy() |
| + pos = args.index(flag) |
| + del args[pos:pos + 2] |
| + with self.subTest(flag=flag), self.assertRaises(ValueError): |
| + probe.parse_args(args) |
| + for value in ('nlb=example.com', 'nlb=192.0.2.999', 'nlb=', 'nlb=2001:db8::1%eth0'): |
| + with self.subTest(value=value), self.assertRaises(ValueError): |
| + probe.parse_args(self.args + ['--entry', value]) |
| + for flag, value in [('--fixture', 'example.com/path'), ('--write-entry', 'unknown'), |
| + ('--duration', '0'), ('--duration', 'nan'), ('--lock-every', '0'), |
| + ('--max-lock-gets', '-1'), ('--entry', 'nlb-a=192.0.2.11')]: |
| + with self.subTest(flag=flag, value=value), self.assertRaises(ValueError): |
| + probe.parse_args(self.args + [flag, value]) |
| + config = probe.parse_args(self.args + ['--entry', 'v6=2001:db8::1']) |
| + self.assertEqual(config.entries['v6'], '2001:db8::1') |
| + |
| + def test_budget_refusal_precedes_io(self): |
| + status = probe.main(self.args + ['--duration', '101', '--max-lock-gets', '20'], |
| + runner=self.fake, clock=self.clock, out=self.stdout) |
| + self.assertEqual(status, 2) |
| + self.assertIn('Lock GET budget exceeded.', self.stdout.getvalue()) |
| + self.assertEqual(self.fake.calls, []) |
| + self.assertFalse(self.out.exists()) |
| + |
| + def test_cap_stops_only_locks_once(self): |
| + config = probe.parse_args(self.args + ['--duration', '7', '--max-lock-gets', '2']) |
| + job = probe.Probe(config, runner=self.fake, clock=self.clock, out=self.stdout) |
| + job.budget.used = 1 |
| + self.assertEqual(job.run(), 0) |
| + rows = [json.loads(line) for line in self.out.read_text().splitlines()] |
| + self.assertEqual(sum(r['kind'] == 'lock' for r in rows), 1) |
| + self.assertEqual(sum(r['kind'] == 'get' for r in rows), 7) |
| + self.assertEqual(sum(r['kind'] == 'write' for r in rows), 7) |
| + self.assertEqual(self.stdout.getvalue().count('Lock reader stopped at the cap.'), 1) |
| + |
| + def test_http_and_lock_cadence(self): |
| + self.assertEqual(probe.main(self.args + ['--duration', '11'], |
| + runner=self.fake, clock=self.clock, out=self.stdout), 0) |
| + rows = [json.loads(line) for line in self.out.read_text().splitlines()] |
| + for kind, ticks in [('get', list(range(11))), ('write', list(range(11))), ('lock', [0, 5, 10])]: |
| + times = [(datetime.fromisoformat(row['t'].replace('Z', '+00:00')) - NOW).total_seconds() |
| + for row in rows if row['kind'] == kind] |
| + self.assertEqual(times, ticks, kind) |
| + |
| + def test_exclusive_evidence_files(self): |
| + for path in (self.out, Path(str(self.out) + '.acks')): |
| + with self.subTest(path=path): |
| + path.write_text('Original evidence.\n') |
| + status = probe.main(self.args, runner=self.fake, clock=self.clock, out=self.stdout) |
| + self.assertEqual(status, 2) |
| + self.assertEqual(path.read_text(), 'Original evidence.\n') |
| + self.assertEqual(self.fake.calls, []) |
| + path.unlink() |
| + if self.out.exists(): |
| + self.out.unlink() |
| + |
| + def test_threads_jsonl_acks_and_compare(self): |
| + args = self.args + ['--entry', 'backhaul=192.0.2.20', '--fixture', 'second.example.com'] |
| + self.assertEqual(probe.main(args, runner=self.fake, clock=self.clock, out=self.stdout), 0) |
| + rows = [json.loads(line) for line in self.out.read_text().splitlines()] |
| + self.assertEqual(len(rows), 20) |
| + self.assertEqual(len({r['rid'] for r in rows if r['kind'] != 'lock'}), 18) |
| + self.assertEqual(json.loads(Path(str(self.out) + '.acks').read_text()), |
| + {'example.com': [1, 2, 3], 'second.example.com': [1, 2, 3]}) |
| + self.assertIn('Summary for example.com through backhaul (get).', self.stdout.getvalue()) |
| + ranges = Path(self.tmp.name) / 'ranges.json' |
| + ranges.write_text(json.dumps({'example.com': RANGES_FORMAT % '1,3', 'second.example.com': RANGES_FORMAT % '1-2'})) |
| + count = len(self.fake.calls) |
| + self.assertEqual(probe.main(['--out', str(self.out), '--compare', str(ranges)], |
| + runner=self.fake, out=self.stdout), 0) |
| + self.assertEqual(len(self.fake.calls), count) |
| + self.assertIn('Lost acknowledged writes for example.com: [2].', self.stdout.getvalue()) |
| + self.assertIn('Lost acknowledged writes for second.example.com: [3].', self.stdout.getvalue()) |
| + |
| + def test_compare_exact_ranges_and_refusals(self): |
| + self.assertEqual(probe.lost_acks([1, 2, 3, 4, 8, 9], RANGES_FORMAT % '1-3,8'), [4, 9]) |
| + self.assertEqual(probe.lost_acks([1, 9], ''), [1, 9]) |
| + self.assertEqual(probe.lost_acks([1, 9], '1-9223372036854775807'), []) |
| + for ranges in ('3-1', 'bad', '1,,3', '0', '1-2-3'): |
| + with self.subTest(ranges=ranges), self.assertRaises(ValueError): |
| + probe.lost_acks([1], ranges) |
| + |
| + def test_cli_with_only_offline_executables_on_path(self): |
| + directory = Path(self.tmp.name) |
| + curl = directory / 'curl' |
| + curl.write_text('#!' + sys.executable + '\n' + |
| + 'import json, sys\n' + |
| + 'args = sys.argv[1:]\n' + |
| + 'rid = args[args.index("-H") + 1].split(": ", 1)[1]\n' + |
| + 'body = ' + repr(FORMAT) + ' % ("fixture-box", 1, 1, rid)\n' + |
| + 'metadata = args[args.index("-w") + 1].replace("%{http_code}", "200").replace("%{time_total}", "0.001")\n' + |
| + 'sys.stdout.write(body + metadata)\n') |
| + aws = directory / 'aws' |
| + aws.write_text('#!' + sys.executable + '\n' + |
| + 'import sys\n' + |
| + 'assert sys.argv[-4:-2] == ["s3", "cp"] and sys.argv[-1] == "-"\n' + |
| + 'print(' + repr(json.dumps(FIXTURES['locks']['held'])) + ')\n') |
| + curl.chmod(0o700) |
| + aws.chmod(0o700) |
| + result = RUN_PROCESS([sys.executable, str(SCRIPT), *self.args, '--duration', '0.2'], |
| + env=dict(os.environ, PATH=str(directory), PYTHONDONTWRITEBYTECODE='1'), |
| + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=10) |
| + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) |
| + rows = [json.loads(line) for line in self.out.read_text().splitlines()] |
| + self.assertEqual({row['kind'] for row in rows}, {'get', 'write', 'lock'}) |
| + self.assertEqual(len(rows), 3) |
| + self.assertTrue(all(row['err'] is None for row in rows)) |
| + self.assertEqual(json.loads(Path(str(self.out) + '.acks').read_text()), {'example.com': [1]}) |
| + |
| + def test_comparison_missing_fixture_and_bad_ack_file_refuse(self): |
| + ack_path = Path(str(self.out) + '.acks') |
| + ranges = Path(self.tmp.name) / 'ranges.json' |
| + args = ['--out', str(self.out), '--compare', str(ranges)] |
| + for acks, body in [({'example.com': [1], 'second.example.com': [1]}, '{"example.com":"1"}'), |
| + ({'example.com': [True]}, '1'), ({'example.com': [0]}, '1'), |
| + ({'example.com': [1]}, '{"example.com":null}')]: |
| + ack_path.write_text(json.dumps(acks)) |
| + ranges.write_text(body) |
| + self.assertEqual(probe.main(args, runner=self.fake, out=self.stdout), 2) |
| + self.assertEqual(self.fake.calls, []) |
| + |
| + def test_summary_tracks_consecutive_failures_and_only_confirmed_acks(self): |
| + summary = probe.Summary(['example.com']) |
| + for n, status in enumerate((200, None, 503, 200, 502, 503, None), 1): |
| + row = self.http(n=n) |
| + row['status'] = status |
| + summary.add(row) |
| + row = self.http(n=8) |
| + row['rid_echo'] = False |
| + summary.add(row) |
| + row = self.http(n=9) |
| + row['err'] = 'timeout' |
| + summary.add(row) |
| + self.assertEqual(summary.acks, {'example.com': {1, 4}}) |
| + summary.print(self.stdout) |
| + text = self.stdout.getvalue() |
| + self.assertIn('Longest run of non-200 responses: 3.', text) |
| + self.assertIn('"503": 2', text) |
| + self.assertIn('"fixture-box": 9', text) |
| + |
| + |
| +if __name__ == '__main__': |
| + unittest.main() |