Skip to content
Draft
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
9 changes: 9 additions & 0 deletions crates/lib/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@ pub(crate) struct UpgradeOpts {
/// Restart or reboot into the new target image.
///
/// Use --soft-reboot to request a userspace-only restart when supported.
///
/// The reboot is refused if a process holds a `block` mode shutdown
/// inhibitor lock (see `systemd-inhibit --list`).
#[clap(long, conflicts_with = "check")]
pub(crate) apply: bool,

Expand Down Expand Up @@ -154,6 +157,9 @@ pub(crate) struct SwitchOpts {
/// Restart or reboot into the new target image.
///
/// Use --soft-reboot to request a userspace-only restart when supported.
///
/// The reboot is refused if a process holds a `block` mode shutdown
/// inhibitor lock (see `systemd-inhibit --list`).
#[clap(long)]
pub(crate) apply: bool,

Expand Down Expand Up @@ -235,6 +241,9 @@ pub(crate) struct RollbackOpts {
/// Currently, this option always reboots. In the future this command
/// will detect the case where no kernel changes are queued, and perform
/// a userspace-only restart.
///
/// The reboot is refused if a process holds a `block` mode shutdown
/// inhibitor lock (see `systemd-inhibit --list`).
#[clap(long)]
pub(crate) apply: bool,

Expand Down
152 changes: 152 additions & 0 deletions crates/lib/src/reboot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,128 @@

use std::{io::Write, process::Command};

use anyhow::Context;
use bootc_utils::CommandRunExt;
use fn_error_context::context;
use serde::Deserialize;

/// The inhibitor mode which asks for an operation not to happen at all.
const INHIBIT_MODE_BLOCK: &str = "block";
/// The inhibitor "what" for system shutdown and reboot.
const INHIBIT_WHAT_SHUTDOWN: &str = "shutdown";

/// An inhibitor lock as returned by logind's `ListInhibitors`, whose D-Bus
/// signature is `a(ssssuu)`.
#[derive(Debug, Deserialize, PartialEq, Eq)]
struct Inhibitor {
/// Colon-separated list of what is inhibited, e.g. `shutdown:sleep`.
what: String,
who: String,
why: String,
/// `block`, `block-weak` or `delay`.
mode: String,
uid: u32,
pid: u32,
}

impl Inhibitor {
/// Whether this lock asks for reboots not to happen at all.
fn blocks_shutdown(&self) -> bool {
self.mode == INHIBIT_MODE_BLOCK && self.what.split(':').any(|w| w == INHIBIT_WHAT_SHUTDOWN)
}
}

/// The output of `busctl --json=short call` for a method returning `a(ssssuu)`.
#[derive(Debug, Deserialize)]
struct ListInhibitorsReply {
data: (Vec<Inhibitor>,),
}

/// Parse the JSON output of `busctl call ... ListInhibitors`, returning the
/// locks which block shutdown.
fn blocking_inhibitors(json: &str) -> anyhow::Result<Vec<Inhibitor>> {
let reply: ListInhibitorsReply =
serde_json::from_str(json).context("Parsing ListInhibitors reply")?;
let (inhibitors,) = reply.data;
Ok(inhibitors
.into_iter()
.filter(Inhibitor::blocks_shutdown)
.collect())
}

/// Ask logind for the locks which block shutdown.
fn query_blocking_inhibitors() -> anyhow::Result<Vec<Inhibitor>> {
let reply = Command::new("busctl")
.args([
"--json=short",
"call",
"org.freedesktop.login1",
"/org/freedesktop/login1",
"org.freedesktop.login1.Manager",
"ListInhibitors",
])
.run_get_string()
.context("Querying logind")?;
blocking_inhibitors(&reply)
}

/// Fail if a process holds a block mode shutdown inhibitor lock.
///
/// Something that takes such a lock (a long-running job, a package manager,
/// etc.) is explicitly asking for the system not to be rebooted underneath
/// it. This mirrors rpm-ostree, and unlike `systemctl reboot
/// --check-inhibitors=yes` it doesn't also refuse when other users are
/// logged in: that would include the administrator's own session.
///
/// Unlike rpm-ostree, if logind can't be queried (e.g. it isn't running) we
/// only warn and allow the reboot: failing closed would break every
/// `--apply` (and automatic updates) on such systems, and where logind does
/// run, systemd 257 and newer enforce block locks themselves.
#[context("Checking for shutdown inhibitors")]
fn check_inhibitors() -> anyhow::Result<()> {
let blocking = match query_blocking_inhibitors() {
Ok(v) => v,
Err(e) => {
crate::utils::medium_visibility_warning(&format!(
"warning: Failed to check for shutdown inhibitors, rebooting anyway: {e:#}"
));
return Ok(());
}
};
if blocking.is_empty() {
return Ok(());
}
let holders = blocking
.iter()
.map(|i| format!("\"{}\" (PID {}, UID {}): {}", i.who, i.pid, i.uid, i.why))
.collect::<Vec<_>>()
.join("; ");
anyhow::bail!(
"Reboot blocked by shutdown inhibitor: {holders}. \
Pending changes take effect on the next boot; use \
`systemctl reboot --check-inhibitors=no` to reboot anyway."
)
}

/// Initiate a system reboot.
/// This function will only return in case of error.
#[context("Initiating reboot")]
pub(crate) fn reboot() -> anyhow::Result<()> {
check_inhibitors()?;
// Flush output streams
let _ = std::io::stdout().flush();
let _ = std::io::stderr().flush();
// Wait for the transient unit and pass through its stderr, so that if
// the reboot is refused (e.g. due to an inhibitor) we report an error
// instead of sleeping forever below. Note --wait/--pipe talk to systemd
// via the D-Bus system bus rather than /run/systemd/private, so without
// dbus (e.g. rescue.target) this fails loudly; staged changes are kept.
Command::new("systemd-run")
.args([
"--quiet",
"--wait",
"--pipe",
"--collect",
"--",
"systemctl",
"reboot",
Expand All @@ -31,3 +140,46 @@ pub(crate) fn reboot() -> anyhow::Result<()> {
std::thread::park();
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_blocking_inhibitors() {
// (busctl output, the `who` of each lock expected to block reboot)
let cases: &[(&str, &[&str])] = &[
(r#"{"type":"a(ssssuu)","data":[[]]}"#, &[]),
(
r#"{"type":"a(ssssuu)","data":[[
["shutdown:sleep","NetworkManager","Waiting","delay",0,901],
["handle-power-key:handle-suspend-key","gdm","GNOME","block",42,1788],
["sleep","backup","Backing up","block",0,2001],
["idle:shutdown","dnf","Installing","block",0,2002],
["shutdown","weak","Maybe","block-weak",0,2003],
["shutdown","bootc-test","testing","block",0,2004]
]]}"#,
&["dnf", "bootc-test"],
),
];
for (json, expected) in cases {
let found = blocking_inhibitors(json).unwrap();
let found = found.iter().map(|i| i.who.as_str()).collect::<Vec<_>>();
assert_eq!(&found, expected, "{json}");
}
}

#[test]
fn test_blocking_inhibitors_malformed() {
for json in [
"",
"not json",
r#"{"type":"a(ssssuu)"}"#,
r#"{"type":"a(ssssuu)","data":[]}"#,
r#"{"type":"a(ssssuu)","data":[[["shutdown","who","why","block"]]]}"#,
r#"{"type":"a(ssssuu)","data":[[["shutdown","who","why","block","0","1"]]]}"#,
] {
assert!(blocking_inhibitors(json).is_err(), "{json:?}");
}
}
}
7 changes: 7 additions & 0 deletions docs/src/man/bootc-fetch-apply-updates.service.5.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ This service causes `bootc` to perform the following steps:
- If one is found, download it
- Reboot

The reboot honors systemd inhibitor locks: if a process holds a
`block` mode `shutdown` inhibitor (see `systemd-inhibit(1)`), the reboot
is refused and the service fails. The update remains staged, and is
applied on the next reboot or the next run of this service. To reboot
anyway, use `systemctl reboot --check-inhibitors=no`. Logged-in users
do not prevent the reboot.

This service also comes with a companion `bootc-fetch-apply-updates.timer`
systemd unit. The current default systemd timer shipped in the upstream
project is enabled for daily updates.
Expand Down
2 changes: 2 additions & 0 deletions docs/src/man/bootc-upgrade.8.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Currently by default, the update will be applied at shutdown time via `ostree-fi
There is also an explicit `bootc upgrade --apply` verb which will automatically take action (rebooting)
if the system has changed.

The reboot is refused, and the command fails with the update left staged, if a process holds a `block` mode shutdown inhibitor lock (see `systemd-inhibit --list`).

However, in the future this is likely to change such that reboots outside of a `bootc upgrade --apply`
do *not* automatically apply the update in addition.

Expand Down
31 changes: 31 additions & 0 deletions tmt/tests/booted/test-image-upgrade-reboot.nu
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# bootc image copy-to-storage
# podman build <from that image>
# bootc switch <into that image> (stage only)
# bootc switch --apply <same image> with a shutdown inhibitor held (must fail)
# bootc switch --apply <same image> (spec unchanged, must still reboot)
# Verify we boot into the new image
#
Expand Down Expand Up @@ -93,6 +94,36 @@ def initial_build [] {
# staged deployments.
print $"Staging ($imgsrc)"
bootc switch --transport containers-storage ($imgsrc)

# A block mode shutdown inhibitor must make --apply fail rather than reboot.
# nushell has no &, so hold the inhibitor from a transient unit.
let inhibit_unit = "test-bootc-inhibit"
systemd-run -q -u $inhibit_unit -- systemd-inhibit --what=shutdown --mode=block --who=bootc-test --why=testing sleep infinity
# Wait for the inhibitor to actually be taken
mut inhibited = false
for _ in 0..30 {
if (systemd-inhibit --list --no-legend | str contains "bootc-test") {
$inhibited = true
break
}
sleep 1sec
}
assert $inhibited "inhibitor should be active"
print "Running --apply with an inhibitor held (should fail, not reboot)"
let r = do { bootc switch --apply --transport containers-storage ($imgsrc) } | complete
systemctl stop $inhibit_unit
print $r.stderr
assert ($r.exit_code != 0) "bootc switch --apply should fail while a shutdown inhibitor is held"
assert ($r.stderr | str contains "shutdown inhibitor") "error should mention the inhibitor"
assert ($r.stderr | str contains "bootc-test") "error should name the inhibitor holder"
# logind notices the inhibitor going away asynchronously
for _ in 0..30 {
if not (systemd-inhibit --list --no-legend | str contains "bootc-test") {
break
}
sleep 1sec
}

print "Re-running with --apply (spec unchanged, should still reboot)"
tmt-reboot -c $"bootc switch --apply --transport containers-storage ($imgsrc)"
}
Expand Down