runnerd-core 0.1.5

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
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
//! 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 std::time::Duration;

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

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

pub mod mirror;

/// The prefix of the names of what the daemon makes in Docker (`Names`).
pub const PREFIX: &str = "runnerd";

/// 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()
    }

    /// Whether `volume` is a slot's volume of any profile, configured now or not: `<prefix>-<profile>-slot-<N>`.
    /// A prefix that is another's start, as a test's `runnerd-test-…` is `runnerd`'s, matches the other's too.
    pub fn is_slot(&self, volume: &str) -> bool {
        volume
            .strip_prefix(&format!("{}-", self.prefix))
            .and_then(|rest| rest.rsplit_once("-slot-"))
            .is_some_and(|(profile, slot)| {
                !profile.is_empty()
                    && !slot.is_empty()
                    && slot.bytes().all(|byte| byte.is_ascii_digit())
            })
    }

    /// The prefix every volume of runnerd's starts with, with its dash.
    pub fn volume_prefix(&self) -> String {
        format!("{}-", self.prefix)
    }

    /// The container that starts a slot's layers over after a host crash, when its volume could not be emptied.
    pub fn start_over(&self) -> String {
        format!("{}-start-over", self.prefix)
    }

    /// 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)
    }

    /// The container that repairs the mirror's storage before the mirror starts.
    pub fn mirror_repair(&self) -> String {
        format!("{}-mirror-repair", 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. It keeps no
/// blob descriptor cache: the proxy's expiry of one repository's copy of a blob deletes the blob other repositories
/// still link to, and the cache would go on answering their pulls with no data (docs/adr/0144).
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(),
            format!("{}=", mirror::DESCRIPTOR_CACHE_ENV),
        ]),
        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, after removing the links in its storage whose blob is gone (`mirror::Repair`),
/// which a failed repair does not hold back.
pub async fn mirror_up(
    docker: &impl DockerApi,
    names: &Names,
    mirror: &config::Mirror,
    slice: &str,
) -> Result<mirror::MirrorUp, Error> {
    match docker.inspect(&names.mirror()).await {
        Ok(state) if state.running => return Ok(mirror::MirrorUp::Running),
        // 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?;
    }
    let repair = mirror::repair(docker, names, slice).await;
    docker
        .run(&names.mirror(), mirror_body(names, mirror, slice))
        .await?;
    Ok(mirror::MirrorUp::Started(repair))
}

/// Stops the mirror, and removes a repair container a killed daemon left on its storage, which would keep the
/// volume from being removed; its storage stays.
pub async fn mirror_down(docker: &impl DockerApi, names: &Names) -> Result<(), Error> {
    for name in [names.mirror(), names.mirror_repair()] {
        match docker.remove(&name).await {
            Err(error) if !is_not_found(&error) => return Err(error),
            _ => {}
        }
    }
    Ok(())
}

/// 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;

/// What `empty_volumes` came to.
#[derive(Debug, Default)]
pub struct Cleared {
    /// The volumes it removed.
    pub removed: Vec<String>,
    /// The volumes it left, each with why.
    pub refused: Vec<Refusal>,
}

/// A volume `empty_volumes` left.
#[derive(Debug)]
pub struct Refusal {
    /// The volume's name.
    pub volume: String,
    /// Why, as the log says it.
    pub why: String,
    /// What kept it.
    pub cause: Kept,
}

/// What kept a volume `empty_volumes` did not remove.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kept {
    /// A running container mounts it.
    Runs,
    /// A stopped container that is not runnerd's mounts it.
    NotRunnerds,
    /// Docker's error, such as an outage, a 5xx or a timeout.
    Docker,
}

impl Refusal {
    /// Whether a container mounts it that `empty_volumes` leaves: a running one, or one that is not runnerd's.
    pub fn held(&self) -> bool {
        self.cause != Kept::Docker
    }
}

/// Removes each of `volumes` that exists, after the containers of runnerd's that mount it and no longer run, such as
/// a runner or a seed a crash stopped: Docker refuses to remove a volume a container mounts, even a stopped one. It
/// leaves a volume a running container mounts, or a container that is not runnerd's, and removes no such container.
pub async fn empty_volumes(docker: &impl DockerApi, volumes: &[String]) -> Cleared {
    let mut emptied = Cleared::default();
    for volume in volumes {
        match empty_volume(docker, volume).await {
            Ok(()) => emptied.removed.push(volume.clone()),
            Err(refusal) => emptied.refused.push(refusal),
        }
    }
    emptied
}

/// Removes `volume`, if it exists, once nothing of runnerd's mounts it.
async fn empty_volume(docker: &impl DockerApi, volume: &str) -> Result<(), Refusal> {
    let refused = |why: String, cause: Kept| Refusal {
        volume: volume.to_owned(),
        why,
        cause,
    };
    let failed = |error: Error| refused(error.to_string(), Kept::Docker);
    for holder in docker.holders(volume).await.map_err(failed)? {
        let name = if holder.name.is_empty() {
            &holder.id
        } else {
            &holder.name
        };
        if holder.running {
            return Err(refused(
                format!("container {name} mounts it and runs"),
                Kept::Runs,
            ));
        }
        if !holder
            .labels
            .keys()
            .any(|label| label.starts_with("runnerd."))
        {
            return Err(refused(
                format!("container {name}, which is not runnerd's, mounts it"),
                Kept::NotRunnerds,
            ));
        }
        match docker.remove(&holder.id).await {
            Err(error) if !is_not_found(&error) => {
                return Err(refused(
                    format!("container {name}, which mounts it, cannot be removed: {error}"),
                    Kept::Docker,
                ));
            }
            _ => {}
        }
    }
    docker.remove_volume(volume).await.map_err(failed)
}

/// 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 its tools layer, then
/// its Android layer, over from the image until the rest fits, and every layer when that is not enough, each with
/// every slot's changes to it (docs/adr/0065, docs/adr/0152); 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 = match docker.start(&spec, reseed.isolation).await {
        Ok(id) => id,
        // A start whose answer was lost may have left the container running: it ends only once Docker says so.
        Err(failed) => match failed.container {
            Some(container) if failed.may_have_run => {
                let _ = finish_reseed(docker, &container).await;
                return Err(failed.error);
            }
            _ => return Err(failed.error),
        },
    };
    finish_reseed(docker, &id).await
}

/// What `start_layers_over` runs on: a slot's volume a host crash may have torn and the guard could not empty, and
/// the image, slice and isolation of a runner.
#[derive(Debug)]
pub struct StartOver<'volume> {
    /// Where runnerd's volumes are.
    pub names: &'volume Names,
    /// The slot's volume.
    pub volume: &'volume str,
    /// A runner image, for its shell: any profile's will do.
    pub image: &'volume str,
    /// The systemd slice the container runs in.
    pub slice: &'volume str,
    /// How the container is isolated, as runners are.
    pub isolation: &'volume dyn Isolation,
}

/// The memory the container of `start_layers_over` may use: it only deletes.
const START_OVER_MEMORY: ByteSize = ByteSize(256 << 20);

/// Deletes everything in a slot's volume but its Docker Engine's store (`image/layers.sh`'s `DOCKER_DATA_ROOT`), in
/// a container that mounts it: its layers' changes and work directories, and the record of the snapshot they were
/// made against. The slot's next runner starts them over from the snapshot, and a reseed finds nothing of slot 1's
/// to copy (ADR 0142). For a volume the guard could not remove, as another container holds it: Docker lets a second
/// container mount it. A container an earlier daemon left is removed first.
pub async fn start_layers_over(
    docker: &impl DockerApi,
    start: &StartOver<'_>,
) -> Result<(), Error> {
    let name = start.names.start_over();
    match docker.remove(&name).await {
        Err(error) if !is_not_found(&error) => return Err(error),
        _ => {}
    }
    let spec = RunnerSpec {
        name: name.clone(),
        image: start.image.to_owned(),
        profile: String::new(),
        slice: start.slice.to_owned(),
        cpus: 1,
        memory: START_OVER_MEMORY,
        env: Vec::new(),
        mounts: vec![volume(start.volume.to_owned(), "/state", false)],
        network: Some("none".to_owned()),
        labels: BTreeMap::from([("runnerd.seed".to_owned(), String::new())]),
        entrypoint: Some(
            [
                "find",
                "/state",
                "-mindepth",
                "1",
                "-maxdepth",
                "1",
                "!",
                "-name",
                "docker",
                "-exec",
                "rm",
                "-rf",
                "{}",
                "+",
            ]
            .map(str::to_owned)
            .to_vec(),
        ),
        jit_config: None,
    };
    let id = docker.start(&spec, start.isolation).await?;
    // Once: the tick awaits it. A container Docker cannot say ended is an error, so the caches stay torn, and the
    // next try removes it before it starts another.
    match finish_once(docker, &id).await {
        Finished::Ended(result) => result.map(|_| ()),
        Finished::Unconfirmed(error) => Err(error),
    }
}

/// 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")
}

/// How long `finish_reseed` waits before it asks Docker again about a container it could not tell had ended.
const ASK_AGAIN: Duration = Duration::from_secs(10);

/// Waits for a seed or measure container to exit, removes it, and returns its output, in a background task. Also takes
/// over a seed container an earlier daemon left running: stopping it between its `rm` and `mv` would lose that
/// snapshot layer. It returns only once Docker said the container exited or is gone: one whose wait and removal both
/// failed, as when the Engine's API went away, may still be rewriting the snapshot or a slot's layers, so it asks
/// again every `ASK_AGAIN`, and the profile reseeds until then (docs/adr/0152). Never awaited in the tick.
pub async fn finish_reseed(docker: &impl DockerApi, container: &str) -> Result<String, Error> {
    loop {
        match finish_once(docker, container).await {
            Finished::Ended(result) => return result,
            Finished::Unconfirmed(error) => {
                warn!(
                    "cannot tell whether {container} ended, so what it writes stays held: asking again in {}s: \
                     {error}",
                    ASK_AGAIN.as_secs()
                );
                tokio::time::sleep(ASK_AGAIN).await;
            }
        }
    }
}

/// What one attempt of `finish_reseed` found.
enum Finished {
    /// The container exited or is gone: its output, or why there is none.
    Ended(Result<String, Error>),
    /// Docker said neither: why its removal failed.
    Unconfirmed(Error),
}

/// Waits for the container once and removes it.
async fn finish_once(docker: &impl DockerApi, container: &str) -> Finished {
    let waited = docker.wait(container).await;
    let exited = waited.is_ok();
    let result = async {
        let code = waited?;
        let output = docker.logs(container).await?;
        if code == 0 {
            Ok(output)
        } else {
            Err(Error::DockerContainerWaitError {
                error: format!("seeding exited {code}: {}", output.trim()),
                code,
            })
        }
    }
    .await;
    match docker.remove(container).await {
        Err(error) if is_not_found(&error) => Finished::Ended(result),
        Err(error) if !exited => Finished::Unconfirmed(error),
        Err(error) => Finished::Ended(result.and(Err(error))),
        Ok(()) => Finished::Ended(result),
    }
}

#[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);
    }
}