Files
rust-discovery/crates/updater-worker/src/reader_registry.rs
T
2026-11-15 11:40:53 +01:00

836 lines
28 KiB
Rust

//! Protected compatible-reader registry plus read-only systemd closure.
//! This does not replace complete current task/FD/maps census, both real locks,
//! original authorization or live process/image proofs. No future-exec promise.
use crate::census::{HostContext, current_host_context};
use anyhow::{Context, Result, ensure};
use rmm_domain::{
agent_update::digest,
agent_update_provisioning::{ActivationEvidence, LocalUpdatePolicy},
jobs::hash,
};
use rmm_updater_linux::{
Budget,
files::{Directory, FileProof, HeldFile},
};
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, BTreeSet},
fs::Metadata,
io::Read,
os::{
fd::{AsRawFd, FromRawFd},
unix::fs::MetadataExt,
},
path::{Path, PathBuf},
process::{Child, Command, Stdio},
sync::Mutex,
thread,
time::{Duration, Instant},
};
pub const READER_CONTRACT: &[u8] = b"rmm.linux-shared-readers.v1\0root-helper:existing-executor.lock-before-sqlite-open-and-every-sql-or-effect-operation;agent:existing-agent.lock-before-both-agent-sqlite-opens-and-held-for-process-lifetime;all-allowed-readers:update-handoff-inflight-decoder-compatible;admission:protected-bootstrap-plus-current-complete-task-fd-maps-census-and-both-original-locks;scope:no-global-future-exec-absence-promise\n";
pub fn reader_contract_sha256() -> String {
hash(READER_CONTRACT)
}
const REGISTRY: &str = "/etc/rmm-agent-updater/reader-registry.json";
const MAX_BYTES: u64 = 65536;
const MAX_ROLLBACK: usize = 32;
const MAX_FILES: usize = 128;
const SERVICES: [&str; 7] = [
"rmm-agent-remote.service",
"rmm-helper-cloud.service",
"rmm-full-maintenance-helper.service",
"rmm-agent-updater.service",
"rmm-apt-helper.service",
"rmm-agent.service",
"rmm-helper-dev-test.service",
];
const ROLLBACK_PATTERN: &str = "rmm-general-startup-rollback-*.timer";
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Registry {
schema_version: u32,
profile: String,
bootstrap_receipt_sha256: String,
reader_contract_sha256: String,
host_context: HostContext,
units: Vec<Unit>,
rollback_timers: Vec<Unit>,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Unit {
unit: String,
unit_file_state: String,
/// Exactly the Frozen OS unit_composition vector: fragment, then DropInPaths
/// in their actual order. FileProof includes original device/inode metadata.
composition: Vec<(String, FileProof)>,
triggers: Vec<String>,
triggered_by: Vec<String>,
}
#[derive(PartialEq, Eq)]
struct Stamp {
dev: u64,
ino: u64,
uid: u32,
gid: u32,
mode: u32,
links: u64,
bytes: u64,
mtime: i64,
mtime_ns: i64,
ctime: i64,
ctime_ns: i64,
}
impl Stamp {
fn read(path: &Path) -> Result<Self> {
let m = std::fs::symlink_metadata(path)?;
ensure!(
m.is_file() && !m.file_type().is_symlink(),
"UPDATE_REGISTRY_REGULAR_FILE"
);
Ok(Self::of(&m))
}
fn of(m: &Metadata) -> Self {
Self {
dev: m.dev(),
ino: m.ino(),
uid: m.uid(),
gid: m.gid(),
mode: m.mode(),
links: m.nlink(),
bytes: m.len(),
mtime: m.mtime(),
mtime_ns: m.mtime_nsec(),
ctime: m.ctime(),
ctime_ns: m.ctime_nsec(),
}
}
}
struct Protected {
directory: Directory,
file: Mutex<HeldFile>,
path: PathBuf,
proof: FileProof,
stamp: Stamp,
raw: Vec<u8>,
}
impl Protected {
fn open(path: &Path) -> Result<Self> {
let before = Stamp::read(path)?;
let directory =
Directory::open(path.parent().context("UPDATE_REGISTRY_PARENT")?, 0, false)?;
let mut file = directory.inspect(
path.file_name().context("UPDATE_REGISTRY_FILENAME")?,
0,
MAX_BYTES,
)?;
let raw = file.bytes(MAX_BYTES)?;
let proof = file.proof().clone();
ensure!(
before == Stamp::read(path)?
&& before.uid == 0
&& before.mode & 0o022 == 0
&& before.bytes == raw.len() as u64,
"UPDATE_REGISTRY_CHANGED_DURING_READ"
);
let result = Self {
directory,
file: Mutex::new(file),
path: path.into(),
proof,
stamp: before,
raw,
};
result.verify()?;
Ok(result)
}
fn verify(&self) -> Result<()> {
self.directory.verify()?;
ensure!(
Stamp::read(&self.path)? == self.stamp,
"UPDATE_REGISTRY_METADATA_CHANGED"
);
let mut held = self
.file
.try_lock()
.map_err(|_| anyhow::anyhow!("UPDATE_REGISTRY_HELD_FILE_BUSY"))?;
held.verify(MAX_BYTES)?;
let mut named = self.directory.file(
self.path.file_name().context("UPDATE_REGISTRY_FILENAME")?,
&self.proof,
MAX_BYTES,
)?;
ensure!(
named.bytes(MAX_BYTES)? == self.raw && Stamp::read(&self.path)? == self.stamp,
"UPDATE_REGISTRY_ORIGINAL_RAW_CHANGED"
);
Ok(())
}
}
/// Non-cloneable independently loaded original registry. No caller completeness
/// flag and no command/path selection is exposed by its public API.
pub struct QualifiedRegistry {
registry: Registry,
protected: Vec<Protected>,
policy_sha256: String,
}
impl QualifiedRegistry {
pub fn load(policy: &LocalUpdatePolicy) -> Result<Self> {
ensure!(
policy.validate() && policy.registry_path == REGISTRY,
"UPDATE_READER_POLICY"
);
let original = Protected::open(Path::new(REGISTRY))?;
ensure!(
original.proof.identity.links == 1
&& hash(&original.raw) == policy.reader_registry_sha256,
"UPDATE_READER_REGISTRY_PIN"
);
let registry: Registry = serde_json::from_slice(&original.raw)
.map_err(|_| anyhow::anyhow!("UPDATE_READER_REGISTRY_CODEC"))?;
validate_registry(&registry, policy)?;
let mut protected = vec![original];
let mut seen = BTreeMap::new();
for unit in registry.units.iter().chain(&registry.rollback_timers) {
for (path, expected) in &unit.composition {
if let Some(existing) = seen.get(path) {
ensure!(
existing == expected,
"UPDATE_READER_SHARED_UNIT_PROOF_CONFLICT"
);
continue;
}
ensure!(protected.len() <= MAX_FILES, "UPDATE_READER_FILE_LIMIT");
let held = Protected::open(Path::new(path))?;
ensure!(
held.proof == *expected,
"UPDATE_READER_UNIT_ORIGINAL_CHANGED"
);
seen.insert(path.clone(), expected.clone());
protected.push(held);
}
}
let result = Self {
registry,
protected,
policy_sha256: hash(&serde_json::to_vec(policy)?),
};
result.verify_protected()?;
Ok(result)
}
pub fn host_context(&self) -> &HostContext {
&self.registry.host_context
}
pub fn verify_protected(&self) -> Result<()> {
for file in &self.protected {
file.verify()?;
}
Ok(())
}
pub fn verify_admission(&self, policy: &LocalUpdatePolicy, budget: &Budget) -> Result<()> {
self.verify_phase(policy, budget, false)
}
pub fn verify_stopped(&self, policy: &LocalUpdatePolicy, budget: &Budget) -> Result<()> {
self.verify_phase(policy, budget, true)
}
fn verify_phase(
&self,
policy: &LocalUpdatePolicy,
budget: &Budget,
stopped: bool,
) -> Result<()> {
budget.check()?;
self.verify_protected()?;
ensure!(
hash(&serde_json::to_vec(policy)?) == self.policy_sha256,
"UPDATE_READER_POLICY_CHANGED"
);
ensure!(
current_host_context()? == self.registry.host_context,
"UPDATE_READER_HOST_CONTEXT_CHANGED"
);
let first_names = rollback_names(budget)?;
let allowed: BTreeSet<_> = self
.registry
.rollback_timers
.iter()
.map(|u| u.unit.as_str())
.collect();
ensure!(
first_names
.iter()
.all(|name| allowed.contains(name.as_str())),
"UPDATE_READER_UNKNOWN_ROLLBACK_TIMER"
);
let mut first = BTreeMap::new();
for (index, unit) in self.registry.units.iter().enumerate() {
let active = index < 4 && (!stopped || index == 3);
let status = observe(unit, budget)?;
status.verify(unit, active, index < 4)?;
first.insert(unit.unit.clone(), status);
}
for unit in &self.registry.rollback_timers {
let status = observe(unit, budget)?;
status.verify(unit, false, false)?;
first.insert(unit.unit.clone(), status);
}
// Structural trigger names are not an assertion that a source is live.
// Every exact registered relevant source is independently closed below.
for unit in self
.registry
.units
.iter()
.chain(&self.registry.rollback_timers)
{
if !unit.triggers.is_empty() {
ensure!(
first[&unit.unit].closed(),
"UPDATE_READER_ACTIVATION_SOURCE_OPEN"
);
}
for name in &unit.triggered_by {
ensure!(
first.get(name).is_some_and(|source| source.closed()),
"UPDATE_READER_ACTIVATION_PATH_OPEN"
);
}
}
ensure!(
rollback_names(budget)? == first_names,
"UPDATE_READER_ROLLBACK_TIMER_SET_CHANGED"
);
self.verify_protected()?;
for unit in self
.registry
.units
.iter()
.chain(&self.registry.rollback_timers)
{
ensure!(
observe(unit, budget)? == first[&unit.unit],
"UPDATE_READER_STATUS_CHANGED"
);
}
ensure!(
current_host_context()? == self.registry.host_context,
"UPDATE_READER_HOST_CONTEXT_CHANGED"
);
self.verify_protected()?;
budget.check()
}
}
fn fixed_units() -> Vec<String> {
let mut names = SERVICES.iter().map(|s| s.to_string()).collect::<Vec<_>>();
for name in SERVICES {
let base = name.strip_suffix(".service").expect("fixed service");
for suffix in ["socket", "timer"] {
names.push(format!("{base}.{suffix}"));
}
}
names
}
fn rollback(name: &str) -> bool {
let Some(value) = name
.strip_prefix("rmm-general-startup-rollback-")
.and_then(|s| s.strip_suffix(".timer"))
else {
return false;
};
uuid::Uuid::parse_str(value)
.is_ok_and(|id| id.get_version_num() == 4 && id.to_string() == value)
}
fn validate_registry(registry: &Registry, policy: &LocalUpdatePolicy) -> Result<()> {
ensure!(
registry.schema_version == 1
&& registry.profile == "linux_shared_readers_v1"
&& registry.reader_contract_sha256 == reader_contract_sha256(),
"UPDATE_READER_REGISTRY_PROFILE"
);
let baseline = policy
.initial_baseline
.decode()
.map_err(anyhow::Error::msg)?;
let ActivationEvidence::Bootstrap {
qualification_receipt_sha256,
} = baseline.record.activation_evidence
else {
anyhow::bail!("UPDATE_READER_INITIAL_BOOTSTRAP_REQUIRED");
};
ensure!(
digest(&registry.bootstrap_receipt_sha256)
&& registry.bootstrap_receipt_sha256 == qualification_receipt_sha256,
"UPDATE_READER_BOOTSTRAP_RECEIPT"
);
let host = &registry.host_context;
ensure!(
[
host.proc_inode,
host.user_namespace_inode,
host.pid_namespace_inode,
host.cgroup_namespace_inode
]
.iter()
.all(|n| *n > 0),
"UPDATE_READER_HOST_CONTEXT_SHAPE"
);
ensure!(
registry
.units
.iter()
.map(|u| u.unit.clone())
.eq(fixed_units())
&& registry.rollback_timers.len() <= MAX_ROLLBACK,
"UPDATE_READER_CLOSED_UNIT_SET"
);
let mut all: BTreeSet<String> = fixed_units().into_iter().collect();
let mut previous = None;
for unit in &registry.rollback_timers {
ensure!(
rollback(&unit.unit)
&& previous
.as_ref()
.is_none_or(|old: &String| old < &unit.unit)
&& all.insert(unit.unit.clone()),
"UPDATE_READER_ROLLBACK_NAMES"
);
previous = Some(unit.unit.clone());
}
let mut total = 0;
for (index, unit) in registry
.units
.iter()
.chain(&registry.rollback_timers)
.enumerate()
{
let active = index < 4;
ensure!(
unit.composition.len() <= 17
&& ((!unit.composition.is_empty()
&& if active {
matches!(unit.unit_file_state.as_str(), "enabled" | "disabled")
} else {
unit.unit_file_state == "disabled"
})
|| (!active && unit.composition.is_empty() && unit.unit_file_state.is_empty())),
"UPDATE_READER_UNIT_STATE_SHAPE"
);
let mut paths = BTreeSet::new();
for (position, (path, proof)) in unit.composition.iter().enumerate() {
let filename = Path::new(path).file_name().and_then(|name| name.to_str());
ensure!(
if position == 0 {
filename == Some(unit.unit.as_str())
} else {
filename.is_some_and(|name| name.ends_with(".conf"))
},
"UPDATE_READER_UNIT_LEAF_NAME"
);
ensure!(
unit_path(path)
&& paths.insert(path)
&& proof.identity.uid == 0
&& proof.identity.inode > 0
&& proof.identity.links > 0
&& proof.identity.mode & libc::S_IFMT == libc::S_IFREG
&& proof.identity.mode & 0o022 == 0
&& proof.bytes <= MAX_BYTES
&& digest(&proof.sha256),
"UPDATE_READER_UNIT_PROOF_SHAPE"
);
total += 1;
}
for names in [&unit.triggers, &unit.triggered_by] {
ensure!(
names.len() <= 32
&& names.windows(2).all(|pair| pair[0] < pair[1])
&& names.iter().all(|name| all.contains(name)),
"UPDATE_READER_UNKNOWN_ACTIVATION_RELATION"
);
}
if unit.composition.is_empty() {
ensure!(
unit.triggers.is_empty() && unit.triggered_by.is_empty(),
"UPDATE_READER_ABSENT_RELATIONS"
);
}
let pin = if index < 3 {
Some(&policy.services[index])
} else if index == 3 {
Some(&policy.updater_service)
} else if index == 4 {
policy.services.get(3)
} else {
None
};
if let Some(pin) = pin {
ensure!(
pin.unit == unit.unit
&& !unit.composition.is_empty()
&& hash(&serde_json::to_vec(&unit.composition)?) == pin.unit_sha256,
"UPDATE_READER_POLICY_UNIT_COMPOSITION"
);
}
if index == 4 && policy.services.len() == 3 {
ensure!(
unit.composition.is_empty(),
"UPDATE_READER_APT_NOT_IN_POLICY"
);
}
}
ensure!(total <= MAX_FILES, "UPDATE_READER_FILE_LIMIT");
Ok(())
}
fn unit_path(value: &str) -> bool {
value.len() <= 4096
&& value.starts_with('/')
&& value
.split('/')
.skip(1)
.all(|part| !part.is_empty() && part != "." && part != "..")
&& value.bytes().all(|b| b.is_ascii_graphic() && b != b'\\')
&& [
"/etc/systemd/system/",
"/usr/lib/systemd/system/",
"/lib/systemd/system/",
"/run/systemd/system/",
"/run/systemd/transient/",
]
.iter()
.any(|root| value.starts_with(root))
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Status {
fields: BTreeMap<String, String>,
main_pid: Option<u32>,
control_pid: Option<u32>,
connections: Option<u32>,
}
const GENERIC: [&str; 11] = [
"Id",
"LoadState",
"ActiveState",
"SubState",
"InvocationID",
"UnitFileState",
"FragmentPath",
"DropInPaths",
"Triggers",
"TriggeredBy",
"Job",
];
impl Status {
fn parse(unit: &str, raw: &[u8]) -> Result<Self> {
ensure!(
raw.len() <= 16384 && raw.is_ascii(),
"UPDATE_READER_STATUS_LIMIT"
);
let text =
std::str::from_utf8(raw).map_err(|_| anyhow::anyhow!("UPDATE_READER_STATUS_CODEC"))?;
let mut fields: BTreeMap<String, String> = BTreeMap::new();
let mut permitted = GENERIC.to_vec();
if unit.ends_with(".service") {
permitted.extend(["MainPID", "ControlPID"]);
} else if unit.ends_with(".socket") {
permitted.extend(["ControlPID", "NConnections"]);
}
for line in text.lines() {
let (key, value) = line.split_once('=').context("UPDATE_READER_STATUS_CODEC")?;
ensure!(
permitted.contains(&key) && fields.insert(key.into(), value.into()).is_none(),
"UPDATE_READER_STATUS_FIELDS"
);
}
ensure!(
GENERIC.iter().all(|key| fields.contains_key(*key)) && fields["Id"] == unit,
"UPDATE_READER_STATUS_INCOMPLETE"
);
let loaded = fields["LoadState"] == "loaded";
let number = |key: &str, required: bool| -> Result<Option<u32>> {
match fields.get(key) {
Some(value) => {
ensure!(
!value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()),
"UPDATE_READER_PID_CODEC"
);
Ok(Some(
value
.parse()
.map_err(|_| anyhow::anyhow!("UPDATE_READER_PID_RANGE"))?,
))
}
None => {
ensure!(!required, "UPDATE_READER_MISSING_PID_PROPERTY");
Ok(None)
}
}
};
let main_pid = number("MainPID", loaded && unit.ends_with(".service"))?;
let control_pid = number("ControlPID", loaded && !unit.ends_with(".timer"))?;
let connections = number("NConnections", loaded && unit.ends_with(".socket"))?;
Ok(Self {
fields,
main_pid,
control_pid,
connections,
})
}
fn closed(&self) -> bool {
self.fields["ActiveState"] == "inactive"
&& self.fields["SubState"] == "dead"
&& self.main_pid.is_none_or(|n| n == 0)
&& self.control_pid.is_none_or(|n| n == 0)
&& self.connections.is_none_or(|n| n == 0)
&& self.fields["Job"].is_empty()
}
fn verify(&self, unit: &Unit, active: bool, original_reader: bool) -> Result<()> {
let fields = &self.fields;
ensure!(
fields["UnitFileState"] == unit.unit_file_state
&& relations(&fields["Triggers"])? == unit.triggers
&& relations(&fields["TriggeredBy"])? == unit.triggered_by,
"UPDATE_READER_UNIT_RELATIONS_CHANGED"
);
if unit.composition.is_empty() {
ensure!(
!active
&& fields["LoadState"] == "not-found"
&& fields["FragmentPath"].is_empty()
&& fields["DropInPaths"].is_empty()
&& self.closed(),
"UPDATE_READER_ABSENT_UNIT_CHANGED"
);
} else {
ensure!(
fields["LoadState"] == "loaded",
"UPDATE_READER_UNIT_NOT_LOADED"
);
let mut paths = vec![fields["FragmentPath"].as_str()];
paths.extend(fields["DropInPaths"].split_ascii_whitespace());
ensure!(
paths
.iter()
.copied()
.eq(unit.composition.iter().map(|(path, _)| path.as_str())),
"UPDATE_READER_UNIT_COMPOSITION_CHANGED"
);
if active {
ensure!(
fields["ActiveState"] == "active"
&& fields["SubState"] == "running"
&& self.main_pid.is_some_and(|pid| pid > 1)
&& self.control_pid == Some(0)
&& fields["Job"].is_empty()
&& fields["InvocationID"].len() == 32
&& fields["InvocationID"]
.bytes()
.all(|b| b.is_ascii_hexdigit())
&& fields["InvocationID"].bytes().any(|b| b != b'0'),
"UPDATE_READER_ACTIVE_REQUIRED"
);
} else {
ensure!(
(original_reader || unit.unit_file_state == "disabled") && self.closed(),
"UPDATE_READER_UNIT_NOT_CLOSED"
);
}
}
Ok(())
}
}
fn relations(value: &str) -> Result<Vec<String>> {
let mut names = value
.split_ascii_whitespace()
.map(str::to_owned)
.collect::<Vec<_>>();
ensure!(names.len() <= 32, "UPDATE_READER_RELATION_LIMIT");
names.sort();
ensure!(
names.windows(2).all(|pair| pair[0] < pair[1]),
"UPDATE_READER_DUPLICATE_RELATION"
);
Ok(names)
}
fn observe(unit: &Unit, budget: &Budget) -> Result<Status> {
let mut properties = GENERIC.to_vec();
if unit.unit.ends_with(".service") {
properties.extend(["MainPID", "ControlPID"]);
} else if unit.unit.ends_with(".socket") {
properties.extend(["ControlPID", "NConnections"]);
}
let property = format!("--property={}", properties.join(","));
let raw = command(&["show", "--all", &property, "--", &unit.unit], budget)?;
Status::parse(&unit.unit, &raw)
}
fn rollback_names(budget: &Budget) -> Result<BTreeSet<String>> {
let mut names = BTreeSet::new();
for args in [
vec![
"list-units",
"--all",
"--plain",
"--no-legend",
"--type=timer",
"--",
ROLLBACK_PATTERN,
],
vec!["list-unit-files", "--no-legend", "--", ROLLBACK_PATTERN],
] {
let raw = command(&args, budget)?;
ensure!(raw.is_ascii(), "UPDATE_READER_TIMER_LIST_CODEC");
for line in std::str::from_utf8(&raw)
.map_err(|_| anyhow::anyhow!("UPDATE_READER_TIMER_LIST_CODEC"))?
.lines()
{
let name = line
.split_ascii_whitespace()
.next()
.context("UPDATE_READER_TIMER_LIST_CODEC")?;
ensure!(
rollback(name) && names.len() < MAX_ROLLBACK + 1,
"UPDATE_READER_TIMER_LIST_LIMIT"
);
names.insert(name.to_owned());
}
}
Ok(names)
}
struct OwnedCommand {
child: Child,
pidfd: std::fs::File,
}
impl Drop for OwnedCommand {
fn drop(&mut self) {
unsafe {
libc::syscall(
libc::SYS_pidfd_send_signal,
self.pidfd.as_raw_fd(),
libc::SIGKILL,
0usize,
0,
)
};
let _ = self.child.wait();
}
}
fn drain(stream: &mut dyn Read, raw: &mut Vec<u8>) -> Result<()> {
let mut chunk = [0; 1024];
loop {
match stream.read(&mut chunk) {
Ok(0) => break,
Ok(count) => {
ensure!(
raw.len() + count <= 16384,
"UPDATE_READER_COMMAND_OUTPUT_LIMIT"
);
raw.extend_from_slice(&chunk[..count]);
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break,
Err(_) => anyhow::bail!("UPDATE_READER_COMMAND_READ"),
}
}
Ok(())
}
fn command(args: &[&str], budget: &Budget) -> Result<Vec<u8>> {
budget.check()?;
let child = Command::new("/usr/bin/systemctl")
.args(["--system", "--no-ask-password", "--no-pager", "--full"])
.args(args)
.env_clear()
.env("PATH", "/usr/bin:/bin")
.env("LC_ALL", "C")
.env("SYSTEMD_COLORS", "0")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|_| anyhow::anyhow!("UPDATE_READER_COMMAND_SPAWN"))?;
let mut child = child;
let pid = unsafe { libc::syscall(libc::SYS_pidfd_open, child.id(), 0) };
if pid < 0 {
let _ = child.kill();
let _ = child.wait();
anyhow::bail!("UPDATE_READER_COMMAND_PIDFD");
}
let mut owned = OwnedCommand {
child,
pidfd: unsafe { std::fs::File::from_raw_fd(pid as i32) },
};
let mut stdout = owned.child.stdout.take().context("UPDATE_READER_STDOUT")?;
let mut stderr = owned.child.stderr.take().context("UPDATE_READER_STDERR")?;
for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] {
ensure!(
unsafe { libc::fcntl(fd, libc::F_SETFL, libc::O_NONBLOCK) } >= 0,
"UPDATE_READER_COMMAND_NONBLOCK"
);
}
let started = Instant::now();
let mut out = Vec::new();
let mut error = Vec::new();
loop {
budget.check()?;
ensure!(
started.elapsed() < Duration::from_secs(10),
"UPDATE_READER_COMMAND_TIMEOUT"
);
drain(&mut stdout, &mut out)?;
drain(&mut stderr, &mut error)?;
if let Some(status) = owned
.child
.try_wait()
.map_err(|_| anyhow::anyhow!("UPDATE_READER_COMMAND_WAIT"))?
{
drain(&mut stdout, &mut out)?;
drain(&mut stderr, &mut error)?;
ensure!(
status.success() && error.is_empty(),
"UPDATE_READER_SYSTEMD_FAILED"
);
budget.check()?;
return Ok(out);
}
thread::sleep(Duration::from_millis(2));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn timer() -> Vec<u8> {
b"Id=rmm-agent-remote.timer\nLoadState=loaded\nActiveState=inactive\nSubState=dead\nInvocationID=\nUnitFileState=disabled\nFragmentPath=/etc/systemd/system/rmm-agent-remote.timer\nDropInPaths=\nTriggers=rmm-agent-remote.service\nTriggeredBy=\nJob=\n".to_vec()
}
#[test]
fn timer_without_process_interface_is_typed_but_missing_service_pid_or_pending_job_denies() {
let raw = timer();
let status = Status::parse("rmm-agent-remote.timer", &raw).unwrap();
assert_eq!(status.main_pid, None);
assert_eq!(status.control_pid, None);
assert!(status.closed());
let pending = String::from_utf8(raw.clone())
.unwrap()
.replace("Job=\n", "Job=123\n");
assert!(
!Status::parse("rmm-agent-remote.timer", pending.as_bytes())
.unwrap()
.closed()
);
let service = String::from_utf8(raw.clone())
.unwrap()
.replace("rmm-agent-remote.timer", "rmm-agent-remote.service");
assert!(Status::parse("rmm-agent-remote.service", service.as_bytes()).is_err());
let mut unknown = raw.clone();
unknown.extend_from_slice(b"MainPID=0\n");
assert!(Status::parse("rmm-agent-remote.timer", &unknown).is_err());
let mut duplicate = raw;
duplicate.extend_from_slice(b"Job=\n");
assert!(Status::parse("rmm-agent-remote.timer", &duplicate).is_err());
assert!(rollback(
"rmm-general-startup-rollback-11111111-1111-4111-8111-111111111111.timer"
));
assert!(!rollback("rmm-general-startup-rollback-*.timer"));
}
}