forge
Explore
Log in

Don't you dare go Hollow

kur

Clone
★ 0

0 watching0 forksRustAGPL-3.073.7 KiB6ae6238Tahinli21 days ago5 commits

install.rs347 lines, 11.7 KiBHistoryRawDownload
1//! Per-app install flow: download, check, swap, restart, health check, rollback.
2//! State files in `state_dir`: `{name}.bad` lists rejected sha256s, `{name}.tag` the last tag installed,
3//! `{name}.sha` the installed sha256 (unpack mode only).
4
5use crate::Res;
6use crate::config::{App, Config};
7use crate::forge::Forge;
8use sha2::{Digest, Sha256};
9use std::fs::{self, File, OpenOptions};
10use std::io::{ErrorKind, Read, Write};
11use std::os::unix::fs::DirBuilderExt;
12use std::path::{Path, PathBuf};
13use std::process::{Command, Stdio};
14use std::thread::sleep;
15use std::time::{Duration, Instant};
16
17const CHECK_TIMEOUT: Duration = Duration::from_secs(10);
18const HEALTH_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
19const STABLE_FOR: Duration = Duration::from_secs(5);
20
21/// Creates the state directory (mode 0700) if it does not exist.
22pub fn ensure_state_dir(dir: &Path) -> Res<()> {
23 fs::DirBuilder::new()
24 .recursive(true)
25 .mode(0o700)
26 .create(dir)
27 .map_err(|e| format!("state dir {}: {e}", dir.display()))
28}
29
30/// Takes the exclusive run lock (`state_dir/lock`). Fails at once if another run holds it.
31pub fn lock(dir: &Path) -> Res<File> {
32 let path = dir.join("lock");
33 let file = File::create(&path).map_err(|e| format!("open {}: {e}", path.display()))?;
34 file.try_lock()
35 .map_err(|_| "another kur run is in progress".to_string())?;
36 Ok(file)
37}
38
39/// `kur status` text for one app (after the name). Changes nothing.
40pub fn status(forge: &Forge, cfg: &Config, app: &App) -> Res<String> {
41 let (tag, asset) = forge.latest(app)?;
42 let installed = installed_sha(cfg, app)?;
43 let state = if installed.as_deref() == Some(asset.sha256.as_str()) {
44 "up to date"
45 } else if is_bad(cfg, app, &asset.sha256)? {
46 "skipped (bad build)"
47 } else {
48 "update available"
49 };
50 let inst = match &installed {
51 Some(sha) => format!("installed {}", short(sha)),
52 None => "not installed".to_string(),
53 };
54 Ok(format!(
55 "{inst}, newest {tag} {}: {state}",
56 short(&asset.sha256)
57 ))
58}
59
60/// Installs the newest release of one app if needed. Returns the status text after the app name.
61pub fn update(forge: &Forge, cfg: &Config, app: &App) -> Res<String> {
62 let (tag, asset) = forge.latest(app)?;
63 if installed_sha(cfg, app)?.as_deref() == Some(asset.sha256.as_str()) {
64 return Ok(format!("up to date ({tag})"));
65 }
66 if is_bad(cfg, app, &asset.sha256)? {
67 return Ok(format!("skipped (bad build {tag})"));
68 }
69
70 let staged = app.sibling(".kur-new");
71 if app.unpack {
72 let archive = app.sibling(".kur-new.tar.gz");
73 let _ = fs::remove_file(&archive);
74 remove_tree(&staged)?;
75 if let Err(e) = forge.download(&asset, &archive) {
76 let _ = fs::remove_file(&archive);
77 return Err(e);
78 }
79 let unpacked = unpack(&archive, &staged);
80 let _ = fs::remove_file(&archive);
81 if let Err(e) = unpacked {
82 let _ = fs::remove_dir_all(&staged);
83 mark_bad(cfg, app, &asset.sha256)?;
84 return Err(e);
85 }
86 } else {
87 let _ = fs::remove_file(&staged);
88 if let Err(e) = forge.download(&asset, &staged) {
89 let _ = fs::remove_file(&staged);
90 return Err(e);
91 }
92 if let Err(e) = check_binary(app, &staged) {
93 let _ = fs::remove_file(&staged);
94 mark_bad(cfg, app, &asset.sha256)?;
95 return Err(e);
96 }
97 }
98 swap(app, &staged)?;
99
100 let Some(unit) = app.unit.as_deref() else {
101 record_install(cfg, app, &tag, &asset.sha256)?;
102 return Ok(format!("{tag} installed"));
103 };
104 match deploy(app, unit) {
105 Ok(()) => {
106 record_install(cfg, app, &tag, &asset.sha256)?;
107 Ok(format!("{tag} installed"))
108 }
109 Err(reason) => {
110 let marked = mark_bad(cfg, app, &asset.sha256);
111 let mut msg = rollback(app, unit, &tag, &reason);
112 if let Err(e) = marked {
113 msg = format!("{msg}; could not record bad build: {e}");
114 }
115 Err(msg)
116 }
117 }
118}
119
120/// First 12 hex chars of a sha256, for display.
121fn short(sha: &str) -> &str {
122 sha.get(..12).unwrap_or(sha)
123}
124
125/// sha256 of the installed app: of the file, or in unpack mode the one recorded at install.
126/// None if nothing is installed.
127fn installed_sha(cfg: &Config, app: &App) -> Res<Option<String>> {
128 if !app.unpack {
129 return file_sha256(&app.path);
130 }
131 if !app.path.exists() {
132 return Ok(None);
133 }
134 match fs::read_to_string(state_file(cfg, app, "sha")) {
135 Ok(text) => Ok(Some(text.trim().to_string())),
136 Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
137 Err(e) => Err(format!("read sha: {e}")),
138 }
139}
140
141/// Removes the directory tree at `path`. A missing path is not an error.
142fn remove_tree(path: &Path) -> Res<()> {
143 match fs::remove_dir_all(path) {
144 Err(e) if e.kind() != ErrorKind::NotFound => Err(format!("remove {}: {e}", path.display())),
145 _ => Ok(()),
146 }
147}
148
149/// Lowercase hex sha256 of the file at `path`, or None if it does not exist.
150pub(crate) fn file_sha256(path: &Path) -> Res<Option<String>> {
151 let mut file = match File::open(path) {
152 Ok(file) => file,
153 Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
154 Err(e) => return Err(format!("open {}: {e}", path.display())),
155 };
156 let mut hasher = Sha256::new();
157 let mut buf = vec![0u8; 64 * 1024];
158 loop {
159 let n = file
160 .read(&mut buf)
161 .map_err(|e| format!("read {}: {e}", path.display()))?;
162 if n == 0 {
163 break;
164 }
165 hasher.update(&buf[..n]);
166 }
167 Ok(Some(hex::encode(hasher.finalize())))
168}
169
170fn state_file(cfg: &Config, app: &App, ext: &str) -> PathBuf {
171 cfg.state_dir.join(format!("{}.{ext}", app.name))
172}
173
174/// Whether `sha` is listed in the app's `.bad` file.
175fn is_bad(cfg: &Config, app: &App, sha: &str) -> Res<bool> {
176 match fs::read_to_string(state_file(cfg, app, "bad")) {
177 Ok(text) => Ok(text.lines().any(|line| line.trim() == sha)),
178 Err(e) if e.kind() == ErrorKind::NotFound => Ok(false),
179 Err(e) => Err(format!("read bad list: {e}")),
180 }
181}
182
183fn mark_bad(cfg: &Config, app: &App, sha: &str) -> Res<()> {
184 let path = state_file(cfg, app, "bad");
185 let mut file = OpenOptions::new()
186 .create(true)
187 .append(true)
188 .open(&path)
189 .map_err(|e| format!("open {}: {e}", path.display()))?;
190 writeln!(file, "{sha}").map_err(|e| format!("write {}: {e}", path.display()))
191}
192
193fn write_tag(cfg: &Config, app: &App, tag: &str) -> Res<()> {
194 let path = state_file(cfg, app, "tag");
195 fs::write(&path, tag).map_err(|e| format!("write {}: {e}", path.display()))
196}
197
198/// Records a successful install: the tag, and in unpack mode the asset sha256.
199fn record_install(cfg: &Config, app: &App, tag: &str, sha: &str) -> Res<()> {
200 write_tag(cfg, app, tag)?;
201 if app.unpack {
202 let path = state_file(cfg, app, "sha");
203 fs::write(&path, sha).map_err(|e| format!("write {}: {e}", path.display()))?;
204 }
205 Ok(())
206}
207
208/// Unpacks the gzip tar at `archive` into `dir`, which must not exist yet.
209fn unpack(archive: &Path, dir: &Path) -> Res<()> {
210 fs::create_dir(dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
211 let status = Command::new("tar")
212 .arg("-xzf")
213 .arg(archive)
214 .arg("-C")
215 .arg(dir)
216 .stdin(Stdio::null())
217 .status()
218 .map_err(|e| format!("cannot run tar: {e}"))?;
219 if status.success() {
220 Ok(())
221 } else {
222 Err(format!("tar exited with {status}"))
223 }
224}
225
226/// Runs the staged binary with the app's `check` args, if any. Fails on non-zero exit or timeout.
227fn check_binary(app: &App, staged: &Path) -> Res<()> {
228 let Some(args) = &app.check else {
229 return Ok(());
230 };
231 let mut child = Command::new(staged)
232 .args(args)
233 .stdin(Stdio::null())
234 .stdout(Stdio::null())
235 .stderr(Stdio::null())
236 .spawn()
237 .map_err(|e| format!("cannot run staged binary: {e}"))?;
238 let deadline = Instant::now() + CHECK_TIMEOUT;
239 loop {
240 if let Some(status) = child.try_wait().map_err(|e| format!("check: {e}"))? {
241 return if status.success() {
242 Ok(())
243 } else {
244 Err(format!("check exited with {status}"))
245 };
246 }
247 if Instant::now() >= deadline {
248 let _ = child.kill();
249 let _ = child.wait();
250 return Err("check timed out".into());
251 }
252 sleep(Duration::from_millis(50));
253 }
254}
255
256/// Moves the current binary (or directory, in unpack mode) to `.prev` and the staged one into place,
257/// then fsyncs the dir.
258fn swap(app: &App, staged: &Path) -> Res<()> {
259 if app.unpack {
260 remove_tree(&app.sibling(".prev"))?;
261 }
262 match fs::rename(&app.path, app.sibling(".prev")) {
263 Err(e) if e.kind() != ErrorKind::NotFound => {
264 return Err(format!("keep previous {}: {e}", app.path.display()));
265 }
266 _ => {}
267 }
268 fs::rename(staged, &app.path).map_err(|e| format!("install {}: {e}", app.path.display()))?;
269 let dir = app.path.parent().unwrap_or(Path::new("/"));
270 File::open(dir)
271 .and_then(|d| d.sync_all())
272 .map_err(|e| format!("fsync {}: {e}", dir.display()))
273}
274
275/// Restarts `unit` and waits until it is active and healthy, then requires it to stay active.
276/// Returns the failure reason on error.
277fn deploy(app: &App, unit: &str) -> Result<(), String> {
278 restart(unit)?;
279 let deadline = Instant::now() + Duration::from_secs(app.health_timeout_secs);
280 while !(is_active(unit) && health_ok(app.health_url.as_deref())) {
281 if Instant::now() >= deadline {
282 return Err("health check timed out".into());
283 }
284 sleep(Duration::from_secs(1));
285 }
286 sleep(STABLE_FOR);
287 if !is_active(unit) {
288 return Err(format!("{unit} stopped after health check"));
289 }
290 Ok(())
291}
292
293/// Restores `.prev` over the failed binary and restarts the unit. Returns the error text.
294fn rollback(app: &App, unit: &str, tag: &str, reason: &str) -> String {
295 let failed = format!("{tag} failed health check ({reason})");
296 if app.unpack
297 && let Err(e) = remove_tree(&app.path)
298 {
299 return format!("{failed}, restore failed: {e}");
300 }
301 match fs::rename(app.sibling(".prev"), &app.path) {
302 Ok(()) => match restart(unit) {
303 Ok(()) => format!("{failed}, rolled back"),
304 Err(e) => format!("{failed}, rolled back but {e}"),
305 },
306 Err(e) if e.kind() == ErrorKind::NotFound => {
307 format!("{failed}, no previous binary to restore")
308 }
309 Err(e) => format!("{failed}, restore failed: {e}"),
310 }
311}
312
313/// True if `url` is unset or answers 2xx within the request timeout. No token is sent.
314fn health_ok(url: Option<&str>) -> bool {
315 let Some(url) = url else {
316 return true;
317 };
318 ureq::get(url)
319 .config()
320 .timeout_global(Some(HEALTH_REQUEST_TIMEOUT))
321 .build()
322 .call()
323 .is_ok_and(|resp| resp.status().is_success())
324}
325
326fn restart(unit: &str) -> Result<(), String> {
327 systemctl(&["restart", unit])
328}
329
330fn is_active(unit: &str) -> bool {
331 systemctl(&["is-active", "--quiet", unit]).is_ok()
332}
333
334/// Runs `systemctl --user` with `args`. Only the user manager of the account kur runs as is used.
335pub(crate) fn systemctl(args: &[&str]) -> Result<(), String> {
336 let status = Command::new("systemctl")
337 .arg("--user")
338 .args(args)
339 .stdout(Stdio::null())
340 .status()
341 .map_err(|e| format!("systemctl: {e}"))?;
342 if status.success() {
343 Ok(())
344 } else {
345 Err(format!("systemctl {} failed", args.join(" ")))
346 }
347}