Repository navigation
Retry the Package Upgrade Once After a Mirror Mismatch in upgrade-host.sh #4532
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
8c9a4b1
Retry the Package Upgrade Once After a Mirror Mismatch in upgrade-hos…
ptr727 f887bb0
Retry a Failed Package List Read Once as Well
ptr727 0c67513
Retry the Fetching Installs and Leave Acquire::Retries to apt
ptr727 9be87a6
Assert the Retried apt-get Call Keeps Its Full Arguments
ptr727 e6fef52
Wait for the Retry Delay in the Background and Guard the apt-get Call…
ptr727 c10cea9
Test the Interrupt During the Retry Wait and Tighten the apt-get Site…
ptr727 fdd3e77
Collect the Killed Retry Wait in the Interrupt Trap
ptr727 dfba6ae
Assert Every Retried apt-get Call in Full and Read the Sleep Pid Once…
ptr727 5601c48
Keep the Retry Wait in the Foreground Like Every Other Command
ptr727 a8fa745
Pin Every apt-get Mention in the Call-Site Guard
ptr727 2f32376
Reuse the Retried-Call Assertion and Say a List Read Retries Alone
ptr727 6247a9c
Scope the Retry Wording to apt-get
ptr727 1a8a215
Name the Retry Section for the apt-get Calls It Covers
ptr727 94981e4
Name UTF-8 on the Upgrade Test's Text-Mode Spawn
ptr727 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,240 @@ | ||
| #!/usr/bin/env python3 | ||
| """Tests for `upgrade-host.sh --packages` retrying a failed upgrade, driven through the whole script. | ||
|
|
||
| Every command that would change the host is a stub on `PATH`: `apt-get`, `sudo`, `snap`, and `systemctl`. | ||
| `sleep` is stubbed too, so the retry's wait is recorded rather than spent. | ||
| Each `apt-get` stub fails on the attempts its `FAIL_<subcommand>` variable lists, which stands in for a mirror caught mid-sync. | ||
|
|
||
| Run as `python3 tests/test_upgrade_host_linux.py`, or under `python3 -m unittest discover -s tests`. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| import re | ||
| import shutil | ||
| import subprocess | ||
| import sys | ||
| import tempfile | ||
| import unittest | ||
| from pathlib import Path | ||
|
|
||
| ROOT = Path(__file__).resolve().parent.parent | ||
| UPGRADER = ROOT / "host-setup" / "linux" / "upgrade-host.sh" | ||
|
|
||
| APT_GET_STUB = """#!/bin/bash | ||
| set -Eeuo pipefail | ||
| printf 'apt-get %s\\n' "$*" >>"$STUB_LOG" | ||
| sub=${1//-/_} | ||
| count_file="$STUB_DIR/count.$sub" | ||
| count=$(($(cat "$count_file" 2>/dev/null || printf 0) + 1)) | ||
| printf '%s' "$count" >"$count_file" | ||
| fail_var="FAIL_$sub" | ||
| for attempt in ${!fail_var:-}; do | ||
| if [[ $attempt == "$count" ]]; then | ||
| printf 'E: Unable to fetch some archives, attempt %s\\n' "$count" >&2 | ||
| exit 100 | ||
| fi | ||
| done | ||
| """ | ||
|
|
||
| RECORDING_STUB = """#!/bin/bash | ||
| printf '%s %s\\n' "$(basename "$0")" "$*" >>"$STUB_LOG" | ||
| """ | ||
|
|
||
| SUDO_STUB = """#!/bin/bash | ||
| exec "$@" | ||
| """ | ||
|
|
||
| INACTIVE_STUB = """#!/bin/bash | ||
| exit 1 | ||
| """ | ||
|
|
||
|
|
||
| @unittest.skipUnless( | ||
| sys.platform.startswith("linux") and Path("/etc/os-release").is_file(), | ||
| "runs the Linux upgrader", | ||
| ) | ||
| class TestPackageUpgradeRetry(unittest.TestCase): | ||
| def setUp(self) -> None: | ||
| self.work = Path(tempfile.mkdtemp(prefix="upgrade-host-")) | ||
| self.addCleanup(shutil.rmtree, self.work) | ||
| self.bin = self.work / "bin" | ||
| self.bin.mkdir() | ||
| self.log = self.work / "calls.log" | ||
| stubs = { | ||
| "apt-get": APT_GET_STUB, | ||
| "sleep": RECORDING_STUB, | ||
| "snap": RECORDING_STUB, | ||
| "sudo": SUDO_STUB, | ||
| "systemctl": INACTIVE_STUB, | ||
| } | ||
| for name, body in stubs.items(): | ||
| stub = self.bin / name | ||
| stub.write_text(body, encoding="utf-8") | ||
| stub.chmod(0o755) | ||
|
|
||
| def run_upgrade( | ||
| self, *args: str, fail: dict[str, str], stdin: int | None = None | ||
| ) -> subprocess.CompletedProcess[str]: | ||
| env = dict(os.environ) | ||
| env.update({f"FAIL_{sub}": attempts for sub, attempts in fail.items()}) | ||
| env.update( | ||
| { | ||
| "PATH": f"{self.bin}{os.pathsep}{env.get('PATH', '')}", | ||
| "STUB_DIR": str(self.work), | ||
| "STUB_LOG": str(self.log), | ||
| "TMPDIR": str(self.work), | ||
| } | ||
| ) | ||
| return subprocess.run( | ||
| ["bash", str(UPGRADER), "--packages", *args], | ||
| env=env, | ||
| stdin=stdin if stdin is not None else subprocess.DEVNULL, | ||
| capture_output=True, | ||
| text=True, | ||
| encoding="utf-8", | ||
| timeout=60, | ||
| check=False, | ||
| ) | ||
|
|
||
| def calls(self) -> list[str]: | ||
| if not self.log.exists(): | ||
| return [] | ||
| return [ | ||
| " ".join(line.split()[:2]) for line in self.log.read_text(encoding="utf-8").splitlines() | ||
|
ptr727 marked this conversation as resolved.
Resolved
|
||
| ] | ||
|
|
||
| def full_calls(self) -> list[str]: | ||
| if not self.log.exists(): | ||
| return [] | ||
| return self.log.read_text(encoding="utf-8").splitlines() | ||
|
|
||
| def assert_retried_call_kept_its_arguments(self, subcommand: str, expected: str) -> None: | ||
| lines = [line for line in self.full_calls() if line.split()[:2] == ["apt-get", subcommand]] | ||
| self.assertEqual(lines, [expected, expected]) | ||
|
|
||
| def test_an_unattended_upgrade_that_fails_once_reads_the_lists_again_and_succeeds(self) -> None: | ||
| result = self.run_upgrade("--yes", fail={"full_upgrade": "1"}) | ||
| self.assertEqual(result.returncode, 0, result.stderr) | ||
| self.assertEqual( | ||
| self.calls(), | ||
| [ | ||
| "apt-get update", | ||
| "apt-get full-upgrade", | ||
| "sleep 90", | ||
| "apt-get update", | ||
| "apt-get full-upgrade", | ||
| "apt-get install", | ||
| "apt-get autoremove", | ||
| "apt-get autoclean", | ||
| ], | ||
| ) | ||
| self.assertIn("a mirror still syncing is the usual cause", result.stderr) | ||
| self.assert_retried_call_kept_its_arguments( | ||
| "full-upgrade", | ||
| "apt-get full-upgrade -y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold", | ||
| ) | ||
|
|
||
| def test_an_unattended_upgrade_that_fails_twice_stops_with_apt_s_status(self) -> None: | ||
| result = self.run_upgrade("--yes", fail={"full_upgrade": "1 2"}) | ||
| self.assertEqual(result.returncode, 100, result.stderr) | ||
| self.assertEqual( | ||
| self.calls(), | ||
| [ | ||
| "apt-get update", | ||
| "apt-get full-upgrade", | ||
| "sleep 90", | ||
| "apt-get update", | ||
| "apt-get full-upgrade", | ||
| ], | ||
| ) | ||
|
|
||
| def test_a_failed_list_read_before_the_retry_stops_the_run(self) -> None: | ||
| result = self.run_upgrade("--yes", fail={"full_upgrade": "1", "update": "2"}) | ||
| self.assertEqual(result.returncode, 100, result.stderr) | ||
| self.assertEqual( | ||
| self.calls(), ["apt-get update", "apt-get full-upgrade", "sleep 90", "apt-get update"] | ||
| ) | ||
|
|
||
| def test_an_unattended_list_read_that_fails_once_is_retried_alone(self) -> None: | ||
| result = self.run_upgrade("--yes", fail={"update": "1"}) | ||
| self.assertEqual(result.returncode, 0, result.stderr) | ||
| self.assertEqual( | ||
| self.calls(), | ||
| [ | ||
| "apt-get update", | ||
| "sleep 90", | ||
| "apt-get update", | ||
| "apt-get full-upgrade", | ||
| "apt-get install", | ||
| "apt-get autoremove", | ||
| "apt-get autoclean", | ||
| ], | ||
| ) | ||
| self.assert_retried_call_kept_its_arguments( | ||
| "update", | ||
| "apt-get update -y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold", | ||
| ) | ||
|
|
||
| def test_an_unattended_install_that_fails_once_reads_the_lists_again_and_succeeds(self) -> None: | ||
| result = self.run_upgrade("--yes", fail={"install": "1"}) | ||
| self.assertEqual(result.returncode, 0, result.stderr) | ||
| self.assertEqual( | ||
| self.calls(), | ||
| [ | ||
| "apt-get update", | ||
| "apt-get full-upgrade", | ||
| "apt-get install", | ||
| "sleep 90", | ||
| "apt-get update", | ||
| "apt-get install", | ||
| "apt-get autoremove", | ||
| "apt-get autoclean", | ||
| ], | ||
| ) | ||
| self.assert_retried_call_kept_its_arguments( | ||
| "install", | ||
| "apt-get install -f -y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold", | ||
| ) | ||
|
|
||
| def test_every_apt_get_call_site_but_the_retry_helper_s_own_is_a_deliberate_choice( | ||
| self, | ||
| ) -> None: | ||
| mention = re.compile(r"(?<![\w-])apt[_-]get(?![\w-])") | ||
| sites = [ | ||
| line.strip() | ||
| for line in UPGRADER.read_text(encoding="utf-8").splitlines() | ||
| if mention.search(line) and not line.lstrip().startswith("#") | ||
| ] | ||
| self.assertEqual( | ||
| sites, | ||
| [ | ||
| "retry a failed apt-get list read, install, or upgrade once", | ||
| 'command -v apt-get >/dev/null || die "apt-get not found, this script upgrades apt based hosts"', | ||
| 'apt_get() { run_root apt-get "$@" "${APT_OPTS[@]}"; }', | ||
| 'apt_get "$@" || status=$?', | ||
| 'warn "apt-get $* failed (exit $status), a mirror still syncing is the usual cause"', | ||
| "apt_get update", | ||
| 'apt_get "$@"', | ||
| "apt_get autoremove --purge", | ||
| "run_root apt-get autoclean", | ||
| "apt_get autoremove --purge", | ||
| "run_root apt-get autoclean", | ||
| ], | ||
| ) | ||
|
|
||
| def test_an_attended_upgrade_is_not_retried(self) -> None: | ||
| primary, secondary = os.openpty() | ||
| self.addCleanup(os.close, primary) | ||
| try: | ||
| os.write(primary, b"y\n") | ||
| result = self.run_upgrade(fail={"full_upgrade": "1"}, stdin=secondary) | ||
| finally: | ||
| os.close(secondary) | ||
| self.assertEqual(result.returncode, 100, result.stderr) | ||
| self.assertEqual(self.calls(), ["apt-get update", "apt-get full-upgrade"]) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.