zc2 0.0.50

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
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
//! `ContainerRuntime`: the reconciler's only door to Docker, so
//! `reconcile::drive` can be driven in tests by a fake instead of the real
//! CLI. `DockerCli` shells out the same way `mesh.rs`'s `docker()` helper
//! does (Command::new("docker") + captured stdout/stderr), extended with the
//! handful of subcommands a reconciler needs that a static local mesh never
//! did: pull, per-container run/stop/rm, health inspection, and label-based
//! listing.
//!
//! Networking (post-drill fix): the broker driving this reconciler is
//! usually ITSELF a container (mounted `/var/run/docker.sock`, talking to
//! the HOST's daemon) — a live drill against the dev stack found that
//! publishing container ports to the docker HOST's `127.0.0.1` (the
//! original design) is unreachable from the broker's own network namespace;
//! only a host-native `zc` shares that namespace. So `run` no longer
//! publishes any ports at all — it joins `ZAKURO_DEPLOY_NETWORK` (or
//! `bridge`) instead, and `container_ip` resolves the environment's own
//! address on that network, which any container on the same network
//! (including this one, once it's also joined to it) can reach directly.
//!
//! Except on Docker Desktop (macOS, Windows): the daemon and its networks
//! live in a VM, so a host-native broker has no route to any container IP
//! (zc#485 — probes to `172.17.0.x` time out or are refused by whatever the
//! default gateway is). There `run` also publishes every port on the host's
//! `127.0.0.1` (ephemeral host port), and `container_addr` answers that
//! mapping instead. See [`publish_loopback`].

use std::collections::HashMap;
use std::process::Command;
use std::time::Duration;

use super::{Healthcheck, Port};

/// Everything needed to `docker run` one deployment version.
pub struct RunSpec<'a> {
    pub name: String,
    pub image: &'a str,
    pub cmd: Option<&'a str>,
    pub ports: &'a [Port],
    pub env: &'a HashMap<String, String>,
    /// `(key, value)` pairs applied as `--label key=value`.
    pub labels: Vec<(String, String)>,
    /// `(host_path, container_path)` pairs applied as `-v host:container`.
    pub mounts: Vec<(String, String)>,
    /// `--cpus` / `--memory` / `--gpus`: always set (zc#510). Derived from
    /// the node budget ([`ContainerRuntime::budget`], clamped by
    /// [`crate::sandbox::Limits::clamp_request`]), so a
    /// workload that asked for nothing still runs capped at the budget.
    pub limits: crate::sandbox::Limits,
    /// `--network`; `None` joins [`deploy_network`].
    pub network: Option<String>,
    /// Untrusted workload: add `--pids-limit 4096` and
    /// `--security-opt no-new-privileges`.
    pub hardened: bool,
}

/// The `docker run` argument vector for `spec` (everything up to and
/// including the optional command). Pure so the flag mapping is unit-tested
/// without docker. `default_network` is used when `spec.network` is `None`.
pub fn build_run_args(spec: &RunSpec, default_network: &str) -> Vec<String> {
    let network = spec
        .network
        .clone()
        .unwrap_or_else(|| default_network.to_string());
    // Sorted so the argv is deterministic (the env is a HashMap).
    let mut env: Vec<(String, String)> = spec
        .env
        .iter()
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect();
    env.sort();
    // No `-p`/port publishing here: see this module's doc comment -- the
    // broker reaches the environment by its own network IP
    // (`container_ip`), not a host-published port, because the broker
    // driving this is usually itself a container with its own netns.
    // Docker Desktop's loopback publish is spliced in by `run`.
    crate::sandbox::docker::run_argv(&crate::sandbox::StartSpec {
        name: spec.name.clone(),
        image: spec.image.to_string(),
        network: Some(network),
        create_network: false,
        labels: spec.labels.clone(),
        mounts: spec.mounts.clone(),
        publish: Vec::new(),
        env,
        // Split on whitespace: these commands come from the hub's
        // deployment config (`cmd: "python -m http.server 8000"`), not
        // arbitrary shell -- no quoting/escaping semantics to preserve.
        cmd: spec
            .cmd
            .map(|c| c.split_whitespace().map(str::to_string).collect())
            .unwrap_or_default(),
        limits: spec.limits.clone(),
        remove_on_exit: false,
        hardened: spec.hardened,
    })
}

/// The docker network new environment containers join. `ZAKURO_DEPLOY_NETWORK`
/// when set and non-blank (e.g. `hubnet`, so the broker and every environment
/// it starts share a network the broker itself was also joined to at deploy
/// time), else docker's own default `bridge`.
pub fn deploy_network() -> String {
    std::env::var("ZAKURO_DEPLOY_NETWORK")
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "bridge".to_string())
}

/// Whether environment containers also publish their ports on the host's
/// loopback, and the broker dials those instead of the container IP.
/// `ZAKURO_DEPLOY_PUBLISH_LOOPBACK` (`1`/`true` or `0`/`false`) when set and
/// non-blank, else on for a macOS or Windows build: that broker is host-native
/// and talks to Docker Desktop, whose container IPs it cannot route to.
pub fn publish_loopback() -> bool {
    publish_loopback_from(
        std::env::var("ZAKURO_DEPLOY_PUBLISH_LOOPBACK")
            .ok()
            .as_deref(),
        cfg!(any(target_os = "macos", target_os = "windows")),
    )
}

/// [`publish_loopback`] without the environment, so it is unit-tested.
fn publish_loopback_from(var: Option<&str>, os_default: bool) -> bool {
    match var.map(|v| v.trim().to_ascii_lowercase()).as_deref() {
        Some("1") | Some("true") => true,
        Some("0") | Some("false") => false,
        _ => os_default,
    }
}

/// `-p 127.0.0.1::<port>` per distinct container port: an ephemeral host
/// port bound on loopback only, never on the LAN.
fn loopback_publish_args(ports: &[u16], bind: &str) -> Vec<String> {
    let mut seen = Vec::new();
    let mut args = Vec::new();
    for &p in ports {
        if seen.contains(&p) {
            continue;
        }
        seen.push(p);
        args.push("-p".to_string());
        args.push(format!("{bind}::{p}"));
    }
    args
}

/// Insert [`loopback_publish_args`] for `spec.ports` into `args` (from
/// [`build_run_args`]) just before the image, where `docker run` flags end.
/// `sandbox`: bind on the sandbox's own interfaces (the host reaches its
/// bridge address), not its loopback.
fn add_loopback_publish(args: &mut Vec<String>, spec: &RunSpec, sandbox: bool) {
    let ports: Vec<u16> = spec.ports.iter().map(|p| p.container).collect();
    let at = args.len() - spec.cmd.map_or(0, |c| c.split_whitespace().count()) - 1;
    let bind = if sandbox { "0.0.0.0" } else { "127.0.0.1" };
    args.splice(at..at, loopback_publish_args(&ports, bind));
}

/// The dialable address in `docker port <id> <port>/tcp` output, one
/// `host:port` per line. Prefers an IPv4 mapping; a wildcard bind is dialled
/// on loopback.
fn parse_published_port(out: &str) -> Option<(String, u16)> {
    let parsed: Vec<std::net::SocketAddr> =
        out.lines().filter_map(|l| l.trim().parse().ok()).collect();
    let addr = parsed
        .iter()
        .find(|a| a.is_ipv4())
        .or_else(|| parsed.first())?;
    let host = if addr.ip().is_unspecified() {
        "127.0.0.1".to_string()
    } else {
        addr.ip().to_string()
    };
    Some((host, addr.port()))
}

/// The `--internal` docker network a policy-isolated environment joins (no
/// route to the mesh or the internet). `ZAKURO_DEPLOY_ISOLATED_NETWORK` when
/// set and non-blank, else `zc-isolated`. A containerised broker must itself
/// be attached to it to reach (health-check / proxy) these environments.
pub fn isolated_network() -> String {
    std::env::var("ZAKURO_DEPLOY_ISOLATED_NETWORK")
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "zc-isolated".to_string())
}

/// Abstraction over "a place that can run OCI containers", so the reconciler
/// logic in `reconcile::drive` is testable without Docker installed and
/// without touching the network.
pub trait ContainerRuntime {
    /// Whether this runtime is usable at all on this host (e.g. `docker`
    /// resolves on PATH and the daemon answers). Checked once per tick;
    /// `deploy::tick` reports every running-desired deployment `failed` and
    /// does nothing else when this is `false`.
    fn available(&self) -> bool;
    fn pull(&self, image: &str) -> Result<(), String>;
    /// Starts a fresh container per `spec`, returning its id. Idempotent
    /// w.r.t. the container *name*: a stale container from a crashed prior
    /// attempt with the same name is removed first, since docker refuses to
    /// reuse a name that's still allocated. Joins `deploy_network()` — no
    /// port publishing (see this module's doc comment).
    fn run(&self, spec: &RunSpec) -> Result<String, String>;
    /// Start a FOREIGN job's container (a Space lease): in its own ephemeral
    /// instance (T2, zc#578) where the backend has one, else like [`run`].
    /// The image is pulled here, inside the boundary, with the docker config
    /// in `pull_config` (a dir [`login_in`] wrote) when there is one. The id
    /// it returns routes every later call to the right boundary.
    ///
    /// [`run`]: ContainerRuntime::run
    /// [`login_in`]: ContainerRuntime::login_in
    fn run_leased(
        &self,
        spec: &RunSpec,
        _pull_config: Option<&std::path::Path>,
    ) -> Result<String, String> {
        self.run(spec)
    }
    fn stop(&self, container_id: &str) -> Result<(), String>;
    fn rm(&self, container_id: &str) -> Result<(), String>;
    /// `docker start` on an already-created (but currently stopped)
    /// container — used to bring a rollback's surviving previous container
    /// back up if it isn't running for some unrelated reason.
    fn restart(&self, container_id: &str) -> Result<(), String>;
    fn is_running(&self, container_id: &str) -> bool;
    /// The container's own IP address on its docker network (first
    /// non-empty entry across `NetworkSettings.Networks`) — the address the
    /// broker actually proxies/health-checks against, NOT a host-published
    /// port (see this module's doc comment for why). A real implementation
    /// retries a few times: docker assigns this address a moment after
    /// `run` returns, not synchronously with it. `Err`/empty when the
    /// container has no network IP at all (e.g. `--network host`), which
    /// callers fall back on treating as "reachable on this host's own
    /// loopback" — the container isn't on its own network in that mode.
    fn container_ip(&self, container_id: &str) -> Result<String, String>;
    /// Where the broker dials the container's own `port`: `(container_ip,
    /// port)`, or the published loopback mapping on a Docker Desktop host
    /// (see this module's doc comment). The default suits any runtime whose
    /// container IPs are routable.
    fn container_addr(&self, container_id: &str, port: u16) -> Result<(String, u16), String> {
        self.container_ip(container_id).map(|ip| (ip, port))
    }
    /// One readiness probe against `container_id` per `hc` (TCP connect, or
    /// an HTTP GET expecting 2xx — see `health_http_url`). Split out as its
    /// own trait method, rather than composed from `container_ip` + a raw
    /// socket/HTTP call inline in `reconcile::wait_healthy`, specifically so
    /// a fake runtime in tests can answer it directly instead of needing a
    /// real container or a real socket to poll.
    fn health_check(&self, container_id: &str, hc: &Healthcheck) -> bool;
    /// Like `health_check`, but says WHY a probe failed, as one line such as
    /// `GET http://172.17.0.3:8888/api → connection refused` or `→ HTTP 503`.
    /// This is what `reconcile::wait_healthy` calls. The default wraps
    /// `health_check` (no detail), so runtimes that only know pass/fail keep
    /// working.
    fn health_probe(&self, container_id: &str, hc: &Healthcheck) -> Result<(), String> {
        if self.health_check(container_id, hc) {
            Ok(())
        } else {
            Err("health check failed".to_string())
        }
    }
    /// Last `lines` lines of the container's logs, stdout and stderr merged
    /// (Jupyter and most servers log to stderr), best-effort (empty string
    /// on any failure) — used to give the hub something more useful than
    /// "exited" in a `failed` status report.
    fn logs_tail(&self, container_id: &str, lines: u32) -> String;
    /// Container ids currently labelled `zakuro.deployment=<id>` (any
    /// version), for reconciling local state against reality after a broker
    /// restart.
    fn list_by_label(&self, id: &str) -> Vec<String>;
    /// Container ids carrying the label key `key` (any value).
    fn list_by_label_key(&self, _key: &str) -> Vec<String> {
        Vec::new()
    }
    /// `login` with a private docker config dir (never touches the host's
    /// `~/.docker/config.json`). Defaults to plain `login`.
    fn login_in(
        &self,
        _config_dir: &std::path::Path,
        registry: &str,
        username: &str,
        password: &str,
    ) -> Result<(), String> {
        self.login(registry, username, password)
    }
    /// `pull` using the same private docker config dir.
    fn pull_in(&self, _config_dir: &std::path::Path, image: &str) -> Result<(), String> {
        self.pull(image)
    }
    /// `docker login` to `registry` (credentials via stdin). Default no-op for
    /// runtimes that need none.
    fn login(&self, _registry: &str, _username: &str, _password: &str) -> Result<(), String> {
        Ok(())
    }
    /// The image digest(s) the running container was created from, as
    /// comma-separated `sha256:<hex>` values (every RepoDigest of its image,
    /// else the image id). Callers compare against a pinned digest.
    fn image_digest(&self, _container_id: &str) -> Result<String, String> {
        Err("image_digest not supported by this runtime".to_string())
    }
    /// This node's budget as one [`crate::sandbox::Limits`] (zc#510), which
    /// every environment and Space container is clamped to. The node's own
    /// (`sandbox::node_limits`) unless a test fake pins it. `Err` (an
    /// invalid budget) fails the start; it never runs unlimited.
    fn budget(&self) -> Result<crate::sandbox::Limits, String> {
        crate::sandbox::node_limits()
    }
    /// Whether the node's sharing policy lets this guest deployment run here
    /// (ZC-0017 §5, zc#514): squad, the Environments switch, price floor and
    /// schedule. Default: yes (test fakes); the Docker runtime asks the policy.
    fn admit_guest(&self, _d: &super::Desired) -> Result<(), crate::policy::admit::Refusal> {
        Ok(())
    }
    /// Every running container's share of the node budget (zc#565): share
    /// workers, deployments and Space leases alike, read from the daemon by
    /// [`crate::sandbox::BUDGET_LABEL`]. Default: nothing runs (test fakes).
    fn allocations(&self) -> Result<Vec<crate::sandbox::Allocation>, String> {
        Ok(Vec::new())
    }
}

/// The container name this reconciler gives a deployment version. Unique per
/// (deployment, version) so a version bump never collides with the container
/// it's replacing while both are briefly alive during the health check.
pub fn container_name(id: &str, version: u64) -> String {
    format!("zk-dep-{id}-v{version}")
}

/// Labels stamped on every container this reconciler creates, so
/// `list_by_label`/`docker ps --filter` can find them again.
pub fn deployment_labels(id: &str, version: u64) -> Vec<(String, String)> {
    vec![
        ("zakuro.deployment".to_string(), id.to_string()),
        ("zakuro.version".to_string(), version.to_string()),
    ]
}

/// The URL an `"http"` healthcheck (or the `/serve` proxy) targets on the
/// container's own address. Split out from `DockerCli::health_check` so the
/// path-joining logic (default `"/"`, tolerate a path with or without a
/// leading slash) is unit-testable without a real container or socket.
/// `host` is a bare IP or hostname — no scheme, no port.
pub fn health_http_url(host: &str, port: u16, hc: &Healthcheck) -> String {
    let path = hc.path.as_deref().unwrap_or("/");
    let path = if path.starts_with('/') {
        path.to_string()
    } else {
        format!("/{path}")
    };
    format!("http://{host}:{port}{path}")
}

/// `docker` CLI-backed `ContainerRuntime`.
pub struct DockerCli;

/// Why the container runtime is unusable (zc#473). Serialised snake_case so
/// the hub can switch on it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RuntimeError {
    /// The socket the CLI would use does not exist.
    SocketMissing,
    /// The socket exists but this user may not use it (not in `docker` group).
    PermissionDenied,
    /// The CLI is there but the daemon does not answer.
    DaemonDown,
    /// No `docker` binary on PATH.
    NotInstalled,
    /// Anything else; see `detail`.
    Other,
}

/// Structured outcome of the runtime probe: what `deploy_runtime` is derived
/// from, plus the reason when it is false.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct RuntimeProbe {
    pub available: bool,
    /// `"docker"`, `"containerd"` (present but unusable here) or `None`.
    pub runtime: Option<&'static str>,
    pub error: Option<RuntimeError>,
    pub detail: String,
    /// RFC 3339 UTC.
    pub checked_at: String,
}

/// What one `docker version` attempt observed. Injected in tests.
#[derive(Debug, Clone)]
pub enum CliOutcome {
    /// The process could not be started (`NotFound` = binary missing).
    SpawnFailed(std::io::ErrorKind, String),
    /// The process ran; `stderr` is trimmed.
    Exited { success: bool, stderr: String },
    /// The process did not finish within [`PROBE_TIMEOUT`] and was killed
    /// (a daemon that accepts on its socket but never answers).
    TimedOut,
}

/// How long `docker version` may take before the probe calls the daemon down.
pub const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// Run `cmd` for at most `timeout`; kill it past that. Returns the outcome and
/// the captured stdout (empty on spawn failure or timeout).
pub fn run_bounded(cmd: &mut Command, timeout: std::time::Duration) -> (CliOutcome, String) {
    use std::io::Read;
    use std::process::Stdio;
    let mut child = match cmd
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
    {
        Ok(c) => c,
        Err(e) => {
            return (
                CliOutcome::SpawnFailed(e.kind(), e.to_string()),
                String::new(),
            )
        }
    };
    fn drain<R: Read + Send + 'static>(r: Option<R>) -> std::thread::JoinHandle<String> {
        std::thread::spawn(move || {
            let mut buf = Vec::new();
            if let Some(mut r) = r {
                let _ = r.read_to_end(&mut buf);
            }
            String::from_utf8_lossy(&buf).into_owned()
        })
    }
    let out = drain(child.stdout.take());
    let err = drain(child.stderr.take());
    let deadline = std::time::Instant::now() + timeout;
    let status = loop {
        match child.try_wait() {
            Ok(Some(st)) => break Some(st),
            Ok(None) if std::time::Instant::now() >= deadline => {
                let _ = child.kill();
                let _ = child.wait();
                break None;
            }
            Ok(None) => std::thread::sleep(std::time::Duration::from_millis(20)),
            Err(e) => {
                return (
                    CliOutcome::SpawnFailed(e.kind(), e.to_string()),
                    String::new(),
                );
            }
        }
    };
    match status {
        Some(st) => (
            CliOutcome::Exited {
                success: st.success(),
                stderr: err.join().unwrap_or_default().trim().to_string(),
            },
            out.join().unwrap_or_default(),
        ),
        // A grandchild may still hold the pipes open; do not join the readers.
        None => (CliOutcome::TimedOut, String::new()),
    }
}

/// Facts about the host that disambiguate a failed `docker version`.
#[derive(Debug, Clone)]
pub struct HostFacts {
    /// Unix socket the docker CLI would use.
    pub socket_path: String,
    pub socket_exists: bool,
    /// `/run/containerd/containerd.sock` present.
    pub containerd_socket: bool,
}

fn default_socket_path() -> String {
    match std::env::var("DOCKER_HOST") {
        Ok(h) if h.starts_with("unix://") => h["unix://".len()..].to_string(),
        _ => "/var/run/docker.sock".to_string(),
    }
}

fn host_facts() -> HostFacts {
    let socket_path = default_socket_path();
    HostFacts {
        socket_exists: std::path::Path::new(&socket_path).exists(),
        socket_path,
        containerd_socket: std::path::Path::new("/run/containerd/containerd.sock").exists(),
    }
}

/// Pure classification of one probe attempt.
pub fn classify_probe(outcome: CliOutcome, facts: &HostFacts, checked_at: String) -> RuntimeProbe {
    let fail = |runtime, error, detail: String| RuntimeProbe {
        available: false,
        runtime,
        error: Some(error),
        detail,
        checked_at: checked_at.clone(),
    };
    match outcome {
        CliOutcome::Exited { success: true, .. } => RuntimeProbe {
            available: true,
            runtime: Some("docker"),
            error: None,
            detail: "docker daemon responding".into(),
            checked_at,
        },
        CliOutcome::TimedOut => fail(
            Some("docker"),
            RuntimeError::DaemonDown,
            format!(
                "docker version did not answer within {} s",
                PROBE_TIMEOUT.as_secs()
            ),
        ),
        CliOutcome::SpawnFailed(kind, msg) => {
            if kind == std::io::ErrorKind::NotFound {
                let (rt, extra) = if facts.containerd_socket {
                    (
                        Some("containerd"),
                        " (containerd is present, but zc deploys through docker)",
                    )
                } else {
                    (None, "")
                };
                fail(
                    rt,
                    RuntimeError::NotInstalled,
                    format!("`docker` binary not found on PATH{extra}"),
                )
            } else {
                fail(
                    None,
                    RuntimeError::Other,
                    format!("could not run `docker`: {msg}"),
                )
            }
        }
        CliOutcome::Exited { stderr, .. } => {
            let low = stderr.to_lowercase();
            let sock = &facts.socket_path;
            if low.contains("permission denied") {
                fail(
                    Some("docker"),
                    RuntimeError::PermissionDenied,
                    format!("permission denied on {sock}"),
                )
            } else if !facts.socket_exists || low.contains("no such file or directory") {
                fail(
                    None,
                    RuntimeError::SocketMissing,
                    format!("docker socket {sock} does not exist"),
                )
            } else if low.contains("cannot connect")
                || low.contains("daemon running")
                || low.contains("connection refused")
            {
                fail(
                    Some("docker"),
                    RuntimeError::DaemonDown,
                    format!("docker daemon is not responding on {sock}"),
                )
            } else {
                let first = stderr.lines().next().unwrap_or("docker version failed");
                fail(
                    Some("docker"),
                    RuntimeError::Other,
                    format!("docker version failed: {first}"),
                )
            }
        }
    }
}

impl RuntimeProbe {
    /// Operator-facing next step for the failure, `None` when available.
    pub fn next_step(&self) -> Option<String> {
        Some(match self.error? {
            RuntimeError::PermissionDenied => {
                "add the zc service user to the docker group (usermod -aG docker <user>) and restart zc".into()
            }
            RuntimeError::SocketMissing => "start the docker service (systemctl enable --now docker) or set DOCKER_HOST".into(),
            RuntimeError::DaemonDown => "start the docker daemon (systemctl start docker)".into(),
            RuntimeError::NotInstalled => "install docker on this host".into(),
            RuntimeError::Other => "run `zc doctor` on this host for details".into(),
        })
    }

    /// Message for a rollout `failed` status.
    pub fn failure_message(&self) -> String {
        match self.next_step() {
            None => "container runtime available".into(),
            Some(step) => format!(
                "no container runtime on this host: {} — {step}",
                self.detail
            ),
        }
    }

    /// `deploy_runtime_detail` register payload object.
    pub fn to_json(&self) -> serde_json::Value {
        serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
    }
}

/// Human-readable `zc doctor` output for a probe.
pub fn doctor_report(p: &RuntimeProbe) -> String {
    let mut out = format!(
        "container runtime: {}\n  runtime:    {}\n  detail:     {}\n  checked_at: {}",
        if p.available { "OK" } else { "UNAVAILABLE" },
        p.runtime.unwrap_or("none"),
        p.detail,
        p.checked_at
    );
    if let Some(e) = p.error {
        out.push_str(&format!(
            "\n  error:      {}",
            serde_json::to_value(e)
                .ok()
                .and_then(|v| v.as_str().map(String::from))
                .unwrap_or_default()
        ));
    }
    if let Some(step) = p.next_step() {
        out.push_str(&format!("\n  next step:  {step}"));
    }
    out
}

/// Probe this host's container runtime now (one `docker version`).
///
/// Not `docker info`: that also runs every CLI plugin's
/// `docker-cli-plugin-metadata` (Docker Desktop ships ~15), and under a
/// macOS LaunchAgent those spawns are throttled past [`PROBE_TIMEOUT`], so a
/// running daemon was reported down and the reconciler skipped every pass
/// (deployments never stopped). `docker version` loads no plugins and still
/// fails the same way when the daemon cannot be reached.
pub fn runtime_probe() -> RuntimeProbe {
    let (outcome, _) = run_bounded(
        Command::new("docker").args(["version", "--format", "{{.Server.Version}}"]),
        PROBE_TIMEOUT,
    );
    classify_probe(outcome, &host_facts(), chrono::Utc::now().to_rfc3339())
}

/// Whether THIS host can run containers at all. See [`runtime_probe`] for the
/// reason behind a `false`. One `docker version` per call: keep it on the ~60s
/// node-sync cadence.
pub fn runtime_available() -> bool {
    runtime_probe().available
}

/// Run `docker <args>` on the active backend (`docker`, or nerdctl in the
/// sandbox; see [`crate::sandbox::engine`]), returning trimmed stdout or the
/// trimmed stderr as an error. Same shape as `mesh.rs::docker()`, kept separate
/// rather than shared: `mesh.rs` is the local static-mesh bring-up path, this
/// is the hub-driven reconciler, and coupling them would make either harder to
/// change independently.
fn docker(args: &[&str]) -> Result<String, String> {
    crate::sandbox::engine::run(args)
}

/// Where a container lives: on the active backend, or inside a per-job
/// instance (T2, the id says so).
enum Where<'a> {
    Engine,
    Job(&'a str),
}

/// Split a container id into where it runs and its name there.
fn locate(id: &str) -> (Where<'_>, &str) {
    match crate::sandbox::ephemeral::parse_job_id(id) {
        Some((inst, name)) => (Where::Job(inst), name),
        None => (Where::Engine, id),
    }
}

/// The per-job instance manager (sized once from the environment).
fn ephemeral() -> &'static crate::sandbox::ephemeral::Ephemeral {
    crate::sandbox::engine::ephemeral()
}

/// `docker <args>` where `w` is: the backend, or nerdctl inside a job's instance.
fn docker_at(w: &Where, args: &[&str]) -> Result<String, String> {
    match w {
        Where::Engine => docker(args),
        Where::Job(inst) => {
            use crate::sandbox::lxc::IncusCli as _;
            let argv: Vec<String> = args.iter().map(|a| a.to_string()).collect();
            crate::sandbox::lxc::IncusShell.run(&crate::sandbox::ephemeral::Ephemeral::exec_argv(
                inst, &argv,
            ))
        }
    }
}

/// `docker logs --tail N`, stdout and stderr merged (stdout first). `docker()`
/// returns stdout only, which is empty for anything that logs to stderr.
/// Best-effort: empty string on any failure.
fn docker_logs(container_id: &str, lines: u32) -> String {
    let (w, name) = locate(container_id);
    let n = lines.to_string();
    let args = ["logs", "--tail", n.as_str(), name];
    let argv: Vec<String> = args.iter().map(|a| a.to_string()).collect();
    let cmd = match w {
        Where::Engine => crate::sandbox::engine::command(&argv).ok(),
        Where::Job(inst) => {
            let full = crate::sandbox::ephemeral::Ephemeral::exec_argv(inst, &argv);
            let mut c = Command::new(crate::sandbox::lxc::cli_binary());
            c.args(&full[1..]);
            Some(c)
        }
    };
    let Some(Ok(out)) = cmd.map(|mut c| c.output()) else {
        return String::new();
    };
    merge_logs(&out.stdout, &out.stderr)
}

/// Join a container's captured stdout and stderr into one tail.
fn merge_logs(stdout: &[u8], stderr: &[u8]) -> String {
    let out = String::from_utf8_lossy(stdout);
    let err = String::from_utf8_lossy(stderr);
    [out.trim_end(), err.trim_end()]
        .iter()
        .filter(|s| !s.is_empty())
        .copied()
        .collect::<Vec<_>>()
        .join("\n")
}

/// A short human reason for a failed connect.
fn describe_io_error(e: &std::io::Error) -> String {
    match e.kind() {
        std::io::ErrorKind::ConnectionRefused => "connection refused".to_string(),
        std::io::ErrorKind::TimedOut => "timed out".to_string(),
        _ => e.to_string(),
    }
}

fn describe_ureq_error(e: &ureq::Error) -> String {
    match e {
        ureq::Error::Io(io) => describe_io_error(io),
        ureq::Error::Timeout(_) => "timed out".to_string(),
        other => other.to_string(),
    }
}

fn docker_login(
    config_dir: Option<&std::path::Path>,
    registry: &str,
    username: &str,
    password: &str,
) -> Result<(), String> {
    use std::io::Write;
    let mut argv: Vec<String> = Vec::new();
    if let Some(d) = config_dir {
        argv.push("--config".into());
        argv.push(d.display().to_string());
    }
    argv.extend(
        ["login", "-u", username, "--password-stdin", registry]
            .iter()
            .map(|a| a.to_string()),
    );
    let mut child = crate::sandbox::engine::command(&argv)?
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .map_err(|e| format!("container runtime not available: {e}"))?;
    if let Some(mut si) = child.stdin.take() {
        let _ = si.write_all(password.as_bytes());
    }
    let out = child.wait_with_output().map_err(|e| e.to_string())?;
    if out.status.success() {
        Ok(())
    } else {
        Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
    }
}

/// A per-job registry login: written as the instance's docker `config.json`
/// (the credential reaches the instance as a file, never an argv).
fn write_job_login(
    config_dir: &std::path::Path,
    registry: &str,
    username: &str,
    password: &str,
) -> Result<(), String> {
    use std::io::Write;
    #[cfg(unix)]
    use std::os::unix::fs::OpenOptionsExt;
    let mut o = std::fs::OpenOptions::new();
    o.write(true).create(true).truncate(true);
    #[cfg(unix)]
    o.mode(0o600);
    o.open(config_dir.join("config.json"))
        .and_then(|mut f| {
            f.write_all(
                crate::sandbox::ephemeral::docker_config_json(registry, username, password)
                    .as_bytes(),
            )
        })
        .map_err(|e| format!("docker config: {e}"))
}

/// How many times `DockerCli::container_ip` retries an empty result, and how
/// long it sleeps between attempts. The IP shows up in
/// `NetworkSettings.Networks` a moment after `docker run` returns — not
/// synchronously with it — so the first inspect or two can legitimately come
/// back empty even though the container is fine.
const CONTAINER_IP_RETRIES: u32 = 10;
const CONTAINER_IP_RETRY_DELAY: Duration = Duration::from_millis(300);

/// Whether containers run in the shared LXC sandbox (T1) on this host.
fn in_sandbox() -> bool {
    crate::sandbox::engine::active()
        .engine
        .as_ref()
        .is_some_and(|e| e.is_lxc())
}

/// Whether a foreign job gets its own instance (T2) on this host.
fn per_job_isolation() -> bool {
    crate::sandbox::engine::active_job_tier() == crate::sandbox::engine::Tier::PerJob
}

/// The root disk of a per-job instance: the budget's.
fn ephemeral_disk_bytes() -> u64 {
    crate::sandbox::Budget::from_env(&|k| std::env::var(k).ok())
        .map(|b| b.disk_bytes)
        .unwrap_or(crate::sandbox::lxc::DEFAULT_DISK_BYTES)
}

/// The shared sandbox's bridge address, which the host can dial.
fn sandbox_address() -> Option<String> {
    use crate::sandbox::lxc::IncusCli as _;
    let out = crate::sandbox::lxc::IncusShell
        .run(&[
            "incus".to_string(),
            "list".to_string(),
            crate::sandbox::lxc::SANDBOX.to_string(),
            "-f".to_string(),
            "csv".to_string(),
            "-c".to_string(),
            "4".to_string(),
        ])
        .ok()?;
    crate::sandbox::ephemeral::parse_ipv4(&out)
}

impl ContainerRuntime for DockerCli {
    fn available(&self) -> bool {
        crate::sandbox::engine::available()
    }

    fn admit_guest(&self, d: &super::Desired) -> Result<(), crate::policy::admit::Refusal> {
        crate::broker::admission::guest_deployment(d)
    }

    fn pull(&self, image: &str) -> Result<(), String> {
        docker(&["pull", image]).map(|_| ())
    }

    fn run(&self, spec: &RunSpec) -> Result<String, String> {
        // Best-effort: clear a stale container occupying this exact name
        // (e.g. left over from a crashed prior reconcile attempt at the same
        // version). Docker errors on a name collision otherwise.
        let _ = docker(&["rm", "-f", &spec.name]);

        // An isolated environment must never fall back to a routable network:
        // if the internal network can't be ensured, fail the start.
        if spec.network.as_deref() == Some(isolated_network().as_str())
            && docker(&["network", "inspect", &isolated_network()]).is_err()
        {
            docker(&["network", "create", "--internal", &isolated_network()])
                .map_err(|e| format!("cannot create isolated network: {e}"))?;
        }
        let mut args = build_run_args(spec, &deploy_network());
        // Docker doesn't publish ports from an `--internal` network, so an
        // isolated environment stays unpublished. Inside the LXC sandbox the
        // container IP is not routable from the host either, so ports are
        // published on the sandbox's own address (`container_addr` dials it).
        if (publish_loopback() || in_sandbox())
            && spec.network.as_deref() != Some(isolated_network().as_str())
        {
            add_loopback_publish(&mut args, spec, in_sandbox());
        }
        // Node-wide GPU passthrough (ZAKURO_DEPLOY_GPUS) is part of the
        // budget now (`sandbox::Budget::from_env`), so it already is in
        // `spec.limits`.

        let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        docker(&arg_refs)
    }

    fn run_leased(
        &self,
        spec: &RunSpec,
        pull_config: Option<&std::path::Path>,
    ) -> Result<String, String> {
        if !per_job_isolation() {
            return self.run(spec);
        }
        use crate::sandbox::ephemeral;
        let eph = ephemeral();
        ephemeral::start_reaper_once(eph);
        ephemeral::start_job(
            eph,
            &ephemeral::JobRun {
                name: spec.name.clone(),
                image: spec.image.to_string(),
                labels: spec.labels.clone(),
                mounts: spec.mounts.clone(),
                env: {
                    let mut e: Vec<(String, String)> = spec
                        .env
                        .iter()
                        .map(|(k, v)| (k.clone(), v.clone()))
                        .collect();
                    e.sort();
                    e
                },
                cmd: spec
                    .cmd
                    .map(|c| c.split_whitespace().map(str::to_string).collect())
                    .unwrap_or_default(),
                limits: spec.limits.clone(),
                disk_bytes: ephemeral_disk_bytes(),
                hardened: spec.hardened,
                pull_config: pull_config.map(std::path::Path::to_path_buf),
            },
            &ephemeral::real_nvidia_smi,
        )
    }

    fn stop(&self, container_id: &str) -> Result<(), String> {
        match locate(container_id) {
            // The instance is the boundary: stopping the job is deleting it.
            (Where::Job(inst), _) => ephemeral().destroy(inst),
            (w, name) => docker_at(&w, &["stop", name]).map(|_| ()),
        }
    }

    fn rm(&self, container_id: &str) -> Result<(), String> {
        match locate(container_id) {
            (Where::Job(inst), _) => ephemeral().destroy(inst),
            (w, name) => docker_at(&w, &["rm", "-f", name]).map(|_| ()),
        }
    }

    fn restart(&self, container_id: &str) -> Result<(), String> {
        let (w, name) = locate(container_id);
        docker_at(&w, &["start", name]).map(|_| ())
    }

    fn is_running(&self, container_id: &str) -> bool {
        let (w, name) = locate(container_id);
        docker_at(&w, &["inspect", "-f", "{{.State.Running}}", name])
            .map(|out| out == "true")
            .unwrap_or(false)
    }

    fn container_ip(&self, container_id: &str) -> Result<String, String> {
        let (w, container_id) = locate(container_id);
        for attempt in 0..CONTAINER_IP_RETRIES {
            let out = docker_at(
                &w,
                &[
                    "inspect",
                    "-f",
                    "{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}",
                    container_id,
                ],
            )?;
            // First non-empty token: a container can be on more than one
            // network (rare here, but the format string doesn't rule it
            // out), and an entry with no assigned address yet renders as an
            // empty string between the spaces rather than being omitted.
            if let Some(ip) = out.split_whitespace().find(|s| !s.is_empty()) {
                return Ok(ip.to_string());
            }
            if attempt + 1 < CONTAINER_IP_RETRIES {
                std::thread::sleep(CONTAINER_IP_RETRY_DELAY);
            }
        }
        Err(format!(
            "container {container_id} has no network IP after {CONTAINER_IP_RETRIES} attempts \
             (host network mode, or the container exited)"
        ))
    }

    fn container_addr(&self, container_id: &str, port: u16) -> Result<(String, u16), String> {
        if let (Where::Job(_), _) = locate(container_id) {
            // A per-job instance publishes nothing: its container talks over
            // the mounted socket, and its nested IP is not routable here.
            return Err(format!(
                "{container_id} runs in its own instance and publishes no port"
            ));
        }
        if publish_loopback() || in_sandbox() {
            let spec = format!("{port}/tcp");
            for attempt in 0..CONTAINER_IP_RETRIES {
                if let Some((host, mapped)) = docker(&["port", container_id, &spec])
                    .ok()
                    .and_then(|out| parse_published_port(&out))
                {
                    // Inside the sandbox the mapping lives on its own bridge
                    // address, which the host can dial.
                    return match sandbox_address().filter(|_| in_sandbox()) {
                        Some(ip) => Ok((ip, mapped)),
                        None => Ok((host, mapped)),
                    };
                }
                if attempt + 1 < CONTAINER_IP_RETRIES {
                    std::thread::sleep(CONTAINER_IP_RETRY_DELAY);
                }
            }
            // Not published (isolated, or started before this broker
            // published ports): the container IP is all there is.
        }
        self.container_ip(container_id).map(|ip| (ip, port))
    }

    fn health_check(&self, container_id: &str, hc: &Healthcheck) -> bool {
        self.health_probe(container_id, hc).is_ok()
    }

    fn health_probe(&self, container_id: &str, hc: &Healthcheck) -> Result<(), String> {
        // `--network host` (or any other mode docker gives no per-container
        // IP for) has nothing of its own to address: the environment's
        // process is reachable exactly where it bound, on THIS docker
        // host's own loopback — which is only actually correct when this
        // broker shares that host's netns (host-native `zc`, or a broker
        // container itself run with `--network host`). Anything more
        // specific than that fallback would need the hub to tell us which
        // mode a deployment wants, which isn't part of the contract today.
        let (host, port) = self
            .container_addr(container_id, hc.port)
            .unwrap_or_else(|_| ("127.0.0.1".to_string(), hc.port));
        match hc.kind.as_str() {
            "tcp" => std::net::TcpStream::connect((host.as_str(), port))
                .map(|_| ())
                .map_err(|e| format!("TCP {host}:{port} → {}", describe_io_error(&e))),
            _ => {
                let url = health_http_url(&host, port, hc);
                match ureq::get(&url)
                    .config()
                    .timeout_global(Some(Duration::from_secs(3)))
                    .http_status_as_error(false)
                    .build()
                    .call()
                {
                    Ok(r) if (200..300).contains(&r.status().as_u16()) => Ok(()),
                    Ok(r) => Err(format!("GET {url} → HTTP {}", r.status().as_u16())),
                    Err(e) => Err(format!("GET {url} → {}", describe_ureq_error(&e))),
                }
            }
        }
    }

    fn logs_tail(&self, container_id: &str, lines: u32) -> String {
        docker_logs(container_id, lines)
    }

    fn allocations(&self) -> Result<Vec<crate::sandbox::Allocation>, String> {
        crate::sandbox::engine::allocations()
    }

    fn list_by_label_key(&self, key: &str) -> Vec<String> {
        docker(&["ps", "-a", "-q", "--filter", &format!("label={key}")])
            .map(|out| {
                out.lines()
                    .map(|l| l.trim().to_string())
                    .filter(|l| !l.is_empty())
                    .collect()
            })
            .unwrap_or_default()
    }

    fn login_in(
        &self,
        config_dir: &std::path::Path,
        registry: &str,
        username: &str,
        password: &str,
    ) -> Result<(), String> {
        if per_job_isolation() {
            // The job's own instance logs in: nothing touches the shared
            // sandbox, so a lease's token never outlives its instance.
            return write_job_login(config_dir, registry, username, password);
        }
        docker_login(Some(config_dir), registry, username, password)
    }

    fn pull_in(&self, config_dir: &std::path::Path, image: &str) -> Result<(), String> {
        if per_job_isolation() {
            // Pulled inside the job's instance by `run_leased`.
            return Ok(());
        }
        docker(&["--config", &config_dir.display().to_string(), "pull", image]).map(|_| ())
    }

    fn login(&self, registry: &str, username: &str, password: &str) -> Result<(), String> {
        docker_login(None, registry, username, password)
    }

    fn image_digest(&self, container_id: &str) -> Result<String, String> {
        let (w, container_id) = locate(container_id);
        let image_id = docker_at(&w, &["inspect", "-f", "{{.Image}}", container_id])?;
        let digests = docker_at(
            &w,
            &[
                "image",
                "inspect",
                "-f",
                "{{range .RepoDigests}}{{.}} {{end}}",
                &image_id,
            ],
        )
        .unwrap_or_default();
        let found: Vec<String> = digests
            .split_whitespace()
            .filter_map(|d| d.rsplit_once('@').map(|(_, h)| h.to_string()))
            .collect();
        if found.is_empty() {
            Ok(image_id)
        } else {
            Ok(found.join(","))
        }
    }

    fn list_by_label(&self, id: &str) -> Vec<String> {
        docker(&[
            "ps",
            "-a",
            "-q",
            "--filter",
            &format!("label=zakuro.deployment={id}"),
        ])
        .map(|out| out.lines().map(|l| l.trim().to_string()).collect())
        .unwrap_or_default()
    }
}

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

    #[test]
    fn run_spec_new_fields_map_to_docker_args() {
        let env = HashMap::from([("K".to_string(), "V".to_string())]);
        let spec = RunSpec {
            name: "n".into(),
            image: "img@sha256:ab",
            cmd: None,
            ports: &[],
            env: &env,
            labels: vec![("a".into(), "b".into())],
            mounts: vec![("/h/s.sock".into(), "/run/zakuro/space.sock".into())],
            limits: crate::sandbox::Limits::new(2.5, 8.0, crate::sandbox::Gpus::Count(1)),
            network: Some("egress".into()),
            hardened: true,
        };
        let args = build_run_args(&spec, "bridge");
        let joined = args.join(" ");
        assert!(joined.contains("--network egress"));
        assert!(joined.contains("-v /h/s.sock:/run/zakuro/space.sock"));
        assert!(joined.contains("--cpus 2.5"));
        assert!(joined.contains("--memory 8192m"));
        assert!(joined.contains("--gpus 1"));
        assert!(joined.contains("--pids-limit 4096"));
        assert!(joined.contains("--security-opt no-new-privileges"));
        assert!(joined.contains("--label a=b"));
        assert!(joined.contains("-e K=V"));
        assert_eq!(args.last().unwrap(), "img@sha256:ab");

        let plain = RunSpec {
            mounts: vec![],
            limits: crate::sandbox::Limits::new(1.0, 1.0, crate::sandbox::Gpus::Count(0)),
            network: None,
            hardened: false,
            ..spec
        };
        let j = build_run_args(&plain, "bridge").join(" ");
        assert!(j.contains("--network bridge"));
        // No GPU asked for, none passed; cpu and memory are always capped.
        assert!(!j.contains("--gpus"));
        assert!(
            j.contains("--cpus 1 --memory 1024m --memory-swap 1024m"),
            "{j}"
        );
        assert!(!j.contains(" -v "));
        assert!(!j.contains("--pids-limit") && !j.contains("no-new-privileges"));
    }

    #[test]
    fn container_name_is_unique_per_version() {
        assert_eq!(container_name("dep_1", 3), "zk-dep-dep_1-v3");
        assert_ne!(container_name("dep_1", 3), container_name("dep_1", 4));
    }

    #[test]
    fn deployment_labels_carry_id_and_version() {
        let labels = deployment_labels("dep_1", 3);
        assert!(labels.contains(&("zakuro.deployment".to_string(), "dep_1".to_string())));
        assert!(labels.contains(&("zakuro.version".to_string(), "3".to_string())));
    }

    fn hc(kind: &str, path: Option<&str>) -> Healthcheck {
        Healthcheck {
            kind: kind.to_string(),
            port: 8000,
            path: path.map(|s| s.to_string()),
            timeout_s: 60,
        }
    }

    #[test]
    fn merge_logs_keeps_stderr_when_stdout_is_empty() {
        assert_eq!(
            merge_logs(b"", b"jupyter: bind failed\n"),
            "jupyter: bind failed"
        );
        assert_eq!(merge_logs(b"out\n", b"err\n"), "out\nerr");
        assert_eq!(merge_logs(b"", b""), "");
    }

    #[test]
    fn connect_errors_read_as_plain_words() {
        let refused = std::io::Error::from(std::io::ErrorKind::ConnectionRefused);
        assert_eq!(describe_io_error(&refused), "connection refused");
        let timeout = std::io::Error::from(std::io::ErrorKind::TimedOut);
        assert_eq!(describe_io_error(&timeout), "timed out");
    }

    #[test]
    fn health_http_url_defaults_path_to_root() {
        assert_eq!(
            health_http_url("172.17.0.5", 8000, &hc("http", None)),
            "http://172.17.0.5:8000/"
        );
    }

    #[test]
    fn health_http_url_tolerates_a_path_without_leading_slash() {
        assert_eq!(
            health_http_url("172.17.0.5", 8000, &hc("http", Some("healthz"))),
            "http://172.17.0.5:8000/healthz"
        );
    }

    #[test]
    fn health_http_url_keeps_an_already_leading_slash() {
        assert_eq!(
            health_http_url("172.17.0.5", 8000, &hc("http", Some("/api/health"))),
            "http://172.17.0.5:8000/api/health"
        );
    }

    #[test]
    fn health_http_url_uses_the_container_ip_not_loopback() {
        // The whole point of the drill fix: this must never say 127.0.0.1
        // when a real container IP is available.
        let url = health_http_url("10.13.13.10", 8000, &hc("http", None));
        assert!(url.starts_with("http://10.13.13.10:"));
        assert!(!url.contains("127.0.0.1"));
    }

    #[test]
    fn health_http_url_dials_the_given_port_not_the_container_port() {
        // A published port (Docker Desktop) differs from hc.port.
        assert_eq!(
            health_http_url("127.0.0.1", 49153, &hc("http", Some("/api"))),
            "http://127.0.0.1:49153/api"
        );
    }

    #[test]
    fn loopback_publish_args_bind_each_port_once_on_loopback_only() {
        assert_eq!(
            loopback_publish_args(&[8888, 8000, 8888], "127.0.0.1"),
            vec!["-p", "127.0.0.1::8888", "-p", "127.0.0.1::8000"]
        );
        assert!(loopback_publish_args(&[], "127.0.0.1").is_empty());
        assert_eq!(
            loopback_publish_args(&[80], "0.0.0.0"),
            vec!["-p".to_string(), "0.0.0.0::80".to_string()]
        );
    }

    #[test]
    fn loopback_publish_goes_before_the_image_and_its_command() {
        let env = HashMap::new();
        let ports = [Port {
            container: 8888,
            protocol: "http".into(),
        }];
        let spec = RunSpec {
            name: "n".into(),
            image: "jupyter/base-notebook:latest",
            cmd: Some("jupyter lab"),
            ports: &ports,
            env: &env,
            labels: vec![],
            mounts: vec![],
            limits: crate::sandbox::Limits::new(1.0, 1.0, crate::sandbox::Gpus::None),
            network: None,
            hardened: false,
        };
        let mut args = build_run_args(&spec, "bridge");
        add_loopback_publish(&mut args, &spec, false);
        assert!(args
            .join(" ")
            .ends_with("-p 127.0.0.1::8888 jupyter/base-notebook:latest jupyter lab"));
    }

    #[test]
    fn parse_published_port_prefers_the_ipv4_loopback_mapping() {
        assert_eq!(
            parse_published_port("[::1]:49154\n127.0.0.1:49153"),
            Some(("127.0.0.1".to_string(), 49153))
        );
        assert_eq!(
            parse_published_port("0.0.0.0:49153"),
            Some(("127.0.0.1".to_string(), 49153))
        );
        assert_eq!(parse_published_port(""), None);
        assert_eq!(parse_published_port("garbage"), None);
    }

    #[test]
    fn publish_loopback_defaults_per_os_and_honours_the_override() {
        assert!(publish_loopback_from(None, true));
        assert!(!publish_loopback_from(None, false));
        assert!(!publish_loopback_from(Some(" 0 "), true));
        assert!(!publish_loopback_from(Some("false"), true));
        assert!(publish_loopback_from(Some("1"), false));
        assert!(publish_loopback_from(Some("true"), false));
        assert!(publish_loopback_from(Some(""), true));
    }

    #[test]
    fn isolated_spec_runs_on_the_isolated_network() {
        let env = HashMap::new();
        let spec = RunSpec {
            name: "n".into(),
            image: "img",
            cmd: None,
            ports: &[],
            env: &env,
            labels: vec![],
            mounts: vec![],
            limits: crate::sandbox::Limits::new(1.0, 1.0, crate::sandbox::Gpus::None),
            network: Some("zc-isolated".into()),
            hardened: false,
        };
        assert!(build_run_args(&spec, "bridge")
            .join(" ")
            .contains("--network zc-isolated"));
    }

    #[test]
    fn deploy_network_defaults_to_bridge_when_unset() {
        let _lock = crate::credentials::HOME_ENV_LOCK.lock();
        let prev = std::env::var_os("ZAKURO_DEPLOY_NETWORK");
        std::env::remove_var("ZAKURO_DEPLOY_NETWORK");
        assert_eq!(deploy_network(), "bridge");
        if let Some(v) = prev {
            std::env::set_var("ZAKURO_DEPLOY_NETWORK", v);
        }
    }

    #[test]
    fn deploy_network_honours_the_env_override() {
        let _lock = crate::credentials::HOME_ENV_LOCK.lock();
        let prev = std::env::var_os("ZAKURO_DEPLOY_NETWORK");
        std::env::set_var("ZAKURO_DEPLOY_NETWORK", "hubnet");
        assert_eq!(deploy_network(), "hubnet");
        match prev {
            Some(v) => std::env::set_var("ZAKURO_DEPLOY_NETWORK", v),
            None => std::env::remove_var("ZAKURO_DEPLOY_NETWORK"),
        }
    }

    #[test]
    fn deploy_network_blank_value_falls_back_to_bridge() {
        let _lock = crate::credentials::HOME_ENV_LOCK.lock();
        let prev = std::env::var_os("ZAKURO_DEPLOY_NETWORK");
        std::env::set_var("ZAKURO_DEPLOY_NETWORK", "   ");
        assert_eq!(deploy_network(), "bridge");
        match prev {
            Some(v) => std::env::set_var("ZAKURO_DEPLOY_NETWORK", v),
            None => std::env::remove_var("ZAKURO_DEPLOY_NETWORK"),
        }
    }
}

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

    fn facts(exists: bool, containerd: bool) -> HostFacts {
        HostFacts {
            socket_path: "/var/run/docker.sock".into(),
            socket_exists: exists,
            containerd_socket: containerd,
        }
    }
    fn exited(stderr: &str) -> CliOutcome {
        CliOutcome::Exited {
            success: false,
            stderr: stderr.into(),
        }
    }
    fn probe(o: CliOutcome, f: HostFacts) -> RuntimeProbe {
        classify_probe(o, &f, "t".into())
    }

    #[test]
    fn available_when_info_succeeds() {
        let p = probe(
            CliOutcome::Exited {
                success: true,
                stderr: String::new(),
            },
            facts(true, false),
        );
        assert!(p.available && p.error.is_none() && p.runtime == Some("docker"));
        assert!(p.next_step().is_none());
    }

    #[test]
    fn binary_missing_is_not_installed() {
        let p = probe(
            CliOutcome::SpawnFailed(std::io::ErrorKind::NotFound, "nf".into()),
            facts(false, false),
        );
        assert_eq!(p.error, Some(RuntimeError::NotInstalled));
        assert_eq!(p.runtime, None);
    }

    #[test]
    fn containerd_only_is_reported_as_containerd_not_installed() {
        let p = probe(
            CliOutcome::SpawnFailed(std::io::ErrorKind::NotFound, "nf".into()),
            facts(false, true),
        );
        assert_eq!(p.error, Some(RuntimeError::NotInstalled));
        assert_eq!(p.runtime, Some("containerd"));
        assert!(!p.available);
    }

    #[test]
    fn socket_missing() {
        let p = probe(exited("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?"), facts(false, false));
        assert_eq!(p.error, Some(RuntimeError::SocketMissing));
    }

    #[test]
    fn permission_denied_names_socket_and_group_fix() {
        let p = probe(exited("permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock"), facts(true, false));
        assert_eq!(p.error, Some(RuntimeError::PermissionDenied));
        let m = p.failure_message();
        assert!(m.starts_with("no container runtime on this host"));
        assert!(m.contains("permission denied on /var/run/docker.sock"));
        assert!(m.contains("docker group"));
    }

    #[test]
    fn daemon_down_when_socket_exists_but_refuses() {
        let p = probe(exited("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?"), facts(true, false));
        assert_eq!(p.error, Some(RuntimeError::DaemonDown));
    }

    #[test]
    fn hung_daemon_is_daemon_down_with_timeout_detail() {
        // Socket present, process never answered.
        let p = probe(CliOutcome::TimedOut, facts(true, false));
        assert!(!p.available);
        assert_eq!(p.error, Some(RuntimeError::DaemonDown));
        assert_eq!(p.detail, "docker version did not answer within 5 s");
        assert!(p.next_step().is_some());
    }

    #[cfg(unix)]
    #[test]
    fn run_bounded_kills_a_hanging_process() {
        let t = std::time::Instant::now();
        let (o, _) = run_bounded(
            Command::new("sleep").arg("30"),
            std::time::Duration::from_millis(200),
        );
        assert!(matches!(o, CliOutcome::TimedOut));
        assert!(t.elapsed() < std::time::Duration::from_secs(10));
    }

    #[cfg(unix)]
    #[test]
    fn run_bounded_returns_output_of_a_quick_process() {
        let (o, out) = run_bounded(
            Command::new("sh").args(["-c", "echo hi; echo oops >&2; exit 3"]),
            std::time::Duration::from_secs(5),
        );
        assert_eq!(out.trim(), "hi");
        assert!(matches!(o, CliOutcome::Exited { success: false, ref stderr } if stderr == "oops"));
    }

    #[test]
    fn unknown_failure_is_other_with_first_line() {
        let p = probe(exited("boom\nsecond"), facts(true, false));
        assert_eq!(p.error, Some(RuntimeError::Other));
        assert!(p.detail.contains("boom") && !p.detail.contains("second"));
    }

    #[test]
    fn recovery_flips_to_available() {
        let down = probe(
            exited("Cannot connect to the Docker daemon"),
            facts(true, false),
        );
        let up = probe(
            CliOutcome::Exited {
                success: true,
                stderr: String::new(),
            },
            facts(true, false),
        );
        assert!(!down.available && up.available);
    }

    #[test]
    fn doctor_report_prints_reason_and_next_step() {
        let p = probe(exited("permission denied"), facts(true, false));
        let r = doctor_report(&p);
        assert!(
            r.contains("UNAVAILABLE") && r.contains("permission_denied") && r.contains("next step")
        );
    }
}