scripts: chrony script fails loudly and runs unattended (review fixes)
docs/region-ha-runbook.md+8 −4scripts/region-ha-g3/chrony-fixed-box.sh+57 −23scripts/region_ha_g3_chrony_test.py+112 −25
Intent
<task-notification> <task-id>b3cbax8tx</task-id> <tool-use-id>toolu_01V96QSfu8zbVjE5gniGcpR7</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/b3cbax8tx.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 4 implementer" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>aaa945f69f60204ce</task-id> <tool-use-id>toolu_019sg5sBzdEpY7j6XpLdvAfW</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/aaa945f69f60204ce.output</output-file> <status>completed</status> <summary>Agent "Opus task review of Task 4" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Spec:** ✅ Compliant. Every brief item is there, and the host-init hand-off says "New boxes only" in every hunk. Three things I couldn't check from the diff: whether Debian 13 images already ship chrony, the carloku flagship host-init filenames (the report calls them proposals), and whether the `carlos` user exists on every fixed box. The offline test passes at ac7f2450 (13 tests). **Quality:** Needs fixes. **Important:** 1. **The rollback hint won't run under SSM.** The hint is `apt-get install systemd-timesyncd`, with no `-y`. Installing timesyncd has to remove chrony, so apt asks for confirmation. With no terminal it reads end-of-input and aborts. This affects `chrony-fixed-box.sh:9` and `docs/region-ha-runbook.md:96`. Fix: `NEEDRESTART_MODE=l apt-get -y -q install systemd-timesyncd`, and say that it removes chrony. 2. **A failed apt, enable or restart exits silently through `set -e` (`:52-61`).** Timesyncd may already be removed and chrony not running, so the box has no time sync. The operator sees no failure line and no rollback hint. Fix with an ERR trap or a failure function, and make the test assert the hint is printed. 3. **No apt lock wait and no `apt-get update`.** On a box running unattended-upgrades this fails at once, or 404s on stale package lists. Both fail closed, but in an attended window. Fix: `-o DPkg::Lock::Timeout=120`, run `update` first as the group template does, and add `DEBIAN_FRONTEND=noninteractive` and `--force-confold`. **Minor:** - `systemd-run` without `--collect` leaves a failed transient unit loaded when the witness fails. Add `--collect` and optionally `RuntimeMaxSec`. - `--check` doesn't confirm that chrony.service is enabled or that timesyncd is inactive. - `--check` prints the rollback hint even though it changed nothing. - A second run restarts chrony even when the config file is unchanged. - For the copy pass: the config and clock failure lines read as orders rather than saying what failed. One preflight message covers both bad arguments and not-root. - The before and after package states are printed without labels. - Host-init hand-off: - it pastes the whole script verbatim four times and no test covers it, so it will drift; - the heredoc becomes stdin for apt and `systemd-run --pipe`, which is fragile. Writing the file and running it with `</dev/null` is safer; - it carries `--check` parsing that means nothing at first boot. - The forbidden-command grep misses `stop`, `shutdown` and `poweroff`. - Shellcheck was never run because it isn't installed here. Run it somewhere before the attended window. The full review is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g2-prep/.superpowers/sdd/2026-11-05-region-ha-g2-prep/task-4-review.md`.</result> <usage><subagent_tokens>81718</subagent_tokens><tool_uses>10</tool_uses><duration_ms>178141</duration_ms></usage> </task-notification>
Attributed to this commit: 6.83 g CO₂e (883,817 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-g2-prep, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/region-ha-runbook.md b/docs/region-ha-runbook.md| index 7a9895164..fc8e8ebea 100644 |
| --- a/docs/region-ha-runbook.md |
| +++ b/docs/region-ha-runbook.md |
| @@ -89,10 +89,14 @@ bash scripts/region-ha-g3/chrony-fixed-box.sh |
| bash scripts/region-ha-g3/chrony-fixed-box.sh --check |
| ``` |
| -The install prints the package states before and after replacing `systemd-timesyncd` with `chrony`. It writes `server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4` to `/etc/chrony/conf.d/carlos-fixed.conf`, enables chrony and restarts it. It leaves `carlos-edge` and `host.env` alone and does not reboot the box. You can run it again to restore the same configuration. |
| +The install prints labelled package states before and after replacing `systemd-timesyncd` with `chrony`. It refreshes the apt package lists and allows up to 120 seconds for the dpkg lock. Package installation runs without prompts and keeps existing conffiles. It writes `server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4` to `/etc/chrony/conf.d/carlos-fixed.conf` and enables chrony. It restarts chrony on first installation or when that file changes. A second run with the same file still verifies synchronization. It leaves `carlos-edge` and `host.env` alone and does not reboot the box. |
| -Passing output includes a `^*` or `^+` source at `169.254.169.123`, a tracking CSV from `chronyc` running as `carlos` with the edge sandbox restrictions, and `Chrony checks passed.` The install also requires `chronyc waitsync 20 2` to succeed. Save the output with the G3 evidence. `--check` reads the package states, exact configuration and sources, then runs the tracking witness in a transient systemd unit. It does not install packages, write configuration or restart a service. |
| +Passing output includes a `^*` or `^+` source at `169.254.169.123`, a tracking CSV from `chronyc` running as `carlos` with the edge sandbox restrictions, and `Chrony checks passed.` The install also requires `chronyc waitsync 20 2` to succeed. Save the output with the G3 evidence. `--check` reads the package states, exact configuration and sources, reports service states, and requires chrony to be enabled and systemd-timesyncd to be inactive. It then runs the tracking witness in a transient systemd unit with a 30-second runtime limit and collection on success or failure. It does not install packages, write configuration, restart a service or print a rollback hint. |
| -If no matching source appears within 20 seconds, the script exits nonzero and leaves chrony installed. Synchronization or sandbox witness failures also stop the script. The rollback hint is `apt-get install systemd-timesyncd`; run it only if you decide to restore the previous time daemon. A failed check is not permission to continue to G3 step 4. |
| +If no matching source appears within 20 seconds, the script exits nonzero and leaves chrony installed. Synchronization or sandbox witness failures also stop the script. Any failure after changes begin reports what failed, the current package and service states, and this rollback hint. Run the command only if you decide to restore the previous time daemon. |
| -For new fixed boxes, add the matching chrony setup to the deployment's host-init source and template. Do not apply that user_data change to running boxes, and never re-run user_data on a live box. A user_data change in the flagship root can stop and start the box. Keep this first-boot change separate from the attended convergence above. |
| +To restore the previous time daemon, run NEEDRESTART_MODE=l DEBIAN_FRONTEND=noninteractive apt-get -y -q -o DPkg::Lock::Timeout=120 install systemd-timesyncd. This removes chrony. |
| + |
| +A failed check is not permission to continue to G3 step 4. |
| + |
| +For new fixed boxes, have the deployment's host-init copy the reviewed `scripts/region-ha-g3/chrony-fixed-box.sh` to the box and run it with `</dev/null` after the `carlos` account and `/etc/carlos` exist. Do not apply that user_data change to running boxes, and never re-run user_data on a live box. A user_data change in the flagship root can stop and start the box. Keep this first-boot change separate from the attended convergence above. |
diff --git a/scripts/region-ha-g3/chrony-fixed-box.sh b/scripts/region-ha-g3/chrony-fixed-box.sh| index ff88bee3a..d1c894a73 100755 |
| --- a/scripts/region-ha-g3/chrony-fixed-box.sh |
| +++ b/scripts/region-ha-g3/chrony-fixed-box.sh |
| @@ -1,20 +1,24 @@ |
| #!/bin/bash |
| -set -euo pipefail |
| +set -Eeuo pipefail |
| # Operator-facing output, collected here for the copy pass. |
| readonly PASS='Chrony checks passed.' |
| -readonly PREFLIGHT_FAILURE='Run as root on a fixed box with /etc/carlos present, with no arguments or only --check.' |
| -readonly CONFIG_FAILURE='Chrony configuration checks failed. Refuse symbolic links and require the fixed box configuration and installed chrony package.' |
| -readonly CLOCK_FAILURE='Chrony checks failed. Require an Amazon Time Sync source within 20 seconds and passing synchronization and sandbox checks.' |
| -readonly ROLLBACK='To restore the previous time daemon, run apt-get install systemd-timesyncd.' |
| +readonly ARGUMENT_FAILURE='Arguments are invalid. Use no arguments or only --check.' |
| +readonly PREFLIGHT_FAILURE='The root or fixed box prerequisite is missing. Run as root on a box with /etc/carlos present.' |
| +readonly CONFIG_FAILURE='Chrony configuration checks failed. Check for symbolic links, the fixed box configuration and the installed chrony package.' |
| +readonly CLOCK_FAILURE='No selected or candidate Amazon Time Sync source appeared within 20 seconds. Check chrony sources and network access.' |
| +readonly SERVICE_FAILURE='Time service checks failed. Enable chrony and confirm that systemd-timesyncd is inactive.' |
| +readonly COMMAND_FAILURE='A command failed at line %s: %s. Check the command error and current state below.\n' |
| +readonly ROLLBACK='To restore the previous time daemon, run NEEDRESTART_MODE=l DEBIAN_FRONTEND=noninteractive apt-get -y -q -o DPkg::Lock::Timeout=120 install systemd-timesyncd. This removes chrony.' |
| readonly CONF='/etc/chrony/conf.d/carlos-fixed.conf' |
| readonly SOURCE='server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4' |
| check=false |
| +mutating=false |
| if (( $# == 1 )) && [[ $1 == --check ]]; then |
| check=true |
| elif (( $# != 0 )); then |
| - printf '%s\n' "$PREFLIGHT_FAILURE" >&2 |
| + printf '%s\n' "$ARGUMENT_FAILURE" >&2 |
| exit 1 |
| fi |
| if [[ $(id -u) != 0 || ! -d /etc/carlos ]]; then |
| @@ -22,18 +26,33 @@ if [[ $(id -u) != 0 || ! -d /etc/carlos ]]; then |
| exit 1 |
| fi |
| -config_failure() { |
| - printf '%s\n' "$CONFIG_FAILURE" >&2 |
| +failure() { |
| + trap - ERR |
| + printf '%s\n' "$1" >&2 |
| + if "$mutating"; then |
| + printf '%s\n' 'Current package states.' >&2 |
| + package_states >&2 |
| + service_states >&2 |
| + printf '%s\n' "$ROLLBACK" >&2 |
| + fi |
| exit 1 |
| } |
| -clock_failure() { |
| - printf '%s\n' "$CLOCK_FAILURE" "$ROLLBACK" >&2 |
| - exit 1 |
| +command_failure() { |
| + failure "$(printf "$COMMAND_FAILURE" "$1" "$2")" |
| } |
| +trap 'command_failure "$LINENO" "$BASH_COMMAND"' ERR |
| check_paths() { |
| # Check parent directories too, including dangling destination links. |
| - [[ ! -L /etc/chrony && ! -L /etc/chrony/conf.d && ! -L $CONF ]] || config_failure |
| - [[ ! -e $CONF || -f $CONF ]] || config_failure |
| + [[ ! -L /etc/chrony && ! -L /etc/chrony/conf.d && ! -L $CONF ]] || failure "$CONFIG_FAILURE" |
| + [[ ! -e $CONF || -f $CONF ]] || failure "$CONFIG_FAILURE" |
| +} |
| +service_states() { |
| + chrony_enabled=$(systemctl is-enabled chrony.service) || true |
| + chrony_active=$(systemctl is-active chrony.service) || true |
| + timesyncd_active=$(systemctl is-active systemd-timesyncd.service) || true |
| + printf 'Chrony service enablement is %s.\n' "${chrony_enabled:-unknown}" |
| + printf 'Chrony service activity is %s.\n' "${chrony_active:-unknown}" |
| + printf 'Systemd timesyncd service activity is %s.\n' "${timesyncd_active:-unknown}" |
| } |
| package_states() { |
| # An absent package is useful evidence before installation, not a fatal error. |
| @@ -43,22 +62,36 @@ package_states() { |
| check_paths |
| states=$(package_states) |
| -printf '%s\n' "$states" |
| if "$check"; then |
| - [[ $states == *'chrony install ok installed'* ]] || config_failure |
| - [[ -f $CONF ]] && cmp -s "$CONF" <(printf '%s\n' "$SOURCE") || config_failure |
| + printf '%s\n' 'Current package states.' "$states" |
| + service_states |
| + [[ $chrony_enabled == enabled && $timesyncd_active == inactive ]] || failure "$SERVICE_FAILURE" |
| + [[ $states == *'chrony install ok installed'* ]] || failure "$CONFIG_FAILURE" |
| + [[ -f $CONF ]] && cmp -s "$CONF" <(printf '%s\n' "$SOURCE") || failure "$CONFIG_FAILURE" |
| cat "$CONF" |
| else |
| - NEEDRESTART_MODE=l apt-get -y -q install chrony |
| + printf '%s\n' 'Package states before installation.' "$states" |
| + restart=false |
| + [[ $states == *'chrony install ok installed'* ]] || restart=true |
| + mutating=true |
| + NEEDRESTART_MODE=l DEBIAN_FRONTEND=noninteractive apt-get -q -o DPkg::Lock::Timeout=120 update |
| + NEEDRESTART_MODE=l DEBIAN_FRONTEND=noninteractive apt-get -y -q -o DPkg::Lock::Timeout=120 \ |
| + -o Dpkg::Options::=--force-confold install chrony |
| + printf '%s\n' 'Package states after installation.' |
| package_states |
| check_paths |
| # mktemp uses the operator's on-disk TMPDIR, or /var/tmp when it is unset. |
| staging=$(mktemp "${TMPDIR:-/var/tmp}/carlos-chrony.XXXXXXXX") |
| trap 'rm -f -- "$staging"' EXIT |
| printf '%s\n' "$SOURCE" > "$staging" |
| - install -o root -g root -m 0644 "$staging" "$CONF" |
| + if ! cmp -s "$staging" "$CONF"; then |
| + install -o root -g root -m 0644 "$staging" "$CONF" |
| + restart=true |
| + fi |
| systemctl enable chrony.service |
| - systemctl restart chrony.service |
| + if "$restart"; then |
| + systemctl restart chrony.service |
| + fi |
| fi |
| # Match the group bootstrap's selected/candidate source rule. Cap slow chronyc |
| @@ -79,15 +112,16 @@ for ((attempt = 0; attempt < 20; attempt++)); do |
| (( SECONDS < deadline )) || break |
| sleep 1 |
| done |
| -"$synced" || clock_failure |
| +"$synced" || failure "$CLOCK_FAILURE" |
| if ! "$check"; then |
| - chronyc waitsync 20 2 || clock_failure |
| + chronyc waitsync 20 2 |
| fi |
| -systemd-run --wait --pipe --quiet \ |
| +systemd-run --wait --pipe --quiet --collect \ |
| + -p RuntimeMaxSec=30 \ |
| -p User=carlos \ |
| -p NoNewPrivileges=yes \ |
| -p ProtectSystem=strict \ |
| -p RestrictAddressFamilies='AF_INET AF_INET6 AF_UNIX' \ |
| -p SystemCallFilter=@system-service \ |
| - /usr/bin/chronyc -c tracking || clock_failure |
| + /usr/bin/chronyc -c tracking |
| printf '%s\n' "$PASS" |
diff --git a/scripts/region_ha_g3_chrony_test.py b/scripts/region_ha_g3_chrony_test.py| index e23669536..20a0668b4 100644 |
| --- a/scripts/region_ha_g3_chrony_test.py |
| +++ b/scripts/region_ha_g3_chrony_test.py |
| @@ -11,7 +11,14 @@ ROOT = Path(__file__).resolve().parent.parent |
| SCRIPT = ROOT / 'scripts/region-ha-g3/chrony-fixed-box.sh' |
| TEMPLATE = ROOT / 'infra/modules/region-host/group-init.sh.tftpl' |
| CONF = 'server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4\n' |
| -WITNESS = ['systemd-run', '--wait', '--pipe', '--quiet', '-p', 'User=carlos', |
| +APT_UPDATE = ['apt-get', '-q', '-o', 'DPkg::Lock::Timeout=120', 'update'] |
| +APT_INSTALL = ['apt-get', '-y', '-q', '-o', 'DPkg::Lock::Timeout=120', |
| + '-o', 'Dpkg::Options::=--force-confold', 'install', 'chrony'] |
| +ROLLBACK = ('To restore the previous time daemon, run NEEDRESTART_MODE=l ' |
| + 'DEBIAN_FRONTEND=noninteractive apt-get -y -q -o DPkg::Lock::Timeout=120 ' |
| + 'install systemd-timesyncd. This removes chrony.') |
| +WITNESS = ['systemd-run', '--wait', '--pipe', '--quiet', '--collect', |
| + '-p', 'RuntimeMaxSec=30', '-p', 'User=carlos', |
| '-p', 'NoNewPrivileges=yes', '-p', 'ProtectSystem=strict', |
| '-p', 'RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX', |
| '-p', 'SystemCallFilter=@system-service', '/usr/bin/chronyc', '-c', 'tracking'] |
| @@ -34,7 +41,18 @@ elif name == 'dpkg-query': |
| print(package + ' ' + state) |
| elif name == 'apt-get': |
| assert os.environ.get('NEEDRESTART_MODE') == 'l' |
| - pathlib.Path(os.environ['INSTALLED']).touch() |
| + assert os.environ.get('DEBIAN_FRONTEND') == 'noninteractive' |
| + if 'install' in args: |
| + pathlib.Path(os.environ['INSTALLED']).touch() |
| +elif name == 'systemctl' and args[0] in ('is-enabled', 'is-active'): |
| + if args[0] == 'is-enabled': |
| + state = os.environ.get('CHRONY_ENABLED', 'enabled') |
| + elif args[-1] == 'chrony.service': |
| + state = os.environ.get('CHRONY_ACTIVE', 'active') |
| + else: |
| + state = os.environ.get('TIMESYNCD_ACTIVE', 'inactive') |
| + print(state) |
| + sys.exit(0 if state in ('enabled', 'active') else 1) |
| elif name == 'chronyc' and args == ['-n', 'sources']: |
| print(os.environ.get('SOURCES', '^* 169.254.169.123 3 4 377 1 +0ns[+0ns] +/- 1ms')) |
| elif name == 'systemd-run': |
| @@ -71,7 +89,8 @@ class ChronyFixedBoxTests(unittest.TestCase): |
| source = SCRIPT.read_text().replace('/etc/carlos', str(self.marker)) |
| source = source.replace('/etc/chrony', str(self.root / 'etc/chrony')) |
| result = subprocess.run(['bash', '-c', source, 'chrony-fixed-box.sh', *args], |
| - env=dict(self.env, **env), capture_output=True, text=True, timeout=15) |
| + env=dict(self.env, **env), stdin=subprocess.DEVNULL, |
| + capture_output=True, text=True, timeout=15) |
| calls = [json.loads(line) for line in self.log.read_text().splitlines()] if self.log.exists() else [] |
| return result, calls |
| @@ -80,23 +99,33 @@ class ChronyFixedBoxTests(unittest.TestCase): |
| self.conf.write_text(CONF) |
| def test_happy_path_and_idempotence(self): |
| - for _ in range(2): |
| + for run in range(2): |
| self.log.unlink(missing_ok=True) |
| + before = self.conf.stat() if self.conf.exists() else None |
| result, calls = self.run_script() |
| self.assertEqual(result.returncode, 0, result.stderr) |
| self.assertEqual(self.conf.read_text(), CONF) |
| self.assertEqual(self.conf.stat().st_mode & 0o777, 0o644) |
| - self.assertEqual([c[0] for c in calls], ['id', 'dpkg-query', 'dpkg-query', 'apt-get', |
| - 'dpkg-query', 'dpkg-query', 'install', 'systemctl', 'systemctl', 'chronyc', |
| - 'chronyc', 'systemd-run']) |
| - self.assertIn(['apt-get', '-y', '-q', 'install', 'chrony'], calls) |
| - self.assertEqual(calls[7:11], [['systemctl', 'enable', 'chrony.service'], |
| - ['systemctl', 'restart', 'chrony.service'], ['chronyc', '-n', 'sources'], |
| - ['chronyc', 'waitsync', '20', '2']]) |
| + expected = ['id', 'dpkg-query', 'dpkg-query', 'apt-get', 'apt-get', |
| + 'dpkg-query', 'dpkg-query'] |
| + expected += ['install', 'systemctl', 'systemctl'] if run == 0 else ['systemctl'] |
| + expected += ['chronyc', 'chronyc', 'systemd-run'] |
| + self.assertEqual([c[0] for c in calls], expected) |
| + self.assertEqual(calls[3:5], [APT_UPDATE, APT_INSTALL]) |
| + self.assertIn(['systemctl', 'enable', 'chrony.service'], calls) |
| + self.assertEqual(calls[-3:-1], [['chronyc', '-n', 'sources'], |
| + ['chronyc', 'waitsync', '20', '2']]) |
| self.assertEqual(calls[-1], WITNESS) |
| - self.assertEqual(calls[6][1:7], ['-o', 'root', '-g', 'root', '-m', '0644']) |
| - self.assertFalse(Path(calls[6][-2]).exists(), 'staging file leaked') |
| - self.assertIn('chrony unknown ok not-installed' if _ == 0 else 'chrony install ok installed', result.stdout) |
| + if run == 0: |
| + self.assertIn(['systemctl', 'restart', 'chrony.service'], calls) |
| + self.assertEqual(calls[7][1:7], ['-o', 'root', '-g', 'root', '-m', '0644']) |
| + self.assertFalse(Path(calls[7][-2]).exists(), 'staging file leaked') |
| + else: |
| + self.assertNotIn(['systemctl', 'restart', 'chrony.service'], calls) |
| + self.assertEqual(self.conf.stat().st_mtime_ns, before.st_mtime_ns) |
| + self.assertIn('chrony unknown ok not-installed' if run == 0 else 'chrony install ok installed', result.stdout) |
| + self.assertIn('Package states before installation.', result.stdout) |
| + self.assertIn('Package states after installation.', result.stdout) |
| self.assertIn('systemd-timesyncd deinstall ok config-files', result.stdout) |
| self.assertIn('A9FEA97B,169.254.169.123', result.stdout) |
| self.assertIn('Chrony checks passed.', result.stdout) |
| @@ -106,7 +135,13 @@ class ChronyFixedBoxTests(unittest.TestCase): |
| before = self.conf.stat() |
| result, calls = self.run_script('--check') |
| self.assertEqual(result.returncode, 0, result.stderr) |
| - self.assertEqual([c[0] for c in calls], ['id', 'dpkg-query', 'dpkg-query', 'chronyc', 'systemd-run']) |
| + self.assertEqual([c[0] for c in calls], ['id', 'dpkg-query', 'dpkg-query', |
| + 'systemctl', 'systemctl', 'systemctl', 'chronyc', 'systemd-run']) |
| + self.assertIn(['systemctl', 'is-enabled', 'chrony.service'], calls) |
| + self.assertIn(['systemctl', 'is-active', 'systemd-timesyncd.service'], calls) |
| + self.assertIn('Chrony service enablement is enabled.', result.stdout) |
| + self.assertIn('Systemd timesyncd service activity is inactive.', result.stdout) |
| + self.assertNotIn(ROLLBACK, result.stdout + result.stderr) |
| self.assertEqual(calls[-1], WITNESS) |
| self.assertEqual(self.conf.stat().st_mtime_ns, before.st_mtime_ns) |
| self.assertEqual(self.conf.read_text(), CONF) |
| @@ -157,7 +192,7 @@ class ChronyFixedBoxTests(unittest.TestCase): |
| self.assertNotIn(WITNESS, calls) |
| self.assertTrue(self.installed.exists()) |
| self.assertIn('20', result.stderr) |
| - self.assertIn('apt-get install systemd-timesyncd', result.stderr) |
| + self.assertIn(ROLLBACK, result.stderr) |
| def test_candidate_source_passes(self): |
| result, _ = self.run_script(SOURCES='^+ 169.254.169.123') |
| @@ -182,18 +217,59 @@ class ChronyFixedBoxTests(unittest.TestCase): |
| result, calls = self.run_script(FAIL_AT=failure) |
| self.assertNotEqual(result.returncode, 0) |
| self.assertNotIn('Chrony checks passed.', result.stdout) |
| - self.assertIn('apt-get install systemd-timesyncd', result.stderr) |
| + self.assertIn(ROLLBACK, result.stderr) |
| if failure.startswith('chronyc'): |
| self.assertNotIn(WITNESS, calls) |
| def test_mutation_commands_fail_closed(self): |
| - for failure in ('apt-get -y -q install chrony', 'systemctl enable chrony.service', |
| - 'systemctl restart chrony.service'): |
| - self.log.unlink(missing_ok=True) |
| - result, calls = self.run_script(FAIL_AT=failure) |
| - self.assertNotEqual(result.returncode, 0) |
| - self.assertNotIn(WITNESS, calls) |
| - self.assertNotIn('Chrony checks passed.', result.stdout) |
| + for failure in (' '.join(APT_UPDATE), ' '.join(APT_INSTALL), |
| + 'systemctl enable chrony.service', 'systemctl restart chrony.service'): |
| + with self.subTest(failure=failure): |
| + self.log.unlink(missing_ok=True) |
| + self.conf.unlink(missing_ok=True) |
| + self.installed.unlink(missing_ok=True) |
| + result, calls = self.run_script(FAIL_AT=failure, CHRONY_ACTIVE='inactive') |
| + self.assertNotEqual(result.returncode, 0) |
| + self.assertNotIn(WITNESS, calls) |
| + self.assertNotIn('Chrony checks passed.', result.stdout) |
| + self.assertIn(failure, result.stderr) |
| + self.assertIn(ROLLBACK, result.stderr) |
| + self.assertIn('Current package states.', result.stderr) |
| + self.assertIn('chrony ', result.stderr) |
| + self.assertIn('systemd-timesyncd ', result.stderr) |
| + self.assertIn('Chrony service activity is inactive.', result.stderr) |
| + self.assertIn('Systemd timesyncd service activity is inactive.', result.stderr) |
| + |
| + def test_rollback_matches_runbook(self): |
| + self.assertIn(ROLLBACK, SCRIPT.read_text()) |
| + self.assertIn(ROLLBACK, (ROOT / 'docs/region-ha-runbook.md').read_text()) |
| + |
| + def test_check_failures_never_suggest_rollback(self): |
| + self.ready() |
| + for env in ({'CHRONY_ENABLED': 'disabled'}, {'TIMESYNCD_ACTIVE': 'active'}, |
| + {'SOURCES': ''}, {'FAIL_AT': ' '.join(WITNESS)}): |
| + with self.subTest(env=env): |
| + self.log.unlink(missing_ok=True) |
| + result, calls = self.run_script('--check', **env) |
| + self.assertNotEqual(result.returncode, 0) |
| + self.assertNotIn('install systemd-timesyncd', result.stdout + result.stderr) |
| + self.assertNotIn('apt-get', [c[0] for c in calls]) |
| + self.assertNotIn('install', [c[0] for c in calls]) |
| + self.assertTrue(all(c[1] in ('is-active', 'is-enabled') |
| + for c in calls if c[0] == 'systemctl')) |
| + |
| + def test_restarts_for_first_install_or_changed_config(self): |
| + for installed, config in ((False, CONF), (True, CONF.replace('minpoll 4', 'minpoll 6'))): |
| + with self.subTest(installed=installed): |
| + self.log.unlink(missing_ok=True) |
| + self.installed.unlink(missing_ok=True) |
| + if installed: |
| + self.installed.touch() |
| + self.conf.write_text(config) |
| + result, calls = self.run_script() |
| + self.assertEqual(result.returncode, 0, result.stderr) |
| + self.assertIn(['systemctl', 'restart', 'chrony.service'], calls) |
| + self.assertEqual(self.conf.read_text(), CONF) |
| def test_unknown_arguments_refused(self): |
| for args in (('--typo',), ('--check', 'extra')): |
| @@ -208,7 +284,18 @@ class ChronyFixedBoxTests(unittest.TestCase): |
| def test_forbidden_commands(self): |
| source = SCRIPT.read_text() |
| - self.assertNotRegex(source, r'\b(?:reboot|kill)\b|systemctl\s+restart\s+carlos|host\.env') |
| + forbidden = (r'(?m)(?:^|[;|&\n])\s*(?:exec\s+|sudo\s+)?(?:/\S*/)?' |
| + r'(?:reboot|kill|stop|shutdown|poweroff)(?=\s|[;|&]|$)' |
| + r'|\bsystemctl\b[^\n;|&]*\bstop\b' |
| + r'|\bsystemctl\b[^\n;|&]*\brestart\b[^\n;|&]*\bcarlos(?:[-.\s]|$)' |
| + r'|host\.env') |
| + self.assertNotRegex(source, forbidden) |
| + for command in ('stop chrony', 'shutdown -h now', '/sbin/poweroff', |
| + 'systemctl --no-block stop chrony', |
| + 'systemctl restart --no-block carlos-edge.service'): |
| + self.assertRegex(command, forbidden) |
| + for allowed in ('systemctl restart chrony.service', 'echo stopping.', 'echo poweroffline.'): |
| + self.assertNotRegex(allowed, forbidden) |
| self.assertNotRegex(source, '[\u2013\u2014]') |