zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
//! The Colima backend of [`super::Runtime`] (zc#578), macOS's second choice
//! after Lima: the same contract on a zc-created Colima profile, `zakuro`.
//!
//! Colima is Lima underneath with Docker (or containerd) preinstalled, which
//! is why an owner may already have it and not Lima. zc still owns its VM:
//!
//! - every command names the profile (`-p zakuro`); the `default` profile
//!   and any other profile are never started, stopped, resized or used;
//! - the VM is sized from the node budget (cpu, memory, disk), Apple
//!   Virtualization (`vz`) with Rosetta on Apple Silicon, and only the zakuro
//!   work directory is mounted, writable (Colima's own default of mounting
//!   the home is replaced). A profile that mounts the home writable, or that
//!   still has Colima's default mounts, is refused, not adopted;
//! - workloads run through `colima -p zakuro ssh -- docker …`, i.e. the
//!   Docker daemon INSIDE the VM. The alternative, the `colima-zakuro` Docker
//!   context, needs a host `docker` CLI and trusts the context selection
//!   (`DOCKER_HOST`, `docker context use`) to point at the right daemon, so
//!   a wrong environment could put a job on the owner's Docker Desktop. With
//!   `ssh` there is no host context to get wrong, and no host Docker is
//!   needed at all. (`colima nerdctl` would need the containerd runtime and
//!   gives up Docker's mature limits handling.)
//! - no GPU passthrough exists on macOS: a GPU request is refused.
//!
//! Every `colima` call goes through one [`ColimaCli`] (argv in, stdout out,
//! plus the profile's config file), so a fake drives each path in tests.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use super::lima::{
    check_publish, drift, gib_flag, map_mounts, owned_name, refuse_gpu, resolve_binary, run_cli, s,
    vm_cpus, vm_disk_gib, writable_home_mount, Host,
};
use super::lxc::SandboxSize;
use super::{docker, Allocation, Budget, HostResources, Limits, Probe, Runtime, RuntimeKind};
use super::{StartSpec, State, GIB};

/// The one Colima profile every workload runs in.
pub const PROFILE: &str = "zakuro";
/// What the CLI error starts with when the binary is not there.
pub const NOT_INSTALLED: &str = "colima is not installed";
/// First Colima with `--vz-rosetta`, `--activate`, `list --json` and
/// `ssh --` as used here. Verified on 0.10.3.
pub const MIN_VERSION: (u32, u32, u32) = (0, 8, 0);

/// The slice of Colima a backend needs.
pub trait ColimaCli: Send + Sync {
    /// Run one `colima …` argv (`argv[0]` is `colima`): trimmed stdout, or
    /// trimmed stderr as the error.
    fn run(&self, argv: &[String]) -> Result<String, String>;
    /// The text of `profile`'s `colima.yaml`, `None` when it has none.
    fn config(&self, profile: &str) -> Result<Option<String>, String>;
}

/// The real one: shells out and reads `~/.colima/<profile>/colima.yaml`
/// (`COLIMA_HOME`, or `$XDG_CONFIG_HOME/colima` when that is where it lives).
pub struct ColimaShell {
    bin: String,
}

impl ColimaShell {
    /// `ZAKURO_COLIMA`, else `colima` on `PATH`, else the Homebrew prefixes.
    pub fn new() -> Self {
        Self {
            bin: resolve_binary(
                "colima",
                "ZAKURO_COLIMA",
                &|k| std::env::var(k).ok(),
                &|p| p.is_file(),
            ),
        }
    }

    /// The `colima` this host runs.
    pub fn binary() -> String {
        Self::new().bin
    }

    fn config_path(profile: &str) -> Option<PathBuf> {
        let home = std::env::var_os("HOME").map(PathBuf::from);
        let mut roots: Vec<PathBuf> = Vec::new();
        if let Some(c) = std::env::var_os("COLIMA_HOME") {
            roots.push(c.into());
        }
        if let Some(h) = &home {
            roots.push(h.join(".colima"));
        }
        if let Some(x) = std::env::var_os("XDG_CONFIG_HOME") {
            roots.push(Path::new(&x).join("colima"));
        }
        if let Some(h) = &home {
            roots.push(h.join(".config").join("colima"));
        }
        let rel = Path::new(profile).join("colima.yaml");
        roots.iter().map(|r| r.join(&rel)).find(|p| p.is_file())
    }
}

impl Default for ColimaShell {
    fn default() -> Self {
        Self::new()
    }
}

impl ColimaCli for ColimaShell {
    fn run(&self, argv: &[String]) -> Result<String, String> {
        run_cli(&self.bin, "colima", NOT_INSTALLED, argv, None)
    }

    fn config(&self, profile: &str) -> Result<Option<String>, String> {
        match Self::config_path(profile) {
            None => Ok(None),
            Some(p) => std::fs::read_to_string(&p)
                .map(Some)
                .map_err(|e| format!("cannot read {}: {e}", p.display())),
        }
    }
}

/// One profile as `colima list --json` reports it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Info {
    pub name: String,
    pub status: String,
    pub cpus: u32,
    pub memory_bytes: u64,
    pub disk_bytes: u64,
}

/// Parse `colima list --json`: one JSON object per line.
pub fn parse_list(out: &str) -> Vec<Info> {
    out.lines()
        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok())
        .filter_map(|v| {
            Some(Info {
                name: v["name"].as_str()?.to_string(),
                status: v["status"].as_str().unwrap_or("").to_string(),
                cpus: v["cpus"].as_u64().unwrap_or(0) as u32,
                memory_bytes: v["memory"].as_u64().unwrap_or(0),
                disk_bytes: v["disk"].as_u64().unwrap_or(0),
            })
        })
        .collect()
}

/// The mounts section of a `colima.yaml`: `None` when it is empty (`mounts:
/// []` or absent, where Colima mounts the owner's home by default), else
/// `(location, writable)` of each entry. A small reader for the one shape
/// Colima writes; it avoids a YAML dependency for three keys.
pub fn parse_mounts(yaml: &str) -> Option<Vec<(String, bool)>> {
    let mut lines = yaml.lines();
    let first = lines
        .by_ref()
        .find(|l| l.starts_with("mounts:"))?
        .trim_start_matches("mounts:")
        .trim();
    if first.starts_with('[') {
        // `[]`: defaults. An inline non-empty flow list is not what Colima
        // writes; treat it as unreadable, i.e. not adoptable.
        return (first != "[]").then(Vec::new);
    }
    let unq = |v: &str| v.trim().trim_matches(|c| c == '"' || c == '\'').to_string();
    let mut out: Vec<(String, bool)> = Vec::new();
    for l in lines {
        // The section ends at the next top-level key or comment-free blank run.
        if !l.is_empty() && !l.starts_with(' ') && !l.starts_with('-') && !l.starts_with('#') {
            break;
        }
        let t = l.trim().trim_start_matches('-').trim();
        if let Some(loc) = t.strip_prefix("location:") {
            out.push((unq(loc), false));
        } else if let Some(w) = t.strip_prefix("writable:") {
            if let Some(last) = out.last_mut() {
                last.1 = unq(w) == "true";
            }
        }
    }
    (!out.is_empty()).then_some(out)
}

/// `colima start …` for a zc-owned profile.
pub fn start_argv(
    profile: &str,
    size: &SandboxSize,
    host: &Host,
    grow_disk: bool,
    fresh: bool,
) -> Vec<String> {
    let mut a = s(&["colima", "start", "-p", profile]);
    if fresh {
        a.extend(s(&["--runtime", "docker", "--vm-type", "vz"]));
        if host.apple_silicon {
            a.push("--vz-rosetta".into());
        }
        // Never switch the owner's Docker context to this VM, and keep its
        // ssh config out of the owner's ~/.ssh.
        a.extend(s(&["--activate=false", "--ssh-config=false"]));
        if let Some(w) = &host.work_dir {
            a.push("--mount".into());
            a.push(format!("{}:w", w.display()));
        } else {
            a.extend(s(&["--mount", "none"]));
        }
    }
    // Short flags: Colima 0.8 (our minimum) spells the first one `--cpu` and
    // rejects `--cpus` ("unknown flag"), which left the VM uncreated and the
    // worker crash-looping. `-c`, `-m` and `-d` are the same in every release.
    a.extend(s(&["-c", &vm_cpus(&size.limits).to_string()]));
    a.extend(s(&["-m", &gib_flag(size.limits.memory_bytes)]));
    if fresh || grow_disk {
        a.extend(s(&["-d", &vm_disk_gib(size).to_string()]));
    }
    a
}

/// `(major, minor, patch)` from `colima version 0.10.3`.
pub fn parse_version(out: &str) -> Option<(u32, u32, u32)> {
    super::lima::parse_version(out.lines().next()?)
}

/// The guest-side rules (Docker's `DOCKER-USER` hook): containers on any
/// Docker bridge cannot reach the Lima host gateway, the owner's LAN or
/// link-local, while DNS and the internet work and bridges still reach each
/// other. Applied at every start (rules do not survive a guest reboot).
pub fn egress_script() -> String {
    "set -e; \
     iptables -N ZAKURO-EGRESS 2>/dev/null || true; iptables -F ZAKURO-EGRESS; \
     iptables -A ZAKURO-EGRESS -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN; \
     iptables -A ZAKURO-EGRESS -o docker0 -j RETURN; iptables -A ZAKURO-EGRESS -o br-+ -j RETURN; \
     for ns in $(awk '/^nameserver/{print $2}' /etc/resolv.conf /run/systemd/resolve/resolv.conf 2>/dev/null | grep -E '^[0-9.]+$' | sort -u); do \
       iptables -A ZAKURO-EGRESS -d $ns -p udp --dport 53 -j RETURN; \
       iptables -A ZAKURO-EGRESS -d $ns -p tcp --dport 53 -j RETURN; \
     done; \
     for r in 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 169.254.0.0/16 100.64.0.0/10; do \
       iptables -A ZAKURO-EGRESS -d $r -j REJECT; \
     done; \
     for i in docker0 br-+; do \
       iptables -C DOCKER-USER -i $i -j ZAKURO-EGRESS 2>/dev/null || iptables -I DOCKER-USER 1 -i $i -j ZAKURO-EGRESS; \
     done; \
     iptables -N ZAKURO-IN 2>/dev/null || true; iptables -F ZAKURO-IN; \
     for ns in $(awk '/^nameserver/{print $2}' /etc/resolv.conf /run/systemd/resolve/resolv.conf 2>/dev/null | grep -E '^[0-9.]+$' | sort -u); do \
       iptables -A ZAKURO-IN -d $ns -p udp --dport 53 -j RETURN; \
       iptables -A ZAKURO-IN -d $ns -p tcp --dport 53 -j RETURN; \
     done; \
     iptables -A ZAKURO-IN -d 172.16.0.0/12 -j RETURN; \
     iptables -A ZAKURO-IN -m addrtype --dst-type LOCAL -j REJECT; \
     for i in docker0 br-+; do \
       iptables -C INPUT -i $i -j ZAKURO-IN 2>/dev/null || iptables -I INPUT 1 -i $i -j ZAKURO-IN; \
     done"
        .to_string()
}

static ENSURE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Colima as a [`Runtime`].
#[derive(Clone)]
pub struct ColimaRuntime {
    cli: Arc<dyn ColimaCli>,
    profile: String,
    size: Result<SandboxSize, String>,
    host: Host,
    /// Creates the work directory the VM mounts (the real filesystem;
    /// a no-op in unit tests, which must not write outside a temp dir).
    mkdir: fn(&std::path::Path) -> std::io::Result<()>,
    /// This Mac's version, when known: Colima's vz needs 13.5, like Lima's
    /// ([`super::provision::MIN_MACOS`]). `None` (tests, unknown) passes.
    macos_version: Option<(u32, u32)>,
}

impl ColimaRuntime {
    pub fn new(
        cli: Arc<dyn ColimaCli>,
        profile: &str,
        size: Result<SandboxSize, String>,
        host: Host,
    ) -> Self {
        Self {
            cli,
            profile: profile.to_string(),
            size,
            host,
            mkdir: |p| std::fs::create_dir_all(p),
            macos_version: None,
        }
    }

    /// Replace the directory creator (tests).
    #[cfg(test)]
    pub(crate) fn with_mkdir(mut self, f: fn(&std::path::Path) -> std::io::Result<()>) -> Self {
        self.mkdir = f;
        self
    }

    pub fn from_env(cli: Arc<dyn ColimaCli>, get: &dyn Fn(&str) -> Option<String>) -> Self {
        let profile = get("ZAKURO_COLIMA_PROFILE")
            .map(|v| v.trim().to_string())
            .filter(|v| !v.is_empty())
            .unwrap_or_else(|| PROFILE.to_string());
        let size = Budget::from_env(get)
            .and_then(|b| SandboxSize::from_budget(&b, &HostResources::detect()));
        Self::new(cli, &profile, size, Host::detect())
    }

    /// The real CLI. The VM is sized to the owner's limit for the whole
    /// machine ([`super::machine_size`]): the limit set in the app, not the
    /// built-in default, and the same for every node on the machine.
    pub fn shell() -> Self {
        let mut rt = Self::from_env(Arc::new(ColimaShell::new()), &|k| std::env::var(k).ok());
        rt.size = super::machine_size();
        rt.macos_version = super::provision::macos_version();
        rt
    }

    /// The zc-created profile's name.
    pub fn profile(&self) -> &str {
        &self.profile
    }

    fn colima(&self, rest: &[&str]) -> Result<String, String> {
        let mut argv = vec!["colima".to_string()];
        argv.extend(rest.iter().map(|a| a.to_string()));
        self.cli.run(&argv)
    }

    /// A Docker-shaped argv run through the Docker daemon inside the VM.
    pub fn in_vm(&self, docker_argv: &[String]) -> Vec<String> {
        let mut a = s(&["colima", "ssh", "-p", &self.profile, "--", "docker"]);
        let rest = match docker_argv.first().map(String::as_str) {
            Some("docker") => &docker_argv[1..],
            _ => docker_argv,
        };
        a.extend(rest.iter().cloned());
        a
    }

    /// `sh -c <script>` inside the VM (read-only probes such as
    /// `/proc/meminfo` for the agent's resources view).
    pub fn exec_sh(&self, script: &str) -> Result<String, String> {
        self.colima(&["ssh", "-p", &self.profile, "--", "sh", "-c", script])
    }

    fn docker(&self, docker_argv: &[String]) -> Result<String, String> {
        self.cli.run(&self.in_vm(docker_argv))
    }

    pub fn info(&self) -> Result<Option<Info>, String> {
        let out = self.colima(&["list", "--json"])?;
        Ok(parse_list(&out)
            .into_iter()
            .find(|i| i.name == self.profile))
    }

    fn running(i: &Info) -> bool {
        i.status.eq_ignore_ascii_case("Running")
    }

    /// Why this profile cannot be adopted, if it cannot.
    fn adoption_problem(&self) -> Result<Option<String>, String> {
        let Some(yaml) = self.cli.config(&self.profile)? else {
            return Ok(None);
        };
        let p = &self.profile;
        let Some(mounts) = parse_mounts(&yaml) else {
            return Ok(Some(format!(
                "colima profile {p} has Colima's default mounts, which include the owner's home; \
                 refusing to adopt it (`colima delete -p {p}` and zc recreates it with only \
                 the zakuro work directory)"
            )));
        };
        Ok(self.host.home.as_deref().and_then(|h| {
            writable_home_mount(&mounts, h).map(|m| {
                format!(
                    "colima profile {p} mounts {m} writable, which gives the VM the owner's \
                     home; refusing to adopt it (`colima delete -p {p}` and zc recreates it)"
                )
            })
        }))
    }

    pub fn resize_pending(&self) -> Result<bool, String> {
        let size = self.size.clone()?;
        Ok(self
            .info()?
            .map(|i| drift(i.cpus, i.memory_bytes, i.disk_bytes, &size).any())
            .unwrap_or(false))
    }

    /// Create the profile, or bring an existing one to the budget, start it,
    /// and apply the guest firewall.
    pub fn ensure(&self) -> Result<(), String> {
        let _g = ENSURE_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        owned_name(&self.profile, "Colima profile")?;
        if !self.host.macos {
            return Err("the colima backend runs on macOS only".into());
        }
        if let Some(why) = super::provision::too_old(self.macos_version) {
            return Err(why);
        }
        let size = self.size.clone()?;
        let p = self.profile.as_str();
        match self.info()? {
            None => {
                if let Some(problem) = self.adoption_problem()? {
                    return Err(problem);
                }
                if let Some(w) = &self.host.work_dir {
                    (self.mkdir)(w).map_err(|e| format!("cannot create {}: {e}", w.display()))?;
                }
                self.cli
                    .run(&start_argv(p, &size, &self.host, false, true))
                    .map_err(|e| format!("colima start -p {p} failed: {e}"))?;
            }
            Some(info) => {
                if let Some(problem) = self.adoption_problem()? {
                    return Err(problem);
                }
                let d = drift(info.cpus, info.memory_bytes, info.disk_bytes, &size);
                if Self::running(&info) {
                    if d.any() && self.is_idle()? {
                        self.colima(&["stop", "-p", p])?;
                        self.cli
                            .run(&start_argv(p, &size, &self.host, d.disk_grows, false))
                            .map_err(|e| format!("colima start -p {p} failed: {e}"))?;
                    }
                } else if info.status.eq_ignore_ascii_case("Stopped") {
                    self.cli
                        .run(&start_argv(p, &size, &self.host, d.disk_grows, false))
                        .map_err(|e| format!("colima start -p {p} failed: {e}"))?;
                } else {
                    return Err(format!(
                        "colima profile {p} is {} (not Running or Stopped); \
                         `colima delete -p {p}` and zc recreates it",
                        info.status
                    ));
                }
            }
        }
        let mut fw = s(&["colima", "ssh", "-p", p, "--", "sudo", "sh", "-c"]);
        fw.push(egress_script());
        self.cli
            .run(&fw)
            .map_err(|e| format!("applying the guest firewall in {p} failed: {e}"))?;
        self.docker(&s(&["version"]))
            .map_err(|e| format!("docker is not ready in colima profile {p}: {e}"))?;
        Ok(())
    }

    fn is_idle(&self) -> Result<bool, String> {
        Ok(self.docker(&s(&["ps", "-q"]))?.trim().is_empty())
    }
}

impl Runtime for ColimaRuntime {
    fn kind(&self) -> RuntimeKind {
        RuntimeKind::Colima
    }

    fn probe(&self) -> Probe {
        let no = |detail: String| Probe {
            kind: RuntimeKind::Colima,
            available: false,
            detail,
        };
        if !self.host.macos {
            return no("macOS only".into());
        }
        if let Some(why) = super::provision::too_old(self.macos_version) {
            return no(why);
        }
        if let Err(e) = owned_name(&self.profile, "Colima profile") {
            return no(e);
        }
        let out = match self.colima(&["version"]) {
            Ok(v) => v,
            Err(e) if e.starts_with(NOT_INSTALLED) => {
                return no(format!(
                    "{NOT_INSTALLED} (brew install colima, or set ZAKURO_COLIMA)"
                ))
            }
            Err(e) => return no(e.lines().next().unwrap_or("colima version failed").into()),
        };
        let Some(v) = parse_version(&out) else {
            return no(format!("cannot read the colima version from {out:?}"));
        };
        if v < MIN_VERSION {
            return no(format!(
                "colima {}.{}.{} is too old: zc needs {}.{}.{} or newer (brew upgrade colima)",
                v.0, v.1, v.2, MIN_VERSION.0, MIN_VERSION.1, MIN_VERSION.2
            ));
        }
        let vm = match self.info() {
            Err(e) => return no(e.lines().next().unwrap_or("colima list failed").into()),
            Ok(None) => "not created yet (created at the first start)".to_string(),
            Ok(Some(i)) => {
                match self.adoption_problem() {
                    Ok(Some(p)) => return no(p),
                    Ok(None) => {}
                    Err(e) => return no(e),
                }
                format!(
                    "{} ({} cpu, {:.1} GiB memory)",
                    i.status.to_lowercase(),
                    i.cpus,
                    i.memory_bytes as f64 / GIB
                )
            }
        };
        Probe {
            kind: RuntimeKind::Colima,
            available: true,
            detail: format!(
                "colima {}.{}.{}, vz profile {} {vm}",
                v.0, v.1, v.2, self.profile
            ),
        }
    }

    fn verify_image(&self, image: &str, expected_digest: Option<&str>) -> Result<(), String> {
        let out = self
            .docker(&s(&[
                "docker",
                "image",
                "inspect",
                "--format",
                "{{.Id}}|{{json .RepoDigests}}",
                image,
            ]))
            .map_err(|e| {
                format!(
                    "image {image} is not in colima profile {}: {e}",
                    self.profile
                )
            })?;
        let Some(want) = expected_digest else {
            return Ok(());
        };
        let want = want.rsplit('@').next().unwrap_or(want);
        if out.contains(want) {
            Ok(())
        } else {
            Err(format!(
                "image {image} does not match the expected digest {want}"
            ))
        }
    }

    fn start(&self, spec: &StartSpec) -> Result<String, String> {
        refuse_gpu("colima", spec)?;
        check_publish("colima", &spec.publish)?;
        let mounts = map_mounts(self.host.work_dir.as_deref(), &spec.mounts)?;
        self.ensure()?;
        let size = self.size.clone()?;
        let mut inner = spec.clone();
        inner.mounts = mounts;
        inner.limits = Limits {
            cpu_millis: inner.limits.cpu_millis.min(size.limits.cpu_millis),
            memory_bytes: inner.limits.memory_bytes.min(size.limits.memory_bytes),
            gpus: super::Gpus::None,
        };
        if spec.create_network {
            if let Some(net) = &spec.network {
                let _ = self.docker(&s(&["docker", "network", "create", net]));
            }
        }
        let mut run = vec!["docker".to_string()];
        run.extend(docker::run_argv(&inner));
        self.docker(&run)
    }

    fn exec(&self, name: &str, argv: &[String], detach: bool) -> Result<String, String> {
        let mut full = s(&["docker", "exec"]);
        if detach {
            full.push("-d".into());
        }
        full.push(name.to_string());
        full.extend(argv.iter().cloned());
        self.docker(&full)
    }

    fn stop(&self, name: &str) -> Result<(), String> {
        match self.info()? {
            Some(i) if Self::running(&i) => {}
            _ => return Ok(()),
        }
        match self.docker(&crate::up::docker_rm_argv(name)) {
            Ok(_) => Ok(()),
            Err(e) if e.contains("No such container") || e.contains("no such container") => Ok(()),
            Err(e) => Err(e),
        }
    }

    fn limits(&self, name: &str) -> Result<Limits, String> {
        // Read the workload's own cgroup, from inside, as the Lima backend does.
        super::lxc::parse_cgroup_limits(&self.docker(&s(&[
            "docker",
            "exec",
            name,
            "sh",
            "-c",
            "cat /sys/fs/cgroup/cpu.max /sys/fs/cgroup/memory.max; \
             ls -d /dev/nvidia[0-9]* 2>/dev/null | wc -l",
        ]))?)
    }

    fn health(&self, name: &str) -> Result<State, String> {
        let out = self.docker(&crate::up::docker_state_argv(name))?;
        crate::up::parse_container_state(&out)
            .ok_or_else(|| format!("unexpected docker inspect output: {out:?}"))
    }

    fn allocations(&self) -> Result<Vec<Allocation>, String> {
        match self.info()? {
            Some(i) if Self::running(&i) => {}
            _ => return Ok(Vec::new()),
        }
        let mut argv = vec!["docker".to_string()];
        argv.extend(docker::allocations_args());
        Ok(docker::parse_allocations(&self.docker(&argv)?))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sandbox::Gpus;
    use std::sync::Mutex;

    const MIB: u64 = 1024 * 1024;

    #[derive(Default)]
    struct Rec {
        calls: Mutex<Vec<String>>,
        answer: Mutex<Vec<(&'static str, Result<String, String>)>>,
        config: Mutex<Option<String>>,
    }

    impl Rec {
        fn on(&self, needle: &'static str, a: Result<&str, &str>) {
            self.answer
                .lock()
                .unwrap()
                .push((needle, a.map(String::from).map_err(String::from)));
        }
        fn calls(&self) -> Vec<String> {
            self.calls.lock().unwrap().clone()
        }
        fn with_config(&self, yaml: &str) {
            *self.config.lock().unwrap() = Some(yaml.to_string());
        }
    }

    impl ColimaCli for Rec {
        fn run(&self, argv: &[String]) -> Result<String, String> {
            let j = argv.join(" ");
            self.calls.lock().unwrap().push(j.clone());
            for (needle, a) in self.answer.lock().unwrap().iter() {
                if j.contains(needle) {
                    return a.clone();
                }
            }
            Ok(String::new())
        }
        fn config(&self, _profile: &str) -> Result<Option<String>, String> {
            Ok(self.config.lock().unwrap().clone())
        }
    }

    fn size() -> SandboxSize {
        SandboxSize {
            limits: Limits::new(1.5, 2.0, Gpus::None),
            disk_bytes: 10 * 1024 * MIB,
        }
    }

    fn host() -> Host {
        Host {
            macos: true,
            apple_silicon: true,
            home: Some("/Users/jo".into()),
            work_dir: Some("/Users/jo/.zakuro".into()),
        }
    }

    fn rt(rec: &Arc<Rec>) -> ColimaRuntime {
        ColimaRuntime::new(rec.clone(), PROFILE, Ok(size()), host()).with_mkdir(|_| Ok(()))
    }

    fn spec() -> StartSpec {
        StartSpec {
            name: "zc-share-w0".into(),
            image: "img".into(),
            network: None,
            create_network: false,
            labels: vec![],
            mounts: vec![("/Users/jo/.zakuro/work".into(), "/work".into())],
            publish: vec![],
            env: vec![],
            cmd: vec![],
            limits: Limits::new(0.5, 1.0, Gpus::None),
            remove_on_exit: true,
            hardened: false,
        }
    }

    fn list_line(status: &str, cpus: u32, mem_gib: u64, disk_gib: u64) -> String {
        format!(
            r#"{{"name":"zakuro","status":"{status}","arch":"aarch64","cpus":{cpus},"memory":{},"disk":{},"runtime":"docker"}}"#,
            mem_gib * 1024 * MIB,
            disk_gib * 1024 * MIB
        )
    }

    const GOOD_YAML: &str = "cpu: 2\nmounts:\n  - location: /Users/jo/.zakuro\n    mountPoint: /Users/jo/.zakuro\n    writable: true\ndiskImage: \"\"\n";

    #[test]
    fn a_new_profile_is_started_with_the_budget_and_only_the_work_dir() {
        assert_eq!(
            start_argv(PROFILE, &size(), &host(), false, true).join(" "),
            "colima start -p zakuro --runtime docker --vm-type vz --vz-rosetta \
             --activate=false --ssh-config=false --mount /Users/jo/.zakuro:w \
             -c 2 -m 2 -d 10"
        );
        // A restart names the profile and the new size only.
        assert_eq!(
            start_argv(PROFILE, &size(), &host(), false, false).join(" "),
            "colima start -p zakuro -c 2 -m 2"
        );
        assert!(start_argv(PROFILE, &size(), &host(), true, false)
            .join(" ")
            .ends_with("-d 10"));
    }

    #[test]
    fn every_command_names_the_zakuro_profile() {
        let d = Arc::new(Rec::default());
        d.on("list --json", Ok(&list_line("Running", 4, 8, 10)));
        d.on("ps -q", Ok(""));
        d.with_config(GOOD_YAML);
        let r = rt(&d);
        r.ensure().unwrap();
        let _ = r.start(&spec());
        let _ = r.stop("w");
        for c in d.calls() {
            if c.contains("list --json") || c.starts_with("colima version") {
                continue;
            }
            assert!(c.contains("-p zakuro"), "{c}");
            assert!(!c.contains("-p default"), "{c}");
        }
    }

    #[test]
    fn the_default_profile_is_never_used() {
        let d = Arc::new(Rec::default());
        let r = ColimaRuntime::new(d.clone(), "default", Ok(size()), host());
        assert!(r.ensure().unwrap_err().contains("never uses one the owner"));
        assert!(!r.probe().available);
        assert!(d.calls().iter().all(|c| !c.contains("start")));
    }

    #[test]
    fn a_missing_profile_is_created_then_firewalled() {
        let d = Arc::new(Rec::default());
        rt(&d).ensure().unwrap();
        let calls = d.calls();
        assert_eq!(calls[0], "colima list --json");
        assert!(calls[1].starts_with("colima start -p zakuro --runtime docker"));
        assert!(calls[2].starts_with("colima ssh -p zakuro -- sudo sh -c set -e;"));
        assert!(calls[2].contains("DOCKER-USER"), "{}", calls[2]);
        assert_eq!(calls[3], "colima ssh -p zakuro -- docker version");
    }

    #[test]
    fn a_matching_profile_is_adopted_untouched_and_a_changed_budget_resizes_when_idle() {
        let d = Arc::new(Rec::default());
        d.on("list --json", Ok(&list_line("Running", 2, 2, 10)));
        d.with_config(GOOD_YAML);
        rt(&d).ensure().unwrap();
        assert!(!d
            .calls()
            .iter()
            .any(|c| c.contains("colima start") || c.contains("colima stop")));

        let d = Arc::new(Rec::default());
        d.on("list --json", Ok(&list_line("Running", 4, 8, 10)));
        d.on("ps -q", Ok(""));
        d.with_config(GOOD_YAML);
        rt(&d).ensure().unwrap();
        let calls = d.calls();
        let at = |p: &str| calls.iter().position(|c| c.starts_with(p)).unwrap();
        assert!(at("colima stop -p zakuro") < at("colima start -p zakuro -c 2 -m 2"));

        let d = Arc::new(Rec::default());
        d.on("list --json", Ok(&list_line("Stopped", 1, 1, 5)));
        d.with_config(GOOD_YAML);
        rt(&d).ensure().unwrap();
        assert!(d
            .calls()
            .contains(&"colima start -p zakuro -c 2 -m 2 -d 10".to_string()));
    }

    #[test]
    fn a_busy_profile_is_not_resized() {
        let d = Arc::new(Rec::default());
        d.on("list --json", Ok(&list_line("Running", 4, 8, 10)));
        d.on("ps -q", Ok("abc"));
        d.with_config(GOOD_YAML);
        let r = rt(&d);
        r.ensure().unwrap();
        assert!(!d.calls().iter().any(|c| c.contains("colima stop")));
        assert!(r.resize_pending().unwrap());
    }

    #[test]
    fn a_profile_with_the_home_mounted_is_refused() {
        let writable_home = "mounts:\n  - location: /Users/jo\n    writable: true\n";
        let defaults = "mounts: []\n";
        for (yaml, why) in [(writable_home, "writable"), (defaults, "default mounts")] {
            let d = Arc::new(Rec::default());
            d.on("list --json", Ok(&list_line("Running", 2, 2, 10)));
            d.with_config(yaml);
            let e = rt(&d).ensure().unwrap_err();
            assert!(e.contains("owner's home"), "{why}: {e}");
            assert!(!rt(&d).probe().available);
            assert!(!d.calls().iter().any(|c| c.contains("ssh")));
        }
        // Even before the first start: a leftover config with defaults.
        let d = Arc::new(Rec::default());
        d.with_config(defaults);
        assert!(rt(&d).ensure().is_err());
    }

    #[test]
    fn colima_yaml_mounts_are_read() {
        assert_eq!(
            parse_mounts(GOOD_YAML),
            Some(vec![("/Users/jo/.zakuro".to_string(), true)])
        );
        assert_eq!(parse_mounts("mounts: []\nx: 1\n"), None);
        assert_eq!(parse_mounts("cpu: 2\n"), None);
        let q = "mounts:\n  - location: \"/a b\"\n    writable: false\n  - location: '/c'\n    writable: true\nnext: 1\n  - location: /no\n";
        assert_eq!(
            parse_mounts(q),
            Some(vec![("/a b".to_string(), false), ("/c".to_string(), true)])
        );
    }

    #[test]
    fn a_gpu_is_refused_and_workloads_run_through_the_profiles_docker() {
        let d = Arc::new(Rec::default());
        let mut sp = spec();
        sp.limits = Limits::new(0.5, 1.0, Gpus::Count(1));
        assert!(rt(&d)
            .start(&sp)
            .unwrap_err()
            .contains("no GPU passthrough"));
        assert!(d.calls().is_empty());

        let d = Arc::new(Rec::default());
        d.on("list --json", Ok(&list_line("Running", 2, 2, 10)));
        d.on("docker run", Ok("cid"));
        d.with_config(GOOD_YAML);
        assert_eq!(rt(&d).start(&spec()).unwrap(), "cid");
        let run = d
            .calls()
            .into_iter()
            .find(|c| c.contains("docker run"))
            .unwrap();
        assert!(
            run.starts_with("colima ssh -p zakuro -- docker run --rm -d --name zc-share-w0"),
            "{run}"
        );
        assert!(run.contains("--cpus 0.5 --memory 1024m"), "{run}");
        assert!(run.contains("-v /Users/jo/.zakuro/work:/work"), "{run}");

        let mut sp = spec();
        sp.mounts = vec![("/Users/jo".into(), "/h".into())];
        assert!(rt(&Arc::new(Rec::default()))
            .start(&sp)
            .unwrap_err()
            .contains("outside the zakuro work directory"));
    }

    #[test]
    fn limits_stop_health_and_allocations() {
        let d = Arc::new(Rec::default());
        d.on("exec zc-share-w0 sh -c", Ok("50000 100000\n1073741824\n0"));
        let l = rt(&d).limits("zc-share-w0").unwrap();
        assert_eq!((l.cpu_millis, l.memory_bytes), (500, 1073741824));

        let d = Arc::new(Rec::default());
        d.on("list --json", Ok(&list_line("Stopped", 2, 2, 10)));
        rt(&d).stop("w").unwrap();
        assert!(rt(&d).allocations().unwrap().is_empty());
        assert!(!d.calls().iter().any(|c| c.contains("ssh")));

        let d = Arc::new(Rec::default());
        d.on("list --json", Ok(&list_line("Running", 2, 2, 10)));
        d.on(
            "rm -f",
            Err("Error response from daemon: No such container: w"),
        );
        rt(&d).stop("w").unwrap();
        d.on("docker ps --filter", Ok("w|500m,1073741824"));
        assert_eq!(rt(&d).allocations().unwrap().len(), 1);

        let d = Arc::new(Rec::default());
        d.on("inspect -f", Ok("true|2026-01-01T00:00:00Z|0"));
        assert!(rt(&d).health("w").is_ok());
    }

    #[test]
    fn verify_image_checks_the_exact_digest() {
        let d = Arc::new(Rec::default());
        d.on("image inspect", Ok(r#"sha256:aaa|["img@sha256:bbb"]"#));
        let r = rt(&d);
        assert!(r.verify_image("img", Some("img@sha256:bbb")).is_ok());
        assert!(r
            .verify_image("img", Some("sha256:ccc"))
            .unwrap_err()
            .contains("does not match"));
    }

    #[test]
    fn the_probe_says_why() {
        let d = Arc::new(Rec::default());
        d.on("version", Err("colima is not installed (No such file)"));
        let p = rt(&d).probe();
        assert!(
            !p.available && p.detail.contains("brew install colima"),
            "{}",
            p.detail
        );

        let d = Arc::new(Rec::default());
        d.on("version", Ok("colima version 0.5.0\ngit commit: x"));
        assert!(rt(&d).probe().detail.contains("too old"));

        let mut h = host();
        h.macos = false;
        let r = ColimaRuntime::new(Arc::new(Rec::default()), PROFILE, Ok(size()), h);
        assert_eq!(r.probe().detail, "macOS only");

        let d = Arc::new(Rec::default());
        d.on("version", Ok("colima version 0.10.3\ngit commit: 00f6"));
        let p = rt(&d).probe();
        assert!(
            p.available && p.detail.contains("not created yet"),
            "{}",
            p.detail
        );
        d.on("list --json", Ok(&list_line("Running", 2, 2, 10)));
        d.with_config(GOOD_YAML);
        assert!(rt(&d)
            .probe()
            .detail
            .contains("running (2 cpu, 2.0 GiB memory)"));
    }

    /// Deletes the throwaway profile, on success or failure.
    struct Cleanup(String);
    impl Drop for Cleanup {
        fn drop(&mut self) {
            let bin = resolve_binary(
                "colima",
                "ZAKURO_COLIMA",
                &|k| std::env::var(k).ok(),
                &|p| p.is_file(),
            );
            let _ = std::process::Command::new(bin)
                .args(["delete", "-f", "-p", &self.0])
                .output();
            eprintln!("[real-colima] deleted profile {}", self.0);
        }
    }

    /// The real thing on this Mac: a throwaway 2 cpu / 2 GiB / 10 GiB vz
    /// profile, a tiny container with limits, the limits read back, the
    /// guest egress rules, then the profile deleted. `ZAKURO_TEST_REAL_COLIMA=1`
    /// and `--ignored`; never touches `zakuro` or `default`.
    #[test]
    #[ignore]
    fn real_colima_profile_runs_a_limited_container_and_blocks_the_host() {
        if std::env::var("ZAKURO_TEST_REAL_COLIMA").as_deref() != Ok("1") {
            return;
        }
        let name = format!("zctest-{}", std::process::id());
        assert!(name != "zakuro" && name != "default");
        let cli: Arc<dyn ColimaCli> = Arc::new(ColimaShell::new());
        eprintln!(
            "[real-colima] existing profiles (untouched): {:?}",
            cli.run(&s(&["colima", "list"]))
        );
        let work = std::fs::canonicalize(std::env::temp_dir())
            .unwrap()
            .join(format!("{name}-work"));
        std::fs::create_dir_all(work.join("w")).unwrap();
        let _cleanup = Cleanup(name.clone());
        let mut h = Host::detect();
        h.work_dir = Some(work.clone());
        let size = SandboxSize {
            limits: Limits::new(2.0, 2.0, Gpus::None),
            disk_bytes: 10 * 1024 * MIB,
        };
        let r = ColimaRuntime::new(cli.clone(), &name, Ok(size), h);
        eprintln!("[real-colima] probe before: {:?}", r.probe());
        assert!(r.probe().available);

        let spec = StartSpec {
            name: "zctest-w0".into(),
            image: "alpine:3".into(),
            network: None,
            create_network: false,
            labels: vec![],
            mounts: vec![(work.join("w").display().to_string(), "/work".into())],
            publish: vec![],
            env: vec![],
            cmd: s(&["sleep", "600"]),
            limits: Limits::new(0.5, 0.25, Gpus::None),
            remove_on_exit: false,
            hardened: true,
        };
        let id = r.start(&spec).expect("start");
        eprintln!("[real-colima] started container {id}");
        eprintln!("[real-colima] probe after: {:?}", r.probe());
        let l = r.limits("zctest-w0").expect("limits");
        eprintln!("[real-colima] limits read back from inside: {l}");
        assert_eq!(l.cpu_millis, 500);
        assert_eq!(l.memory_bytes, 256 * MIB);
        assert!(r.health("zctest-w0").unwrap().running);
        assert!(r.verify_image("alpine:3", None).is_ok());
        assert_eq!(r.allocations().unwrap().len(), 1);

        let out = r
            .exec(
                "zctest-w0",
                &s(&["sh", "-c", "echo 'a b'; echo $((1+2)); echo hi > /work/f"]),
                false,
            )
            .unwrap();
        eprintln!("[real-colima] exec output: {out:?}");
        assert_eq!(out, "a b\n3");
        assert_eq!(
            std::fs::read_to_string(work.join("w/f")).unwrap().trim(),
            "hi"
        );

        let l = std::net::TcpListener::bind("0.0.0.0:0").unwrap();
        let port = l.local_addr().unwrap().port().to_string();
        let guest = |cmd: &str| cli.run(&s(&["colima", "ssh", "-p", &name, "--", "sh", "-c", cmd]));
        let gw = guest("getent hosts host.lima.internal | cut -d' ' -f1").unwrap();
        eprintln!("[real-colima] host gateway in the guest: {gw}");
        let base = guest(&format!(
            "timeout 3 bash -c 'echo > /dev/tcp/{gw}/{port}' && echo reachable"
        ));
        eprintln!("[real-colima] guest -> mac listener (baseline): {base:?}");
        let probe = |cmd: &str| r.exec("zctest-w0", &s(&["sh", "-c", cmd]), false);
        let ctr = probe(&format!(
            "nc -z -w 3 {gw} {port} && echo reachable || echo blocked"
        ));
        eprintln!("[real-colima] container -> mac listener: {ctr:?}");
        let net = probe("nc -z -w 5 1.1.1.1 443 && echo internet-ok || echo internet-blocked");
        eprintln!("[real-colima] container -> 1.1.1.1:443: {net:?}");
        let dns = probe("nslookup example.com >/dev/null 2>&1 && echo dns-ok || echo dns-failed");
        eprintln!("[real-colima] container dns: {dns:?}");
        drop(l);
        assert_eq!(
            base.as_deref(),
            Ok("reachable"),
            "baseline: guest must reach the Mac"
        );
        assert_eq!(ctr.as_deref(), Ok("blocked"));
        assert_eq!(net.as_deref(), Ok("internet-ok"));
        assert_eq!(dns.as_deref(), Ok("dns-ok"));

        r.stop("zctest-w0").unwrap();
        assert!(r.health("zctest-w0").is_err());
        eprintln!(
            "[real-colima] stopped; allocations now {:?}",
            r.allocations().unwrap()
        );
    }
}