Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/pi-register/blob/main/src/main.rs # pi-register aien-dev/pi-register Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `pi-register / src / main.rs` 391 lines ยท 13740 bytes Raw Blame History 1 //! pi-register: a register of the services on a Linux server (systemd). 2 3 use clap::{Parser, Subcommand}; 4 use serde::Deserialize; 5 use std::path::{Path, PathBuf}; 6 use std::process::{Command, ExitCode}; 7 8 const DEFAULT_REGISTER: &str = "/etc/pi-register/register.toml"; 9 10 #[derive(Debug, Deserialize, Clone)] 11 struct Service { 12 name: String, 13 purpose: String, 14 unit: String, 15 category: String, 16 owner: String, 17 port: Option, 18 #[serde(default)] 19 depends_on: Vec, 20 #[serde(default)] 21 files: Vec, 22 #[serde(default)] 23 secrets: Option, 24 health: Option, 25 boot: bool, 26 notes: Option, 27 } 28 29 #[derive(Debug, Deserialize)] 30 struct Register { 31 #[serde(default, rename = "service")] 32 services: Vec, 33 } 34 35 #[derive(Parser)] 36 #[command(name = "pi-register", about = "What this machine runs, and why")] 37 struct Cli { 38 /// Path to the register file (default: /etc/pi-register/register.toml, then ./register.toml) 39 #[arg(long, global = true)] 40 register: Option, 41 #[command(subcommand)] 42 command: Cmd, 43 } 44 45 #[derive(Subcommand)] 46 enum Cmd { 47 /// Table of every registered service and its live state 48 Status, 49 /// Everything the register knows about one service 50 Show { name: String }, 51 /// Start a service 52 Start { name: String }, 53 /// Stop a service 54 Stop { name: String }, 55 /// Turn on start-at-boot for a service 56 Enable { name: String }, 57 /// Turn off start-at-boot for a service 58 Disable { name: String }, 59 /// Compare the register with the machine 60 Check, 61 /// Print a Markdown page describing the machine 62 Doc, 63 } 64 65 /// Base-system units that are expected on any Debian/Ubuntu server and are 66 /// not worth registering. Entries ending in '*' match by prefix. 67 const IGNORE: &[&str] = &[ 68 "systemd-*", "getty@*", "serial-getty@*", "dbus*", "ssh.service", "sshd.service", 69 "cron.service", "rsyslog.service", "networkd-dispatcher.service", "polkit.service", 70 "apparmor.service", "console-setup.service", "keyboard-setup.service", "e2scrub*", 71 "fstrim.*", "logrotate.*", "apt-*", "apt-daily*", "unattended-upgrades.service", 72 "ufw.service", "snapd*", "multipathd*", "irqbalance.service", "lvm2*", "blk-availability.service", 73 "cloud-*", "open-iscsi.service", "iscsid*", "rsync.service", "ModemManager.service", 74 "NetworkManager*", "wpa_supplicant.service", "user@*", "user-runtime-dir@*", "udev*", 75 "setvtrgb.service", "secureboot-db.service", "ubuntu-advantage.service", "ua-*", 76 "pollinate.service", "plymouth*", "grub-*", "gpu-manager.service", "hwclock.service", 77 "motd-news.*", "man-db.*", "dpkg-db-backup.*", "e2scrub_*", "finalrd.service", 78 "lxd-*", "lxcfs.service", "sysstat.service", "rpcbind.*", "nfs-*", "avahi-daemon.*", 79 "bluetooth.service", "cups*", "accounts-daemon.service", "udisks2.service", 80 "thermald.service", "upower.service", "power-profiles-daemon.service", 81 "switcheroo-control.service", "rtkit-daemon.service", "pi-register*", 82 "apport.service", "chrony.service", "dmesg.service", "netplan-*", "open-vm-tools.service", 83 "piboot-*", "rpi-eeprom-update.service", "sshd-keygen.service", "vgauth.service", 84 "containerd.service", "ubuntu-fan.service", "postfix.service", 85 ]; 86 87 fn pattern_matches(pat: &str, unit: &str) -> bool { 88 if let Some(prefix) = pat.strip_suffix('*') { 89 unit.starts_with(prefix) 90 } else if let Some(suffix) = pat.strip_prefix('*') { 91 unit.ends_with(suffix) 92 } else if let Some((a, b)) = pat.split_once('*') { 93 unit.starts_with(a) && unit.ends_with(b) && unit.len() >= a.len() + b.len() 94 } else { 95 pat == unit 96 } 97 } 98 99 fn is_ignored(unit: &str) -> bool { 100 IGNORE.iter().any(|p| pattern_matches(p, unit)) 101 } 102 103 /// "foo" becomes "foo.service"; names that already have a unit suffix stay. 104 fn full_unit(unit: &str) -> String { 105 const SUFFIXES: &[&str] = &[".service", ".socket", ".timer", ".target", ".mount", ".path"]; 106 if SUFFIXES.iter().any(|s| unit.ends_with(s)) { 107 unit.to_string() 108 } else { 109 format!("{unit}.service") 110 } 111 } 112 113 fn parse_register(text: &str) -> Result { 114 toml::from_str(text).map_err(|e| format!("the register file is not valid: {e}")) 115 } 116 117 fn find_register(flag: &Option) -> Result { 118 if let Some(p) = flag { 119 return Ok(p.clone()); 120 } 121 for c in [DEFAULT_REGISTER, "./register.toml"] { 122 if Path::new(c).is_file() { 123 return Ok(PathBuf::from(c)); 124 } 125 } 126 Err(format!( 127 "no register found. Looked for {DEFAULT_REGISTER} and ./register.toml. Use --register ." 128 )) 129 } 130 131 fn load(flag: &Option) -> Result { 132 let path = find_register(flag)?; 133 let text = std::fs::read_to_string(&path) 134 .map_err(|e| format!("could not read {}: {e}", path.display()))?; 135 let reg = parse_register(&text).map_err(|e| format!("{}: {e}", path.display()))?; 136 let mut seen = std::collections::HashSet::new(); 137 for s in ®.services { 138 if !seen.insert(&s.name) { 139 return Err(format!("{}: the name '{}' appears twice", path.display(), s.name)); 140 } 141 } 142 Ok(reg) 143 } 144 145 fn systemctl(args: &[&str]) -> Result<(bool, String), String> { 146 let out = Command::new("systemctl") 147 .args(args) 148 .output() 149 .map_err(|e| format!("could not run systemctl (is this a systemd machine?): {e}"))?; 150 Ok(( 151 out.status.success(), 152 String::from_utf8_lossy(&out.stdout).trim().to_string(), 153 )) 154 } 155 156 fn unit_exists(unit: &str) -> bool { 157 matches!(systemctl(&["show", "-p", "LoadState", "--value", unit]), 158 Ok((_, s)) if s != "not-found" && !s.is_empty()) 159 } 160 161 fn unit_state(unit: &str) -> (String, String) { 162 if !unit_exists(unit) { 163 return ("missing".into(), "missing".into()); 164 } 165 let active = systemctl(&["is-active", unit]).map(|r| r.1).unwrap_or_else(|_| "unknown".into()); 166 let enabled = systemctl(&["is-enabled", unit]).map(|r| r.1).unwrap_or_else(|_| "unknown".into()); 167 (active, enabled) 168 } 169 170 fn health(s: &Service) -> &'static str { 171 match &s.health { 172 None => "-", 173 Some(cmd) => match Command::new("sh").arg("-c").arg(cmd).output() { 174 Ok(o) if o.status.success() => "OK", 175 _ => "FAIL", 176 }, 177 } 178 } 179 180 fn find<'a>(reg: &'a Register, name: &str) -> Result<&'a Service, String> { 181 reg.services.iter().find(|s| s.name == name).ok_or_else(|| { 182 let known: Vec<&str> = reg.services.iter().map(|s| s.name.as_str()).collect(); 183 format!("'{name}' is not in the register. Known services: {}", known.join(", ")) 184 }) 185 } 186 187 fn cmd_status(reg: &Register) -> Result<(), String> { 188 println!("{:<28} {:<10} {:<10} {:<10} {:<7} WANT-BOOT", "NAME", "CATEGORY", "ACTIVE", "BOOT", "HEALTH"); 189 for s in ®.services { 190 let (a, e) = unit_state(&full_unit(&s.unit)); 191 println!("{:<28} {:<10} {:<10} {:<10} {:<7} {}", s.name, s.category, a, e, health(s), 192 if s.boot { "yes" } else { "no" }); 193 } 194 Ok(()) 195 } 196 197 fn cmd_show(reg: &Register, name: &str) -> Result<(), String> { 198 let s = find(reg, name)?; 199 println!("Name: {}", s.name); 200 println!("Purpose: {}", s.purpose); 201 println!("Unit: {}", s.unit); 202 println!("Category: {}", s.category); 203 println!("Owner: {}", s.owner); 204 if let Some(p) = s.port { println!("Port: {p}"); } 205 if !s.depends_on.is_empty() { println!("Depends on: {}", s.depends_on.join(", ")); } 206 if !s.files.is_empty() { println!("Files: {}", s.files.join(", ")); } 207 if let Some(x) = &s.secrets { println!("Secrets: {x}"); } 208 if let Some(h) = &s.health { println!("Health cmd: {h}"); } 209 println!("Boot: {}", if s.boot { "yes" } else { "no" }); 210 if let Some(n) = &s.notes { println!("Notes: {n}"); } 211 let (a, e) = unit_state(&full_unit(&s.unit)); 212 println!("Right now: {a} (boot: {e}, health: {})", health(s)); 213 Ok(()) 214 } 215 216 fn cmd_control(reg: &Register, verb: &str, name: &str) -> Result<(), String> { 217 let s = find(reg, name)?; 218 let unit = full_unit(&s.unit); 219 let (ok, _) = systemctl(&[verb, &unit])?; 220 if ok { 221 println!("{verb} {unit}: done"); 222 Ok(()) 223 } else { 224 Err(format!("systemctl {verb} {unit} failed (you may need sudo, or the unit may not exist)")) 225 } 226 } 227 228 fn cmd_check(reg: &Register) -> Result<(), String> { 229 let mut problems = 0; 230 for s in ®.services { 231 if !unit_exists(&full_unit(&s.unit)) { 232 println!("MISSING {} (unit {} not found on this machine)", s.name, s.unit); 233 problems += 1; 234 } 235 } 236 let (ok, out) = systemctl(&["list-unit-files", "--type=service", "--state=enabled", "--no-legend", "--plain"])?; 237 if !ok { 238 return Err("could not list the enabled units on this machine".into()); 239 } 240 let known: std::collections::HashSet = 241 reg.services.iter().map(|s| full_unit(&s.unit)).collect(); 242 for unit in out.lines().filter_map(|l| l.split_whitespace().next()) { 243 if !known.contains(unit) && !is_ignored(unit) { 244 println!("UNREGISTERED {unit} is enabled but not in the register"); 245 problems += 1; 246 } 247 } 248 if problems == 0 { 249 println!("All good: register and machine agree."); 250 Ok(()) 251 } else { 252 Err(format!("{problems} problem(s) found")) 253 } 254 } 255 256 fn cmd_doc(reg: &Register) -> Result<(), String> { 257 println!("# Services on this machine\n"); 258 println!("Generated from the register by pi-register. {} services.\n", reg.services.len()); 259 let mut cats: Vec<&str> = reg.services.iter().map(|s| s.category.as_str()).collect(); 260 cats.sort(); 261 cats.dedup(); 262 for c in cats { 263 println!("## {c}\n"); 264 for s in reg.services.iter().filter(|s| s.category == c) { 265 println!("### {}\n", s.name); 266 println!("{}\n", s.purpose); 267 println!("- Unit: `{}`", s.unit); 268 println!("- Owner: {}", s.owner); 269 if let Some(p) = s.port { println!("- Port: {p}"); } 270 if !s.depends_on.is_empty() { println!("- Depends on: {}", s.depends_on.join(", ")); } 271 if !s.files.is_empty() { 272 println!("- Files: {}", s.files.iter().map(|f| format!("`{f}`")).collect::>().join(", ")); 273 } 274 if let Some(x) = &s.secrets { println!("- Secrets live in: `{x}`"); } 275 if let Some(h) = &s.health { println!("- Health check: `{h}`"); } 276 println!("- Starts at boot: {}", if s.boot { "yes" } else { "no" }); 277 if let Some(n) = &s.notes { println!("- Notes: {n}"); } 278 println!(); 279 } 280 } 281 Ok(()) 282 } 283 284 fn run() -> Result<(), String> { 285 let cli = Cli::parse(); 286 let reg = load(&cli.register)?; 287 match cli.command { 288 Cmd::Status => cmd_status(®), 289 Cmd::Show { name } => cmd_show(®, &name), 290 Cmd::Start { name } => cmd_control(®, "start", &name), 291 Cmd::Stop { name } => cmd_control(®, "stop", &name), 292 Cmd::Enable { name } => cmd_control(®, "enable", &name), 293 Cmd::Disable { name } => cmd_control(®, "disable", &name), 294 Cmd::Check => cmd_check(®), 295 Cmd::Doc => cmd_doc(®), 296 } 297 } 298 299 #[cfg(unix)] 300 extern "C" { 301 fn signal(signum: i32, handler: usize) -> usize; 302 } 303 304 /// Restore the default SIGPIPE action so `pi-register status | head -1` exits quietly 305 /// instead of panicking when the reader closes the pipe. 306 fn restore_sigpipe() { 307 #[cfg(unix)] 308 // SAFETY: signal(SIGPIPE=13, SIG_DFL=0) is a plain libc call with no Rust-side state. 309 unsafe { 310 signal(13, 0); 311 } 312 } 313 314 fn main() -> ExitCode { 315 restore_sigpipe(); 316 match run() { 317 Ok(()) => ExitCode::SUCCESS, 318 Err(e) => { 319 eprintln!("pi-register: {e}"); 320 ExitCode::FAILURE 321 } 322 } 323 } 324 325 #[cfg(test)] 326 mod tests { 327 use super::*; 328 329 const SAMPLE: &str = r#" 330 [[service]] 331 name = "demo" 332 purpose = "Does a thing." 333 unit = "demo" 334 category = "network" 335 owner = "drake" 336 port = 8080 337 depends_on = ["other"] 338 files = ["/etc/demo.conf"] 339 secrets = "/etc/demo/secret" 340 health = "true" 341 boot = true 342 notes = "hi" 343 344 [[service]] 345 name = "min" 346 purpose = "Minimal." 347 unit = "min.service" 348 category = "bot" 349 owner = "drake" 350 boot = false 351 "#; 352 353 #[test] 354 fn parses_full_and_minimal_entries() { 355 let r = parse_register(SAMPLE).unwrap(); 356 assert_eq!(r.services.len(), 2); 357 assert_eq!(r.services[0].port, Some(8080)); 358 assert_eq!(r.services[0].depends_on, vec!["other"]); 359 assert!(r.services[1].port.is_none() && r.services[1].files.is_empty()); 360 } 361 362 #[test] 363 fn rejects_missing_required_field() { 364 assert!(parse_register("[[service]]\nname = \"x\"\n").is_err()); 365 } 366 367 #[test] 368 fn ignore_list_filters_base_units_only() { 369 assert!(is_ignored("systemd-journald.service")); 370 assert!(is_ignored("getty@tty1.service")); 371 assert!(is_ignored("ssh.service")); 372 assert!(is_ignored("chrony.service")); 373 assert!(is_ignored("piboot-try-reboot.service")); 374 assert!(is_ignored("containerd.service") && is_ignored("postfix.service") && is_ignored("ubuntu-fan.service")); 375 assert!(!is_ignored("headscale.service")); 376 assert!(!is_ignored("fail2ban.service")); 377 } 378 379 #[test] 380 fn unit_names_get_suffix() { 381 assert_eq!(full_unit("vault"), "vault.service"); 382 assert_eq!(full_unit("x.timer"), "x.timer"); 383 } 384 385 #[test] 386 fn unknown_name_is_refused() { 387 let r = parse_register(SAMPLE).unwrap(); 388 assert!(find(&r, "nope").is_err()); 389 assert!(find(&r, "demo").is_ok()); 390 } 391 }