Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions host-setup/linux/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ An install or upgrade collects a tool whose install fails and carries on, so one

The cache stays valid for 60 minutes, from `SUDO_TIMESTAMP_TIMEOUT` in the script. Removing the drop-in undoes the sharing. Where the run also switched the sudo alternative, `update-alternatives --auto sudo` is what undoes that half.

## An Unattended apt-get Call Is Retried Once

**An unattended run retries a failed `apt-get` list read, install, or upgrade once.** A third party repository republishing a nightly channel can serve files that disagree with its own index for a while. apt then drops the whole transaction, and every other pending upgrade goes with the one bad package. apt's own fetch retries, on by default since apt 2.3.2, read that same stale index. So `upgrade-host.sh --yes` waits 90 seconds, runs `apt-get update` again, and retries the call. The installs it runs are retried the same way, since they fetch from the same mirrors. A failed `apt-get update` is retried too, after the same wait and with no extra list read. The same window can serve index files that fail their size or hash check. A second failure stops the run with apt's own status, so a fault that persists still surfaces. That includes the list read inside a retry, which is not retried again. An attended run does not retry, because a declined prompt also exits non-zero and the operator is there to see the error. [`tests/test_upgrade_host_linux.py`][test-upgrade-host-linux] drives the retry against a stubbed `apt-get`.

## Release Upgrades

`upgrade-host.sh` splits the routine from the rare. `--packages` upgrades within the current release, and `--release` is its own action because the release upgrade is where hosts differ.
Expand Down Expand Up @@ -205,6 +209,7 @@ CI checks the scripts with `shellcheck` and `shfmt`. It runs both over every `.s
[setup-github]: ./setup-github.sh
[skills-install]: ../../scripts/skills_install.py
[test-bootstrap]: ../../tests/test_bootstrap.py
[test-upgrade-host-linux]: ../../tests/test_upgrade_host_linux.py
[upgrade-host]: ./upgrade-host.sh
[windows-readme]: ../windows/README.md

Expand Down
37 changes: 27 additions & 10 deletions host-setup/linux/upgrade-host.sh
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
set -Eeuo pipefail

readonly BACKUP_ROOT="/var/backups/upgrade-host"
readonly APT_RETRY_DELAY=90

MODE="packages"
DRY_RUN=false
Expand Down Expand Up @@ -93,7 +94,8 @@ Actions, name one, default --packages:

Options:
-n, --dry-run Print the commands instead of running them
-y, --yes Do not prompt, and keep the installed config file on a packaging conflict
-y, --yes Do not prompt, keep the installed config file on a packaging conflict, and
retry a failed apt-get list read, install, or upgrade once

A release upgrade moves one release at a time, which is what both distributions support: a host two
releases behind is upgraded by running this twice. Debian is carried by rewriting the codename in
Expand Down Expand Up @@ -173,6 +175,21 @@ run_root() { run "${SUDO[@]}" "$@"; }

apt_get() { run_root apt-get "$@" "${APT_OPTS[@]}"; }

apt_retry() {
local status=0
apt_get "$@" || status=$?
if [[ $status -eq 0 || $ASSUME_YES != true ]]; then
return "$status"
fi
warn "apt-get $* failed (exit $status), a mirror still syncing is the usual cause"
info "Waiting ${APT_RETRY_DELAY}s, then retrying once"
sleep "$APT_RETRY_DELAY"
if [[ $1 != "update" ]]; then
apt_get update
fi
apt_get "$@"
}

confirm() {
[[ $ASSUME_YES == true || $DRY_RUN == true ]] && return 0
[[ -t 0 ]] || die "Not a terminal and --yes was not given, refusing to change the host unattended"
Expand All @@ -192,13 +209,13 @@ fetch() {

upgrade_packages() {
step "Updating package lists"
apt_get update
apt_retry update

step "Upgrading packages"
apt_get full-upgrade
apt_retry full-upgrade

step "Completing any partial install"
apt_get install -f
apt_retry install -f

step "Removing unused packages and old kernels"
apt_get autoremove --purge
Expand Down Expand Up @@ -326,8 +343,8 @@ ensure_release_prerequisites() {
command -v curl >/dev/null && return 0

step "Installing curl, which the release index is read with"
apt_get update
apt_get install curl ca-certificates
apt_retry update
apt_retry install curl ca-certificates
}

backup_sources() {
Expand Down Expand Up @@ -533,15 +550,15 @@ debian_release_upgrade() {
debian_rewrite_sources "$CODENAME" "$next"

step "Reading the $next package lists"
apt_get update
apt_retry update

# The release notes take the minimal upgrade first.
# So the packages that need no new dependencies land before the ones that pull in a changed dependency set.
step "Upgrading without new packages"
apt_get upgrade --without-new-pkgs
apt_retry upgrade --without-new-pkgs
Comment thread
ptr727 marked this conversation as resolved.
Resolved

step "Upgrading the rest of the distribution"
apt_get full-upgrade
apt_retry full-upgrade

step "Removing what $next no longer needs"
apt_get autoremove --purge
Expand All @@ -554,7 +571,7 @@ ubuntu_release_upgrade() {
step "Checking for a new Ubuntu release"

if ! command -v do-release-upgrade >/dev/null; then
apt_get install update-manager-core
apt_retry install update-manager-core
fi

# Which release is offered, LTS or every release, is the host's own policy in /etc/update-manager/release-upgrades rather than something to decide here.
Expand Down
240 changes: 240 additions & 0 deletions tests/test_upgrade_host_linux.py
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()
Comment thread
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()
Loading