system.rs (7696B)
1 //! The real backend: rpm-ostree for what is booted (ADR-0009: rpm-ostree, not bootc, because a 2 //! layered package makes bootc refuse), skopeo for what a registry has, and `patina-update` 3 //! through pkexec for what changes the system. 4 5 use std::io::{BufRead, BufReader}; 6 use std::process::{Command, Stdio}; 7 use std::sync::mpsc::Sender; 8 9 use crate::backend::{Action, Availability, Backend, Event, Status, valid_image, with_tag}; 10 11 /// The root helper, in the image (linux/system/usr/libexec/patina-update). Polkit knows it by this path. 12 const HELPER: &str = "/usr/libexec/patina-update"; 13 14 pub struct System; 15 16 /// rpm-ostree writes the image a deployment follows with its transport in front. 17 pub fn strip_transport(reference: &str) -> String { 18 if let Some((_, image)) = reference.split_once("docker://") { 19 return image.to_string(); 20 } 21 reference 22 .strip_prefix("ostree-unverified-registry:") 23 .unwrap_or(reference) 24 .to_string() 25 } 26 27 /// `rpm-ostree status --json`: the booted deployment, whether another is staged, whether an older 28 /// one is kept. 29 pub fn parse_status(json: &str) -> Result<Status, String> { 30 let value: serde_json::Value = 31 serde_json::from_str(json).map_err(|e| format!("rpm-ostree status: {e}"))?; 32 let deployments = value["deployments"] 33 .as_array() 34 .ok_or("rpm-ostree status: no deployments")?; 35 let booted = deployments 36 .iter() 37 .find(|d| d["booted"].as_bool() == Some(true)) 38 .ok_or("this system is not booted from an image rpm-ostree manages")?; 39 let text = |key: &str| booted[key].as_str().unwrap_or("").to_string(); 40 Ok(Status { 41 image: strip_transport(&text("container-image-reference")), 42 digest: text("container-image-reference-digest"), 43 version: text("version"), 44 staged: deployments 45 .iter() 46 .any(|d| d["staged"].as_bool() == Some(true)), 47 can_roll_back: deployments 48 .iter() 49 .filter(|d| d["staged"].as_bool() != Some(true)) 50 .count() 51 > 1, 52 }) 53 } 54 55 fn run_output(program: &str, args: &[&str]) -> Result<String, String> { 56 let out = Command::new(program) 57 .args(args) 58 .output() 59 .map_err(|e| format!("can't run {program}: {e}"))?; 60 if out.status.success() { 61 Ok(String::from_utf8_lossy(&out.stdout).trim().to_string()) 62 } else { 63 Err(last_line(&String::from_utf8_lossy(&out.stderr)) 64 .unwrap_or_else(|| format!("{program} failed"))) 65 } 66 } 67 68 fn last_line(text: &str) -> Option<String> { 69 text.lines() 70 .map(str::trim) 71 .rfind(|l| !l.is_empty()) 72 .map(str::to_string) 73 } 74 75 impl Backend for System { 76 fn status(&self) -> Result<Status, String> { 77 parse_status(&run_output("rpm-ostree", &["status", "--json"])?) 78 } 79 80 fn check(&self, image: &str) -> Result<Availability, String> { 81 if !valid_image(image) { 82 return Err(format!("{image} is not an image name")); 83 } 84 let digest = run_output( 85 "skopeo", 86 &[ 87 "inspect", 88 "--no-tags", 89 "--format", 90 "{{.Digest}}", 91 &format!("docker://{}", with_tag(image)), 92 ], 93 )?; 94 let booted = self.status()?; 95 Ok( 96 if digest == booted.digest && with_tag(image) == with_tag(&booted.image) { 97 Availability::UpToDate 98 } else { 99 Availability::Newer { digest } 100 }, 101 ) 102 } 103 104 fn run(&self, action: Action, tx: Sender<Event>) { 105 let args: Vec<String> = match &action { 106 Action::Update => vec!["upgrade".into()], 107 Action::Switch(image) => { 108 if !valid_image(image) { 109 let _ = tx.send(Event::Failed(format!("{image} is not an image name"))); 110 return; 111 } 112 vec!["switch".into(), with_tag(image)] 113 } 114 Action::RollBack => vec!["rollback".into()], 115 }; 116 std::thread::spawn(move || { 117 // Output and errors in one stream, so the screen shows them in the order they came. 118 let child = Command::new("sh") 119 .args(["-c", "exec \"$@\" 2>&1", "sh", "pkexec", HELPER]) 120 .args(&args) 121 .stdout(Stdio::piped()) 122 .spawn(); 123 let mut child = match child { 124 Ok(child) => child, 125 Err(e) => { 126 let _ = tx.send(Event::Failed(format!("can't run pkexec: {e}"))); 127 return; 128 } 129 }; 130 let mut last = None; 131 for line in BufReader::new(child.stdout.take().expect("piped")) 132 .lines() 133 .map_while(Result::ok) 134 { 135 let line = line.trim().to_string(); 136 if !line.is_empty() { 137 last = Some(line.clone()); 138 let _ = tx.send(Event::Line(line)); 139 } 140 } 141 let _ = tx.send(match child.wait().map(|s| s.code()) { 142 Ok(Some(0)) => Event::Done, 143 // pkexec: 126 is a dismissed password prompt, 127 an unauthorised one. 144 Ok(Some(126 | 127)) => { 145 Event::Failed("The password was not given, so nothing was changed".into()) 146 } 147 _ => Event::Failed(last.unwrap_or_else(|| "the update failed".into())), 148 }); 149 }); 150 } 151 152 fn restart(&self) -> Result<(), String> { 153 run_output("systemctl", &["reboot"]).map(|_| ()) 154 } 155 } 156 157 #[cfg(test)] 158 mod tests { 159 use super::*; 160 161 const STATUS: &str = r#"{"deployments":[ 162 {"booted":false,"staged":true,"version":"45.2","container-image-reference":"ostree-unverified-registry:ghcr.io/o/n:latest","container-image-reference-digest":"sha256:new"}, 163 {"booted":true,"staged":false,"version":"45.1","container-image-reference":"ostree-unverified-registry:ghcr.io/o/n:latest","container-image-reference-digest":"sha256:old"}, 164 {"booted":false,"staged":false,"version":"45.0","container-image-reference":"ostree-unverified-registry:ghcr.io/o/n:latest","container-image-reference-digest":"sha256:older"}]}"#; 165 166 #[test] 167 fn the_booted_deployment_is_the_status() { 168 let s = parse_status(STATUS).unwrap(); 169 assert_eq!(s.image, "ghcr.io/o/n:latest"); 170 assert_eq!(s.digest, "sha256:old"); 171 assert_eq!(s.version, "45.1"); 172 assert!(s.staged); 173 assert!(s.can_roll_back); 174 } 175 176 #[test] 177 fn one_deployment_has_nothing_to_roll_back_to() { 178 let one = r#"{"deployments":[{"booted":true,"container-image-reference":"ostree-image-signed:docker://ghcr.io/o/n:v1"}]}"#; 179 let s = parse_status(one).unwrap(); 180 assert_eq!(s.image, "ghcr.io/o/n:v1"); 181 assert!(!s.staged && !s.can_roll_back); 182 } 183 184 /// `rpm-ostree status --json` as the test VM printed it (a fresh install, one deployment). 185 #[test] 186 fn what_rpm_ostree_really_prints() { 187 let s = parse_status(include_str!("../tests/rpm-ostree-status.json")).unwrap(); 188 assert!( 189 s.image.contains('/') && !s.image.contains("ostree-"), 190 "{}", 191 s.image 192 ); 193 assert!(s.digest.starts_with("sha256:"), "{}", s.digest); 194 assert!(!s.version.is_empty()); 195 assert!(!s.staged && !s.can_roll_back); 196 } 197 198 #[test] 199 fn a_system_not_booted_from_an_image_is_an_error() { 200 assert!(parse_status(r#"{"deployments":[{"booted":false}]}"#).is_err()); 201 assert!(parse_status("not json").is_err()); 202 } 203 }