ТОЙОТАРЕМОНТ СЕРВИС

Unattended Security Upgrades and Kernel Reboot Checks: Update Ubuntu Command Line Focus (28)

СЕРВИС Тойота В МОСКВЕ › Рубрика: LAND CRUISER › Unattended Security Upgrades and Kernel Reboot Checks: Update Ubuntu Command Line Focus (28)
0 +1 -1
Sue O'Shaughnessy спросил 4 дня назад

# Unattended Security Upgrades and Kernel Reboot Checks: Update Ubuntu Command Line Focus (28)

## Executive Summary (BLUF)

Administrators who routinely update Ubuntu via the command line often encounter `dpkg` frontend lock contention, unexpected `needrestart` interactive prompts, or silent kernel updates that wait weeks for a reboot. Harmonizing manual CLI patching (`apt update && apt full-upgrade`) with automated `unattended-upgrades` requires aligning systemd timer schedules, configuring non-interactive `needrestart` policies, and checking `/var/run/reboot-required` as part of every terminal maintenance routine.

By tuning `apt-daily-upgrade.timer` to run outside interactive work hours, enforcing `DPkg::Lock::Timeout` on manual CLI invocations, and standardizing post-upgrade verification via `needrestart -k`, operators eliminate lock collisions and keep both command-line and unattended patching workflows predictable.

## Harmonizing Manual CLI Patching with Unattended Systemd Timers

When operators more.. sessions interactively, they expect immediate access to `/var/lib/dpkg/lock-frontend`. However, Ubuntu ships with `apt-daily.timer` and `apt-daily-upgrade.timer` enabled by default. If a background `unattended-upgrade` run is active when an administrator logs in and executes `sudo apt upgrade`, APT aborts or blocks waiting for the lock.

The root cause is a lack of coordination between interactive CLI habits and background systemd timers. Rather than disabling `unattended-upgrades`—which leaves systems unpatched between manual sessions—administrators can configure both workflows to coexist cleanly:

1. **Lock Timeout Resilience**: Passing `-o DPkg::Lock::Timeout=60` in manual `apt` aliases or `/etc/apt/apt.conf.d/99lock-timeout` instructs interactive CLI commands to wait gracefully up to 60 seconds for a background `unattended-upgrade` transaction to finish instead of failing immediately. Under the hood, APT polls `/var/lib/dpkg/lock-frontend` and `/var/lib/apt/lists/lock` at short intervals while printing a clean waiting message rather than aborting with exit code 100.
2. **Timer Window Alignment**: Overriding `apt-daily-upgrade.timer` via `systemctl edit apt-daily-upgrade.timer` to run at `04:00` with a 30-minute `RandomizedDelaySec` moves background package extraction out of daytime terminal hours. Administrators should also inspect `apt-daily.timer` (which runs `apt-get update` and pre-downloads `.deb` archives) so the list refresh completes at least an hour before `apt-daily-upgrade.timer` fires.
3. **Unified Reboot Telemetry**: Whether a kernel update arrives via `sudo apt full-upgrade` or `unattended-upgrades`, both paths invoke the same `linux-image` maintainer scripts that populate `/var/run/reboot-required` and `/var/run/reboot-required.pkgs`. Checking these files—alongside `needrestart -r l`—gives CLI operators an exact view of pending kernel and daemon transitions. On servers running `byobu` or `tmux` status bars, or standard SSH MOTD scripts in `/etc/update-motd.d/98-reboot-required`, this flag surfaces immediately at login so operators know when a maintenance reboot is pending.

## Strategic Frameworks and Architectural Breakdown

Coordinating interactive terminal patching and automated security upgrades relies on a shared lock-aware pipeline.

```text
+-------------------------------------------------------------------+
| UNIFIED CLI & UNATTENDED APT PIPELINE |
+-------------------------------------------------------------------+
| |
v v
+--------------------+ +--------------------+
| Interactive CLI | | Systemd Timer |
| apt full-upgrade | | apt-daily-upgrade |
| (Lock Timeout 60s) | | (04:00 Off-Peak) |
+--------------------+ +--------------------+
| |
+---------------------+---------------------+
|
v
+-----------------------------+
| /var/lib/dpkg/lock-frontend |
| Serialized Transaction Gate |
+-----------------------------+
|
v
+-----------------------------+
| Post-Upgrade Reconciliation |
| - needrestart (CLI vs Auto) |
| - apt-get autoremove check |
| - /var/run/reboot-required |
+-----------------------------+
```

The framework prevents race conditions through four controls:

1. **Serialized Lock Acquisition**: Both manual CLI commands and `unattended-upgrades` respect `lock-frontend`. Adding a global `DPkg::Lock::Timeout` prevents CI scripts and SSH maintenance sessions from crashing on transient lock contention.
2. **Consistent `needrestart` Behavior**: On modern Ubuntu releases, `needrestart` defaults to interactive TUI prompts during manual `apt` runs, which can stall automated SSH scripts. Configuring `NEEDRESTART_MODE=l` (list only) or `a` (automatic) in `/etc/needrestart/needrestart.conf` ensures deterministic behavior across both interactive terminals and background upgrades.
3. **Phased Update Visibility**: When running `apt upgrade` from the command line, Ubuntu may hold back packages due to `Phased-Updates`. Unattended upgrades also honor phasing by default for `-updates` pockets, whereas `-security` patches apply immediately. Understanding this prevents operators from misdiagnosing "kept back" packages as broken dependencies.
4. **Kernel & `/boot` Verification**: After every manual or automated upgrade, checking `uname -r` against `ls -1 /boot/vmlinuz-*` and `/var/run/reboot-required` confirms whether the running kernel matches the newest installed image.

## Comparative Matrix: Legacy Execution vs Modern Practice

Command-line Ubuntu maintenance has matured from raw `apt-get` one-liners to lock-tolerant, telemetry-driven workflows.

| Maintenance Dimension | Legacy Execution (Ad-Hoc `apt-get` & Disabled Timers) | Modern Practice (Lock-Aware `apt` & Coordinated Timers) | Operational Benefit |
|---|---|---|---|
| **Lock Contention** | Immediate failure with `Could not get lock /var/lib/dpkg/lock` | `DPkg::Lock::Timeout=60` in `/etc/apt/apt.conf.d/` | Eliminates transient script failures when timers overlap |
| **Timer Scheduling** | Default random daytime runs interrupting SSH sessions | Systemd drop-in overriding `OnCalendar=04:00` | Keeps interactive work hours free of `dpkg` lock waits |
| **Daemon Restarts** | Guessing which services need bouncing after `apt upgrade` | `needrestart -r l` or automatic mode in `DPkg::Post-Invoke` | Surfaces exact PIDs and systemd units holding deleted libraries |
| **Kernel Tracking** | Comparing `dpkg -l linux-image*` by eye | Reading `/var/run/reboot-required.pkgs` and `needrestart -k` | Automates reboot readiness checks in terminal prompts |
| **Unused Package Pruning** | Forgetting `apt autoremove` until `/boot` hits 100% | `Remove-Unused-Kernel-Packages "true"` + CLI `--purge` | Maintains clean `/boot` partitions automatically |
| **Config Prompts** | Unexpected `ncurses` conffile menus in SSH | `--force-confdef --force-confold` for unattended runs | Prevents hung background processes while allowing manual review |

## Governance, Best Practices, and Compliance Controls

Even when administrators prefer updating Ubuntu from the command line, governance policies must ensure security patches are never skipped due to human absence.

**Never Disable `unattended-upgrades` Without Replacement**
A common anti-pattern when troubleshooting APT lock errors is running `sudo systemctl disable --now apt-daily-upgrade.timer`. Doing so creates a security blind spot whenever operators are away. Instead, keep `unattended-upgrades` enabled for `-security` origins and shift the timer schedule to off-peak hours.

**Shell Alias and Script Hygiene**
Administrators writing maintenance scripts should avoid `apt` (whose CLI output warns it does not have a stable script interface) in favor of `apt-get -y` with `DEBIAN_FRONTEND=noninteractive` for automated jobs, reserving `apt` for interactive human sessions. Always pair `apt-get update` with `&&` so upgrades never execute against stale package indices.

**Audit Trail Continuity**
Both manual CLI upgrades and `unattended-upgrades` write to `/var/log/apt/history.log` and `/var/log/apt/term.log`. Retaining these logs via `logrotate` for at least 90 days provides complete visibility into who triggered a package change, which flags were passed, and whether a kernel reboot was deferred.

**Verification Before Rebooting**
Before issuing `sudo systemctl reboot` from the command line after a kernel upgrade, operators should verify that `fuser /var/lib/dpkg/lock-frontend` returns empty so a background `unattended-upgrade` is not killed mid-unpack. Checking `systemctl list-jobs` also confirms no `apt-daily-upgrade.service` or `fwupd.service` firmware flash is actively running.

**Handling Interrupted Transactions Cleanly**
If an SSH session drops mid-upgrade during a manual CLI session without `tmux` or `screen`, `dpkg` can leave packages in an unpacked, unconfigured state. Rather than deleting lock files manually—which risks database corruption—always run `sudo dpkg --configure -a` followed by `sudo apt-get -f install` to let `dpkg` replay its journaled triggers cleanly before re-enabling unattended runs. Running interactive CLI upgrades inside `tmux` or `screen` is a simple operational safeguard that prevents dropped SSH connections from interrupting `dpkg` maintainer scripts in the first place.

## Implementation Roadmap

Standardizing command-line and unattended Ubuntu patching takes four structured phases.

### Phase 1: Lock Timeout and Timer Schedule Alignment
Create `/etc/apt/apt.conf.d/99lock-timeout` containing `DPkg::Lock::Timeout "60";` so all CLI `apt` and `apt-get` calls wait gracefully for background locks. Inspect current timer schedules with `systemctl cat apt-daily-upgrade.timer`, and create a systemd drop-in (`sudo systemctl edit apt-daily-upgrade.timer`) to set `OnCalendar=04:00` and `RandomizedDelaySec=30m`.

### Phase 2: Unattended Security Policy & `needrestart` Tuning
Verify `/etc/apt/apt.conf.d/50unattended-upgrades` restricts automatic installs to `-security` origins and enables `Remove-Unused-Kernel-Packages "true"`. Configure `/etc/needrestart/conf.d/99-cli-policy.conf` so automated runs restart stateless daemons cleanly without hanging, while interactive CLI runs display a clear summary of any services or kernels requiring attention.

### Phase 3: CLI Reboot Check & Pre-Reboot Guardrails
Add a lightweight status check to `/etc/update-motd.d/` or your shell profile that tests `/var/run/reboot-required` and prints `/var/run/reboot-required.pkgs` upon SSH login. Create a helper alias or script that checks `needrestart -b` and ensures no `dpkg` lock is active before running `sudo systemctl reboot`.

### Phase 4: End-to-End Dry Run and Log Verification
Simulate an unattended run with `sudo unattended-upgrade --dry-run --debug`, then perform a manual `sudo apt update && sudo apt upgrade` to confirm `DPkg::Lock::Timeout` and `needrestart` behave as configured. Inspect `/var/log/apt/history.log` and `/var/log/unattended-upgrades/unattended-upgrades.log` to confirm unified, error-free audit records.

## Frequently Asked Questions (FAQ)

### Why does `sudo apt update` sometimes say the `dpkg` frontend lock is held by `unattended-upgr`?
Ubuntu's `apt-daily-upgrade.timer` triggers `unattended-upgrades` automatically in the background. If you run `apt` from the command line at the same moment, `unattended-upgr` holds `/var/lib/dpkg/lock-frontend` to protect package database integrity. Configuring `DPkg::Lock::Timeout "60";` makes your CLI command wait until the background job finishes.

### Is it safe to kill `unattended-upgr` if I want to run `apt upgrade` immediately?
No. Terminating `unattended-upgr` or `dpkg` mid-transaction can leave packages in a half-configured state, requiring manual repair with `sudo dpkg --configure -a`. Always wait for the background process to release the lock or use a lock timeout.

### What is the difference between `apt upgrade` and `apt full-upgrade` for kernel updates?
`apt upgrade` installs newer versions of existing packages without removing anything, which can hold back new `linux-image-*` meta-packages if they require installing a new versioned kernel package. `apt full-upgrade` (and `unattended-upgrades` when configured) handles kernel transitions and obsolete dependency removal cleanly.

### Why does Ubuntu say packages have been "kept back" when I run `apt upgrade` from the CLI?
Ubuntu uses Phased Updates to roll out non-security updates gradually to a percentage of machines. When a package is in a phased rollout that your machine has not yet reached, `apt` intentionally keeps it back until the rollout percentage expands or a regression check completes.

### How can I check from the command line if a kernel update is waiting for a reboot?
Run `ls -l /var/run/reboot-required` or `sudo needrestart -k`. If `/var/run/reboot-required` exists or `needrestart -k` reports an expected kernel version newer than the running kernel, a reboot is required to activate the patched kernel.

### Should I run `apt autoremove` manually if `unattended-upgrades` is already enabled?
If `Unattended-Upgrade::Remove-Unused-Kernel-Packages "true"` and `Remove-Unused-Dependencies "true"` are set in `50unattended-upgrades`, `unattended-upgrades` handles most cleanup automatically. However, running `sudo apt autoremove --purge` periodically during manual CLI maintenance is still good practice to clear orphaned packages installed manually.

### How do I make `apt` wait for `unattended-upgr` automatically in every terminal session without typing `-o DPkg::Lock::Timeout=60`?
Create a drop-in file at `/etc/apt/apt.conf.d/99lock-timeout` containing the single line `DPkg::Lock::Timeout "60";`. Both `apt` and `apt-get` read every file in `/etc/apt/apt.conf.d/` automatically, so every manual CLI invocation will inherit the 60-second wait behavior.

### Can I trigger `unattended-upgrades` manually from the command line to test my configuration?
Yes. Run `sudo unattended-upgrade -d --dry-run` to simulate the exact origin matching, package selection, and `dpkg` planning in debug mode without modifying the system. Remove `--dry-run` when you are ready to execute the upgrade immediately.

## Conclusion

Updating Ubuntu from the command line and running `unattended-upgrades` are complementary rather than competing practices. By adding `DPkg::Lock::Timeout`, shifting `apt-daily-upgrade.timer` to off-peak hours, standardizing `needrestart` behavior, and checking `/var/run/reboot-required` before every reboot, CLI administrators gain fast, conflict-free terminal workflows backed by continuous automated security patching.