devsandbox 0.8.0

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
use std::path::Path;

use super::{run, services, start};
use crate::config::{Autostart, Config};
use crate::runtime::backend;
use crate::state::State;

/// Bring up every `autostart` sandbox of the config root in `dir`, once per
/// host boot (docs/architecture/automations/autostart.md). Called after
/// `run`/`start`/`rebuild` and by the daemon's startup pass
/// (`serve/host.rs`); never fails the caller — problems are
/// warnings on stderr. No loadable config or no readable boot id is a silent
/// no-op.
///
/// The boot is recorded (and saved) *before* acting, so a start that keeps
/// failing can't retrigger on every invocation; the next boot retries.
pub fn autostart(dir: &Path) {
    let Ok(config) = Config::load(dir) else { return };
    let Some(boot) = boot_id() else { return };
    let Ok(project) = services::project_id(dir) else { return };
    let state = match State::load() {
        Ok(state) => state,
        Err(e) => {
            eprintln!("warning: autostart: {e:#}");
            return;
        }
    };
    if !due(state.autostart_boot.get(&project).map(String::as_str), &boot) {
        return;
    }

    let sandboxes: Vec<String> = config
        .sandboxes
        .keys()
        .filter(|name| match config.resolve_sandbox(name) {
            Ok(sandbox) => sandbox.properties.autostart.unwrap_or_default() != Autostart::Off,
            // Surfaced by the command that uses it; autostart just skips it.
            Err(_) => false,
        })
        .cloned()
        .collect();
    // Not recorded: adding `autostart` later this boot must still take effect.
    if sandboxes.is_empty() {
        return;
    }
    // Not recorded either: with the runtime down (Docker Desktop not up yet,
    // Apple `container system start` not run) every inspect reads as "no such
    // container", so acting now would only print misleading notes and burn
    // this boot's pass.
    if let Err(e) = backend().list(false, crate::runtime::NAME_PREFIX) {
        eprintln!(
            "warning: autostart: {} is not reachable ({e:#}); retried on the next \
             `run`/`start`/`rebuild` or daemon start",
            runtime_label(backend().name())
        );
        return;
    }

    // Claimed under the state lock, so of two racing passes only one acts.
    let claimed = State::update(|fresh| {
        let due = due(fresh.autostart_boot.get(&project).map(String::as_str), &boot);
        if due {
            fresh.autostart_boot.insert(project.clone(), boot);
        }
        Ok(due)
    });
    match claimed {
        Ok(true) => {}
        Ok(false) => return,
        Err(e) => {
            // Acting without the record would repeat on every invocation.
            eprintln!("warning: autostart skipped: {e:#}");
            return;
        }
    }

    let rows: Vec<Row> = state
        .instances
        .iter()
        .map(|(key, info)| Row {
            key,
            sandbox: &info.sandbox,
            project: &info.project,
            child: info.dispatcher.is_some(),
            not_ready: info.progress.is_some(),
        })
        .collect();
    let actions = actions(&project, &sandboxes, &rows, |key| {
        match backend().is_running(&state.instances[key].container) {
            Ok(Some(true)) => Liveness::Running,
            Ok(Some(false)) => Liveness::Stopped,
            Ok(None) => Liveness::Missing,
            Err(e) => {
                eprintln!("warning: autostart: cannot inspect `{key}`: {e:#}");
                Liveness::Unknown
            }
        }
    });

    for action in actions {
        match action {
            Action::Start(key) => {
                println!("autostart: starting {key}");
                let info = &state.instances[&key];
                if let Err(e) = start::start_instance(dir, &key, info) {
                    eprintln!("warning: autostart: cannot start `{key}`: {e:#}");
                }
            }
            Action::Run(sandbox) => {
                println!("autostart: creating an instance of {sandbox}");
                let extras = Default::default();
                match run::run(dir, Some(sandbox.clone()), None, None, None, extras) {
                    Ok(Some(key)) => println!("{key}"),
                    Ok(None) => {}
                    Err(e) => eprintln!("warning: autostart: cannot run `{sandbox}`: {e:#}"),
                }
            }
            Action::SkipNotReady(key) => {
                let view = state.instances[&key].phase_view();
                if let Some(why) = super::not_ready(&key, view.as_ref()) {
                    eprintln!("note: autostart: skipping {why}");
                }
            }
            Action::SkipMissing(key) => {
                eprintln!(
                    "note: autostart: `{key}` has no container; `devsandbox run` recreates it"
                );
            }
        }
    }
}

/// An instance row from state, as the decision sees it.
struct Row<'a> {
    key: &'a str,
    sandbox: &'a str,
    project: &'a str,
    /// Dispatcher-owned (`Instance.dispatcher` set).
    child: bool,
    /// Being materialized, or failed (`Instance.progress` set,
    /// docs/architecture/instances/lifecycle.md).
    not_ready: bool,
}

/// Container state of an instance. `Unknown` (the runtime query failed) is
/// left alone but still counts as an existing instance, so no duplicate is
/// created.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Liveness {
    Running,
    Stopped,
    Missing,
    Unknown,
}

#[derive(Debug, PartialEq, Eq)]
enum Action {
    /// Start this stopped instance (full `start` path).
    Start(String),
    /// Create a first instance of this sandbox (`run` semantics).
    Run(String),
    /// The instance's container is gone; tell the user instead of recreating.
    SkipMissing(String),
    /// In flight or failed: its `run`/`rebuild` owns it, or the user decides
    /// (`rebuild` retries, `rm` removes); noted, never started.
    SkipNotReady(String),
}

/// Whether this boot still needs an autostart pass for the project.
fn due(recorded: Option<&str>, boot: &str) -> bool {
    recorded != Some(boot)
}

/// What to do for each autostart sandbox (in `sandboxes` order): its
/// instances from `project` are started when stopped, skipped when running,
/// noted when containerless; a sandbox with none gets a `Run`. Instances of
/// other config roots are ignored. `liveness` is only queried for relevant
/// instances, so unrelated containers cost no runtime call.
///
/// In-flight and failed instances are noted, never started (nor queried);
/// they still count as existing, so they get no duplicate `Run`.
///
/// Dispatcher children are never started or noted (and not queried): their
/// dispatcher `ensure`s them when it needs them. They still count as existing
/// instances, so a sandbox whose only instances are children gets no `Run` —
/// the dispatcher owns that fleet, and a stray non-child instance would be
/// one nobody asked for.
fn actions(
    project: &str,
    sandboxes: &[String],
    rows: &[Row],
    mut liveness: impl FnMut(&str) -> Liveness,
) -> Vec<Action> {
    let mut out = Vec::new();
    for sandbox in sandboxes {
        let mut any = false;
        for row in rows.iter().filter(|r| r.sandbox == sandbox && r.project == project) {
            any = true;
            if row.child {
                continue;
            }
            if row.not_ready {
                out.push(Action::SkipNotReady(row.key.to_string()));
                continue;
            }
            match liveness(row.key) {
                Liveness::Stopped => out.push(Action::Start(row.key.to_string())),
                Liveness::Missing => out.push(Action::SkipMissing(row.key.to_string())),
                Liveness::Running | Liveness::Unknown => {}
            }
        }
        if !any {
            out.push(Action::Run(sandbox.clone()));
        }
    }
    out
}

/// Restart policy an `autostart = "runtime"` container carries; `unless-stopped`
/// so a container the user stopped stays stopped across a runtime restart.
const RUNTIME_RESTART: &str = "unless-stopped";

/// The `--restart` policy to create a container with (only on backends that
/// support one) and the warnings to print at `run`. Podman only honors the
/// policy at boot through `podman-restart.service`, which devsandbox never
/// installs; Apple `container` has no restart policy, so the sandbox falls
/// back to the devsandbox-driven pass (`autostart = true`).
pub(crate) fn restart_decision(
    mode: Option<Autostart>,
    supported: bool,
    backend: &str,
) -> (Option<&'static str>, Vec<String>) {
    if mode != Some(Autostart::Runtime) {
        return (None, Vec::new());
    }
    if !supported {
        let runtime = runtime_label(backend);
        return (
            None,
            vec![format!(
                "autostart = \"runtime\" is unsupported on {runtime}; behaving as `true`"
            )],
        );
    }
    let mut warnings = Vec::new();
    if backend == "podman" {
        warnings.push(
            "autostart = \"runtime\": podman restarts containers at boot only with \
             `podman-restart.service` enabled (devsandbox never installs it)"
                .to_string(),
        );
    }
    (Some(RUNTIME_RESTART), warnings)
}

/// Backend name as users know it in messages.
fn runtime_label(backend: &str) -> &str {
    if backend == "container" { "Apple container" } else { backend }
}

/// Whether the runtime itself restarts the container (`"runtime"` on a backend
/// with restart policies). Then the in-container boot hook, not the host, owns
/// `postStartCommand` on `start` (docs/architecture/automations/autostart.md);
/// elsewhere `"runtime"` behaves as `true` (see [`restart_decision`]).
pub(crate) fn runtime_restarts(mode: Option<Autostart>, supported: bool) -> bool {
    mode == Some(Autostart::Runtime) && supported
}

/// The policy to switch an existing container to so it matches `mode`, or
/// `None` when `current` already does. `autostart` isn't hashed for drift, so
/// a flip is applied in place on start instead of requiring a rebuild. An
/// unset policy (empty) counts as `no`; an unknown current policy is updated.
fn restart_update(mode: Option<Autostart>, current: Option<&str>) -> Option<&'static str> {
    let desired = if mode == Some(Autostart::Runtime) { RUNTIME_RESTART } else { "no" };
    let current = current.map(|c| if c.is_empty() { "no" } else { c });
    (current != Some(desired)).then_some(desired)
}

/// Bring `container`'s restart policy in line with `mode` (no-op on backends
/// without restart policies). Never fails the caller: an old podman without
/// `update --restart` gets a warning pointing at a recreate.
pub(crate) fn apply_restart_policy(container: &str, instance: &str, mode: Option<Autostart>) {
    if !backend().supports_restart_policy() {
        return;
    }
    let current = backend().restart_policy(container).ok().flatten();
    let Some(policy) = restart_update(mode, current.as_deref()) else { return };
    if let Err(e) = backend().set_restart_policy(container, policy) {
        eprintln!(
            "warning: cannot change restart policy of {container}: {e:#}; \
             recreate with `devsandbox rebuild --force {instance}`"
        );
    }
}

/// The host's current boot id, or `None` when it can't be read (or the OS has
/// no supported source). Also stamped on an instance's `progress`, so a
/// reader can tell a phase recorded before a reboot (`state::Progress::view`).
/// Cached for the process: it can't change while we run, and the snapshot
/// asks once per instance per tick (a `sysctl` spawn on macOS).
pub(crate) fn boot_id() -> Option<String> {
    static CACHED: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
    CACHED.get_or_init(read_boot_id).clone()
}

fn read_boot_id() -> Option<String> {
    #[cfg(target_os = "linux")]
    {
        let text = std::fs::read_to_string("/proc/sys/kernel/random/boot_id").ok()?;
        parse_linux_boot_id(&text)
    }
    #[cfg(target_os = "macos")]
    {
        let out = std::process::Command::new("sysctl")
            .args(["-n", "kern.boottime"])
            .stderr(std::process::Stdio::null())
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        parse_macos_boottime(&String::from_utf8_lossy(&out.stdout))
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        None
    }
}

#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn parse_linux_boot_id(text: &str) -> Option<String> {
    let id = text.trim();
    (!id.is_empty()).then(|| id.to_string())
}

/// `sysctl -n kern.boottime` prints `{ sec = 1695000000, usec = 123456 } Mon
/// Sep 18 …`; the braced part is the stable id (the date suffix is
/// locale/timezone-dependent).
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn parse_macos_boottime(text: &str) -> Option<String> {
    let text = text.trim_start();
    if !text.starts_with('{') {
        return None;
    }
    let end = text.find('}')?;
    Some(text[..=end].to_string())
}

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

    fn row<'a>(key: &'a str, sandbox: &'a str, project: &'a str) -> Row<'a> {
        Row { key, sandbox, project, child: false, not_ready: false }
    }

    fn child<'a>(key: &'a str, sandbox: &'a str, project: &'a str) -> Row<'a> {
        Row { key, sandbox, project, child: true, not_ready: false }
    }

    fn names(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn due_once_per_boot() {
        assert!(due(None, "b1"));
        assert!(due(Some("b0"), "b1"));
        assert!(!due(Some("b1"), "b1"));
    }

    #[test]
    fn stopped_started_running_skipped_missing_noted() {
        let rows = [row("web", "web", "p"), row("web-2", "web", "p"), row("web-3", "web", "p")];
        let got = actions("p", &names(&["web"]), &rows, |key| match key {
            "web" => Liveness::Running,
            "web-2" => Liveness::Stopped,
            _ => Liveness::Missing,
        });
        assert_eq!(got, [Action::Start("web-2".into()), Action::SkipMissing("web-3".into())]);
    }

    #[test]
    fn no_instance_runs_one() {
        let got = actions("p", &names(&["triage"]), &[], |_| unreachable!());
        assert_eq!(got, [Action::Run("triage".into())]);
    }

    #[test]
    fn other_project_ignored_and_does_not_suppress_run() {
        let rows = [row("web", "web", "other")];
        let got = actions("p", &names(&["web"]), &rows, |_| panic!("not queried"));
        assert_eq!(got, [Action::Run("web".into())]);
    }

    #[test]
    fn non_autostart_sandboxes_ignored() {
        let rows = [row("api", "api", "p")];
        let got = actions("p", &names(&["web"]), &rows, |_| panic!("not queried"));
        assert_eq!(got, [Action::Run("web".into())]);
    }

    #[test]
    fn unknown_liveness_neither_starts_nor_runs() {
        let rows = [row("web", "web", "p")];
        assert!(actions("p", &names(&["web"]), &rows, |_| Liveness::Unknown).is_empty());
    }

    #[test]
    fn stopped_child_not_started_nor_queried() {
        let rows = [child("triage-pr-1", "triage", "p")];
        let got = actions("p", &names(&["triage"]), &rows, |_| panic!("not queried"));
        assert!(got.is_empty(), "{got:?}");
    }

    #[test]
    fn only_children_suppress_run() {
        let rows = [child("triage-pr-1", "triage", "p"), child("triage-pr-2", "triage", "p")];
        assert!(actions("p", &names(&["triage"]), &rows, |_| panic!("not queried")).is_empty());
    }

    #[test]
    fn child_and_normal_instance_only_normal_started() {
        let rows = [child("web-pr-1", "web", "p"), row("web", "web", "p")];
        let got = actions("p", &names(&["web"]), &rows, |key| {
            assert_eq!(key, "web", "child queried");
            Liveness::Stopped
        });
        assert_eq!(got, [Action::Start("web".into())]);
    }

    #[test]
    fn in_flight_or_failed_noted_not_queried_and_no_duplicate_run() {
        let rows = [Row { not_ready: true, ..row("web", "web", "p") }];
        let got = actions("p", &names(&["web"]), &rows, |_| panic!("not queried"));
        assert_eq!(got, [Action::SkipNotReady("web".into())]);
    }

    #[test]
    fn parses_linux_boot_id() {
        assert_eq!(parse_linux_boot_id("3f2c-9a\n").as_deref(), Some("3f2c-9a"));
        assert_eq!(parse_linux_boot_id(" \n"), None);
    }

    #[test]
    fn parses_macos_boottime() {
        let out = "{ sec = 1695000000, usec = 123456 } Mon Sep 18 10:00:00 2023\n";
        assert_eq!(
            parse_macos_boottime(out).as_deref(),
            Some("{ sec = 1695000000, usec = 123456 }")
        );
        assert_eq!(parse_macos_boottime("garbage"), None);
        assert_eq!(parse_macos_boottime("{ sec = 1"), None);
    }

    #[test]
    fn restart_flag_on_docker_for_runtime_only() {
        assert_eq!(
            restart_decision(Some(Autostart::Runtime), true, "docker"),
            (Some("unless-stopped"), Vec::new())
        );
        for mode in [None, Some(Autostart::Off), Some(Autostart::Devsandbox)] {
            for (supported, name) in [(true, "docker"), (true, "podman"), (false, "container")] {
                assert_eq!(restart_decision(mode, supported, name), (None, Vec::new()));
            }
        }
    }

    #[test]
    fn restart_flag_on_podman_warns_about_service() {
        let (policy, warnings) = restart_decision(Some(Autostart::Runtime), true, "podman");
        assert_eq!(policy, Some("unless-stopped"));
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("podman-restart.service"), "{warnings:?}");
    }

    #[test]
    fn restart_unsupported_on_apple_falls_back() {
        assert_eq!(
            restart_decision(Some(Autostart::Runtime), false, "container"),
            (
                None,
                vec![
                    "autostart = \"runtime\" is unsupported on Apple container; behaving as `true`"
                        .to_string()
                ]
            )
        );
    }

    #[test]
    fn runtime_restarts_needs_runtime_mode_and_support() {
        assert!(runtime_restarts(Some(Autostart::Runtime), true));
        assert!(!runtime_restarts(Some(Autostart::Runtime), false));
        for mode in [None, Some(Autostart::Off), Some(Autostart::Devsandbox)] {
            assert!(!runtime_restarts(mode, true));
        }
    }

    #[test]
    fn restart_update_only_on_mismatch() {
        let rt = Some(Autostart::Runtime);
        assert_eq!(restart_update(rt, Some("unless-stopped")), None);
        assert_eq!(restart_update(rt, Some("no")), Some("unless-stopped"));
        assert_eq!(restart_update(rt, Some("")), Some("unless-stopped"));
        assert_eq!(restart_update(rt, Some("always")), Some("unless-stopped"));
        assert_eq!(restart_update(rt, None), Some("unless-stopped"));
        for mode in [None, Some(Autostart::Off), Some(Autostart::Devsandbox)] {
            assert_eq!(restart_update(mode, Some("no")), None);
            assert_eq!(restart_update(mode, Some("")), None);
            assert_eq!(restart_update(mode, Some("unless-stopped")), Some("no"));
            assert_eq!(restart_update(mode, None), Some("no"));
        }
    }
}