runnerd-core 0.1.0

Config, domain logic and API types shared by runnerd and its clients
Documentation
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
//! The warm caches runner containers share and keep between jobs: each profile's read-only snapshot, each slot's
//! volume (its layers' changes and its Docker Engine's data), the shared pnpm store and Maven repository, and the
//! Docker Hub mirror on the runners' network. Owns their names, mounts and lifecycle; it never decides when a
//! runner starts, and it never touches a volume a running container uses.

use std::collections::{BTreeMap, HashMap};

use bollard::models::{
    ContainerCreateBody, EndpointSettings, HostConfig, Mount, MountType, NetworkingConfig,
};

use crate::api;
use crate::config::{self, ByteSize};
use crate::docker::{DockerApi, Error, RunnerSpec, is_not_found};
use crate::isolation::Isolation;

/// The Docker Hub pull-through cache (`registry` 3.1.2, multi-platform index).
pub const MIRROR_IMAGE: &str =
    "registry:3.1.2@sha256:01cd312e67026f06f5d89c3e133a4a9adc7cb9eeb9b1194e0b2954dfd770efd2";

/// The host name runner containers reach the mirror at (`image/daemon.json`).
const MIRROR_ALIAS: &str = "mirror";

/// The mirror's `oom_score_adj`: the kernel picks it after the runners' processes, which keep the default 0.
const MIRROR_OOM_SCORE_ADJ: i64 = -500;

/// The names of everything runnerd creates in Docker, under one prefix: `runnerd`, or another for tests.
#[derive(Debug, Clone)]
pub struct Names {
    prefix: String,
}

impl Names {
    /// Names under `prefix`.
    pub fn new(prefix: &str) -> Names {
        Names {
            prefix: prefix.to_owned(),
        }
    }

    /// The network runners and the mirror share.
    pub fn network(&self) -> String {
        self.prefix.clone()
    }

    /// The profile's read-only snapshot.
    pub fn base(&self, profile: &str) -> String {
        format!("{}-{profile}-base", self.prefix)
    }

    /// Slot `slot` (1-based) of the profile: its layers' changes and its Docker Engine's data.
    pub fn slot(&self, profile: &str, slot: usize) -> String {
        format!("{}-{profile}-slot-{slot}", self.prefix)
    }

    /// The pnpm store all slots share.
    pub fn pnpm(&self) -> String {
        format!("{}-pnpm", self.prefix)
    }

    /// The Maven repository all slots share.
    pub fn maven(&self) -> String {
        format!("{}-maven", self.prefix)
    }

    /// The slot (1-based) of the profile whose volume `volume` is, if it is one of its slots'.
    pub fn slot_of(&self, profile: &str, volume: &str) -> Option<usize> {
        volume
            .strip_prefix(&format!("{}-{profile}-slot-", self.prefix))?
            .parse()
            .ok()
    }

    /// The container that rebuilds the profile's snapshot.
    pub fn seed(&self, profile: &str) -> String {
        format!("{}-{profile}-seed", self.prefix)
    }

    /// The container that measures what the profile's slot 1 changed, before its upkeep (`measure`).
    pub fn measure(&self, profile: &str) -> String {
        format!("{}-{profile}-measure", self.prefix)
    }

    /// The mirror's container and its storage volume.
    pub fn mirror(&self) -> String {
        format!("{}-mirror", self.prefix)
    }

    /// What `GET /v1/caches` and `runnerctl caches clean` call the shared build cache: a directory of the daemon's,
    /// not a Docker volume.
    pub fn build_cache(&self) -> String {
        format!("{}-build-cache", self.prefix)
    }
}

fn volume(source: String, target: &str, read_only: bool) -> Mount {
    Mount {
        target: Some(target.to_owned()),
        source: Some(source),
        typ: Some(MountType::VOLUME),
        read_only: Some(read_only),
        ..Default::default()
    }
}

/// What a runner container in slot `slot` (1-based) of the profile mounts (paths from `image/Dockerfile`).
pub fn runner_mounts(names: &Names, profile: &str, slot: usize) -> Vec<Mount> {
    vec![
        volume(names.base(profile), "/base", true),
        volume(names.slot(profile, slot), "/state", false),
        volume(names.pnpm(), "/shared/pnpm", false),
        volume(names.maven(), "/shared/maven", false),
    ]
}

/// The mirror container: Docker Hub through a proxy registry, which refuses pushes, so a job can only make it
/// fetch what Docker Hub serves. Content not pulled again within the TTL expires. No published port.
pub fn mirror_body(names: &Names, mirror: &config::Mirror, slice: &str) -> ContainerCreateBody {
    let memory = i64::try_from(mirror.memory.0).unwrap_or(i64::MAX);
    ContainerCreateBody {
        image: Some(MIRROR_IMAGE.to_owned()),
        env: Some(vec![
            "REGISTRY_PROXY_REMOTEURL=https://registry-1.docker.io".to_owned(),
            format!("REGISTRY_PROXY_TTL={}s", mirror.ttl.as_secs()),
            // Expiry deletes content.
            "REGISTRY_STORAGE_DELETE_ENABLED=true".to_owned(),
        ]),
        labels: Some(HashMap::from([(
            "runnerd.mirror".to_owned(),
            String::new(),
        )])),
        host_config: Some(HostConfig {
            cgroup_parent: Some(slice.to_owned()),
            memory: Some(memory),
            memory_swap: Some(memory),
            nano_cpus: Some(i64::from(mirror.cpus) * 1_000_000_000),
            // When the slice runs out of memory, which measured admission allows, the kernel kills a job's process
            // before the mirror every runner pulls through.
            oom_score_adj: Some(MIRROR_OOM_SCORE_ADJ),
            mounts: Some(vec![volume(names.mirror(), "/var/lib/registry", false)]),
            network_mode: Some(names.network()),
            ..Default::default()
        }),
        networking_config: Some(NetworkingConfig {
            endpoints_config: Some(HashMap::from([(
                names.network(),
                EndpointSettings {
                    aliases: Some(vec![MIRROR_ALIAS.to_owned()]),
                    ..Default::default()
                },
            )])),
        }),
        ..Default::default()
    }
}

/// Creates what a profile's runner in `slot` (1-based) mounts and joins, if missing.
pub async fn prepare(
    docker: &impl DockerApi,
    names: &Names,
    profile: &str,
    slot: usize,
) -> Result<(), Error> {
    docker.ensure_network(&names.network()).await?;
    for name in [
        names.base(profile),
        names.slot(profile, slot),
        names.pnpm(),
        names.maven(),
    ] {
        docker.ensure_volume(&name).await?;
    }
    Ok(())
}

/// Starts the mirror unless it runs.
pub async fn mirror_up(
    docker: &impl DockerApi,
    names: &Names,
    mirror: &config::Mirror,
    slice: &str,
) -> Result<(), Error> {
    match docker.inspect(&names.mirror()).await {
        Ok(state) if state.running => return Ok(()),
        // Stopped on its own: started again from scratch, its storage is the volume.
        Ok(_) => docker.remove(&names.mirror()).await?,
        Err(error) if is_not_found(&error) => {}
        Err(error) => return Err(error),
    }
    docker.ensure_network(&names.network()).await?;
    if !docker.image_present(MIRROR_IMAGE).await? {
        docker.pull(MIRROR_IMAGE).await?;
    }
    docker
        .run(&names.mirror(), mirror_body(names, mirror, slice))
        .await?;
    Ok(())
}

/// Stops the mirror; its storage stays.
pub async fn mirror_down(docker: &impl DockerApi, names: &Names) -> Result<(), Error> {
    match docker.remove(&names.mirror()).await {
        Err(error) if is_not_found(&error) => Ok(()),
        other => other,
    }
}

/// Whether the mirror's container is down, so its storage can be removed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mirror {
    /// It runs, or may: an earlier daemon may have left it up.
    Up,
    /// It is stopped.
    Down,
}

/// What `trim_shared` measured and emptied.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Trimmed {
    /// Every volume's size in bytes, by name, as measured before emptying any.
    pub sizes: BTreeMap<String, u64>,
    /// The shared caches it emptied.
    pub emptied: Vec<Emptied>,
    /// The slot volumes past their profile's slot count it removed.
    pub closed: Vec<Emptied>,
    /// The volumes it was to empty or remove that Docker refused to, as one a stopped container still uses: tried
    /// again at the next check.
    pub refused: Vec<Refused>,
    /// Docker's free disk in bytes, as measured before emptying any; `None` when it could not be measured.
    pub free: Option<u64>,
}

/// A volume `trim_shared` was to remove that Docker refused to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refused {
    /// The volume.
    pub name: String,
    /// What Docker said.
    pub error: String,
}

/// A shared cache `trim_shared` emptied.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Emptied {
    /// The volume.
    pub name: String,
    /// How large it had grown.
    pub size: ByteSize,
}

/// Empties the shared caches that outgrew their limit, the mirror's storage among them once the mirror is down
/// (`Mirror::Down`), and removes the volumes of slots past the count `slots` gives their profile, as a lowered count
/// leaves them: each holds a slot's layers and Docker store, which no job prunes again (docs/adr/0054). Call only
/// while no runner runs, and leave out of `slots` a profile whose reseed runs, which mounts its slots' volumes.
pub async fn trim_shared(
    docker: &impl DockerApi,
    names: &Names,
    caches: &config::Caches,
    mirror: Mirror,
    slots: &BTreeMap<String, usize>,
) -> Result<Trimmed, Error> {
    let sizes = docker.volume_sizes().await?;
    let free = docker.free_space().await.ok();
    let mut emptied = Vec::new();
    let mut refused = Vec::new();
    let mut limits = vec![
        (names.pnpm(), caches.pnpm.max_size),
        (names.maven(), caches.maven.max_size),
    ];
    if mirror == Mirror::Down {
        limits.push((names.mirror(), caches.mirror.max_size));
    }
    for (name, limit) in limits {
        if let Some(&size) = sizes.get(&name)
            && size > limit.0
        {
            // One Docker refuses stays to the next check; the others are still trimmed, and the sizes kept.
            if let Err(error) = docker.remove_volume(&name).await {
                refused.push(Refused {
                    name,
                    error: error.to_string(),
                });
                continue;
            }
            emptied.push(Emptied {
                name,
                size: ByteSize(size),
            });
        }
    }
    let mut closed = Vec::new();
    for (name, &size) in &sizes {
        let past = slots.iter().any(|(profile, &count)| {
            names
                .slot_of(profile, name)
                .is_some_and(|slot| slot > count)
        });
        if past {
            // As a stopped container kept as a failed job's record still uses it.
            if let Err(error) = docker.remove_volume(name).await {
                refused.push(Refused {
                    name: name.clone(),
                    error: error.to_string(),
                });
                continue;
            }
            closed.push(Emptied {
                name: name.clone(),
                size: ByteSize(size),
            });
        }
    }
    Ok(Trimmed {
        sizes,
        emptied,
        closed,
        refused,
        free,
    })
}

/// What the slots' Docker Engines may keep together, in bytes: a quarter of Docker's disk not otherwise used, which
/// is what is free plus what the slot volumes already hold, measured together (docs/adr/0054).
pub fn docker_disk(
    names: &Names,
    config: &config::Config,
    free: u64,
    sizes: &BTreeMap<String, u64>,
) -> u64 {
    let held: u64 = config
        .profiles
        .iter()
        .flat_map(|(profile, settings)| {
            (1..=settings.slots as usize).map(move |slot| names.slot(profile, slot))
        })
        .filter_map(|name| sizes.get(&name))
        .sum();
    free.saturating_add(held) / DOCKER_DISK_SHARE
}

/// One slot's share of `disk` among `slots`, in whole GiB as `image/layers.sh` takes it: at least 1, at most
/// `DOCKER_SLOT_MAX_GIB`.
pub fn docker_budget_gib(disk: u64, slots: u64) -> u64 {
    ((disk / slots.max(1)) >> 30).clamp(1, DOCKER_SLOT_MAX_GIB)
}

/// The slots' Docker Engines together keep at most one part in this of Docker's disk not otherwise used.
const DOCKER_DISK_SHARE: u64 = 4;

/// The most one slot's Docker Engine keeps, in GiB: the image's own default, for a daemon that sets none.
const DOCKER_SLOT_MAX_GIB: u64 = 20;

/// Every cache volume the config's profiles use, what it holds and its limit, with size 0.
pub fn volumes(names: &Names, config: &config::Config) -> Vec<api::CacheVolume> {
    let volume = |name: String, kind: api::CacheKind, limit: Option<u64>| api::CacheVolume {
        name,
        kind,
        bytes: 0,
        limit,
    };
    let mut volumes = Vec::new();
    for (profile, settings) in &config.profiles {
        volumes.push(volume(
            names.base(profile),
            api::CacheKind::Snapshot {
                profile: profile.clone(),
            },
            Some(config.caches.snapshot_max.0),
        ));
        for slot in 1..=settings.slots as usize {
            volumes.push(volume(
                names.slot(profile, slot),
                api::CacheKind::Slot {
                    profile: profile.clone(),
                    slot,
                },
                None,
            ));
        }
    }
    volumes.push(volume(
        names.pnpm(),
        api::CacheKind::Pnpm,
        Some(config.caches.pnpm.max_size.0),
    ));
    volumes.push(volume(
        names.maven(),
        api::CacheKind::Maven,
        Some(config.caches.maven.max_size.0),
    ));
    if config.caches.mirror.enabled {
        volumes.push(volume(
            names.mirror(),
            api::CacheKind::Mirror,
            Some(config.caches.mirror.max_size.0),
        ));
    }
    if config.caches.build.enabled {
        volumes.push(volume(
            names.build_cache(),
            api::CacheKind::Build,
            Some(config.caches.build.max_size.0),
        ));
    }
    volumes.sort_by(|a, b| a.name.cmp(&b.name));
    volumes
}

/// What `reseed` runs on: the profile's image and limits, its slots and the isolation backend.
#[derive(Debug)]
pub struct Reseed<'profile> {
    /// Where the profile's volumes are.
    pub names: &'profile Names,
    /// The profile to reseed.
    pub profile: &'profile str,
    /// The profile's runner image, which holds the seed script.
    pub image: &'profile str,
    /// How many slots the profile has; each slot's layer changes are dropped.
    pub slots: usize,
    /// The systemd slice the seed container runs in.
    pub slice: &'profile str,
    /// The profile's CPUs.
    pub cpus: u32,
    /// The profile's memory.
    pub memory: ByteSize,
    /// Slot 1's layers must have changed at least this much (`caches.reseed_at`).
    pub min_changes: ByteSize,
    /// A snapshot that would outgrow this starts over (`caches.snapshot_max`).
    pub max_size: ByteSize,
    /// How the seed container is isolated, as runners are.
    pub isolation: &'profile dyn Isolation,
}

/// Makes slot 1's layers the profile's new snapshot and drops every slot's own layer changes (`image/seed.sh`),
/// if slot 1 changed at least `min_changes`. A snapshot that would outgrow `max_size` starts over from the image,
/// as every slot's changes go too (docs/adr/0065); after a reseed that did not finish, it starts over whatever the
/// limits (docs/adr/0066). Call only while none of the profile's slots runs. Returns the seed container's output.
pub async fn reseed(docker: &impl DockerApi, reseed: &Reseed<'_>) -> Result<String, Error> {
    let names = reseed.names;
    let mut mounts = vec![volume(names.base(reseed.profile), "/base", false)];
    mounts.extend((1..=reseed.slots).map(|slot| {
        volume(
            names.slot(reseed.profile, slot),
            &format!("/workers/{slot}"),
            false,
        )
    }));
    for mount in &mounts {
        if let Some(source) = &mount.source {
            docker.ensure_volume(source).await?;
        }
    }
    let name = names.seed(reseed.profile);
    let spec = RunnerSpec {
        name: name.clone(),
        image: reseed.image.to_owned(),
        profile: reseed.profile.to_owned(),
        slice: reseed.slice.to_owned(),
        cpus: reseed.cpus,
        memory: reseed.memory,
        env: Vec::new(),
        mounts,
        network: Some("none".to_owned()),
        labels: BTreeMap::from([("runnerd.seed".to_owned(), String::new())]),
        entrypoint: Some(vec![
            "/usr/local/sbin/runnerd-seed".to_owned(),
            reseed.min_changes.0.to_string(),
            reseed.max_size.0.to_string(),
        ]),
        jit_config: None,
    };
    // A seed container left by a daemon that died while seeding.
    match docker.remove(&name).await {
        Err(error) if !is_not_found(&error) => return Err(error),
        _ => {}
    }
    let id = docker.start(&spec, reseed.isolation).await?;
    finish_reseed(docker, &id).await
}

/// What a measure container (`image/seed.sh measure`) runs on: the profile's image, its slot 1 and the snapshot,
/// both read-only, and the isolation backend.
#[derive(Debug)]
pub struct Measure<'profile> {
    /// Where the profile's volumes are.
    pub names: &'profile Names,
    /// The profile whose slot 1 is measured.
    pub profile: &'profile str,
    /// The profile's runner image, which holds the seed script.
    pub image: &'profile str,
    /// The systemd slice the measure container runs in.
    pub slice: &'profile str,
    /// How the measure container is isolated, as runners are.
    pub isolation: &'profile dyn Isolation,
}

/// What a measure found: what a reseed would weigh against `caches.reseed_at`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Measured {
    /// Slot 1's changes to the layers hold this many bytes, its Docker Engine's data aside.
    Changed(u64),
    /// The profile's last reseed did not finish (docs/adr/0066): the next one starts over, whatever slot 1 changed.
    Unfinished,
}

/// The memory a measure container may use: it only adds up file sizes.
const MEASURE_MEMORY: ByteSize = ByteSize(256 << 20);

/// Measures what the profile's slot 1 changed (`image/seed.sh measure`), in a container that mounts slot 1's
/// volume and the snapshot read-only, so it may run while the profile's runners do. A measure container an earlier
/// daemon left is removed first.
pub async fn measure(docker: &impl DockerApi, measure: &Measure<'_>) -> Result<Measured, Error> {
    let spec = measure_spec(measure);
    match docker.remove(&spec.name).await {
        Err(error) if !is_not_found(&error) => return Err(error),
        _ => {}
    }
    let id = docker.start(&spec, measure.isolation).await?;
    let output = finish_reseed(docker, &id).await?;
    measured(&output).ok_or_else(|| Error::DockerContainerWaitError {
        error: format!("measuring printed {:?}", output.trim()),
        code: 0,
    })
}

/// The container `measure` runs: `seed.sh measure` on slot 1's volume and the snapshot, both read-only.
pub fn measure_spec(measure: &Measure<'_>) -> RunnerSpec {
    let names = measure.names;
    RunnerSpec {
        name: names.measure(measure.profile),
        image: measure.image.to_owned(),
        profile: measure.profile.to_owned(),
        slice: measure.slice.to_owned(),
        cpus: 1,
        memory: MEASURE_MEMORY,
        env: Vec::new(),
        mounts: vec![
            volume(names.base(measure.profile), "/base", true),
            volume(names.slot(measure.profile, 1), "/workers/1", true),
        ],
        network: Some("none".to_owned()),
        // As a seed container's: a restart finds it beside them (`seed`), and removes it.
        labels: BTreeMap::from([("runnerd.seed".to_owned(), String::new())]),
        entrypoint: Some(vec![
            "/usr/local/sbin/runnerd-seed".to_owned(),
            "measure".to_owned(),
        ]),
        jit_config: None,
    }
}

/// What the output of `image/seed.sh measure` says, in its last line that says it: a warning before it, such as
/// one of `du` about a file a job deleted while it counted, leaves the number as advisory as it is anyway.
fn measured(output: &str) -> Option<Measured> {
    output.lines().rev().map(str::trim).find_map(|line| {
        if line == "the last reseed did not finish" {
            return Some(Measured::Unfinished);
        }
        line.strip_prefix("slot 1 changed ")?
            .strip_suffix(" bytes")?
            .parse()
            .ok()
            .map(Measured::Changed)
    })
}

/// Whether the output of a reseed (`image/seed.sh`) says it replaced the snapshot, and so dropped every slot's own
/// layer changes, rather than left them because slot 1 changed too little.
pub fn seeded(output: &str) -> bool {
    !output.trim_start().starts_with("not seeded")
}

/// Waits for a seed or measure container to exit, removes it, and returns its output. Also takes over a seed
/// container an earlier daemon left running: stopping it between its `rm` and `mv` would lose that snapshot layer.
pub async fn finish_reseed(docker: &impl DockerApi, container: &str) -> Result<String, Error> {
    let result = async {
        let code = docker.wait(container).await?;
        let output = docker.logs(container).await?;
        if code == 0 {
            Ok(output)
        } else {
            Err(Error::DockerContainerWaitError {
                error: format!("seeding exited {code}: {}", output.trim()),
                code,
            })
        }
    }
    .await;
    let removed = docker.remove(container).await;
    let output = result?;
    removed?;
    Ok(output)
}

#[cfg(test)]
mod tests {
    use std::path::Path;
    use std::process::Command;

    use super::docker_budget_gib;
    use crate::testdir::TestDir;

    /// Runs `script` in bash with `image/layers.sh` sourced and `args` as its arguments; returns what it printed.
    #[allow(
        clippy::unwrap_used,
        reason = "a test helper: a script that does not run fails the test"
    )]
    fn with_layers(script: &str, args: &[&Path]) -> String {
        let layers = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../image/layers.sh");
        let output = Command::new("bash")
            .arg("-euc")
            .arg(format!(". \"$0\"; {script}"))
            .arg(layers)
            .args(args)
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "the script exits 0: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8(output.stdout).unwrap()
    }

    #[test]
    #[allow(
        clippy::unwrap_used,
        reason = "a test: a file it cannot write fails it"
    )]
    fn no_credential_a_job_leaves_in_the_cache_layer_reaches_the_slots_next_job() {
        let listed = with_layers("printf '%s\\n' \"${CACHE_SECRETS[@]}\"", &[]);
        let secrets: Vec<&str> = listed.lines().collect();
        for credential in [
            "cargo/credentials.toml",
            "gradle/gradle.properties",
            "gradle/init.d",
            "m2/settings.xml",
            "m2/settings-security.xml",
            "huggingface/token",
        ] {
            assert!(
                secrets.contains(&credential),
                "{credential} is in CACHE_SECRETS: {secrets:?}"
            );
        }
        let dir = TestDir::new("cache-secrets");
        let upper = dir.0.join("upper");
        let write = |path: &str| {
            let path = upper.join(path);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, "token").unwrap();
        };
        // Each as a file, and as a directory a job made there, as Gradle's init.d is.
        for secret in &secrets {
            write(&format!("files/{secret}"));
            write(&format!("dirs/{secret}/held"));
        }
        let kept = [
            "npm/_cacache/index",
            "m2/wrapper/dists/maven.zip",
            "gradle/caches/jars",
        ];
        for path in kept {
            write(&format!("files/{path}"));
        }
        with_layers(
            "drop_cache_secrets \"$1/files\"; drop_cache_secrets \"$1/dirs\"",
            &[&upper],
        );
        for secret in &secrets {
            for copy in ["files", "dirs"] {
                let path = upper.join(copy).join(secret);
                assert!(!path.exists(), "{} is gone", path.display());
            }
        }
        for path in kept {
            assert!(upper.join("files").join(path).exists(), "{path} stays");
        }
    }

    #[test]
    #[allow(
        clippy::unwrap_used,
        reason = "a test: a file it cannot write fails it"
    )]
    fn what_slot_1_changed_counts_its_layers_and_not_its_docker_engines_data() {
        let dir = TestDir::new("layer-changes");
        let state = dir.0.join("state");
        let write = |path: &str, bytes: usize| {
            let path = state.join(path);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, vec![0u8; bytes]).unwrap();
        };
        let changes = || -> u64 {
            with_layers("layer_changes \"$1\"", &[&state])
                .trim()
                .parse()
                .unwrap()
        };
        write("cache/upper/npm/index", 1);
        let before = changes();
        // A job's images in the slot's Docker Engine: a reseed leaves them, so they must not reach `reseed_at`.
        write("docker/overlay2/layer", 1 << 20);
        // Layer work directories hold nothing a reseed copies.
        write("tools/work/scratch", 1 << 20);
        assert_eq!(changes(), before);
        write("tools/upper/node/bin", 100_000);
        write("android/upper/ndk/lib", 200_000);
        let after = changes();
        assert!(
            after >= before + 300_000 && after < before + 400_000,
            "the tools and android layers count: {before} then {after}"
        );
    }

    #[test]
    fn a_slots_docker_budget_is_its_share_between_1_and_20_gib() {
        assert_eq!(docker_budget_gib(100 << 30, 10), 10);
        assert_eq!(
            docker_budget_gib(1 << 40, 4),
            20,
            "a large disk still stops at 20 GiB"
        );
        assert_eq!(
            docker_budget_gib(1 << 30, 13),
            1,
            "a full disk still keeps 1 GiB"
        );
        assert_eq!(docker_budget_gib(1 << 30, 0), 1);
    }
}