shep-daemon 0.25.2

The supervision engine behind shep: process spawning, restart policy, the log plane, watch and cron restarts, and the RPC server
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
//! Getting a process running, or taking one over.
//!
//! `spawn_fresh` assembles a spec from the credentials and secret view its
//! caller resolved, and hands the runner a process. `install_adopted` is the
//! other door: a survivor of a previous shepherd arrives already running, and
//! has to be fitted back into a slot without being restarted.

use super::*;

impl<R: ProcessRunner> Actor<R> {
    /// The credentials `id`'s next spawn must apply, resolved once if this
    /// entry has never had them resolved.
    ///
    /// An entry resolved at its `Start` answers from the stored value, so a
    /// running app's identity cannot change underneath it. A failed resolution
    /// stores nothing, so a later restart asks again.
    ///
    /// # Errors
    /// - Whatever [`privilege::resolve`] refused this app's `user`/`group`
    ///   for, including a non-root daemon asked to change identity.
    pub(super) fn credentials_for_spawn(
        &mut self,
        id: u32,
    ) -> Result<Option<Credentials>, PrivilegeError> {
        let slot = self
            .sheep
            .get(&id)
            .expect("credentials_for_spawn: unknown id");
        match slot.entry.credentials {
            SpawnIdentity::Resolved(credentials) => Ok(credentials),
            SpawnIdentity::Unresolved => {
                let credentials = privilege::resolve(slot.entry.spec.config())?;
                self.sheep
                    .get_mut(&id)
                    .expect("credentials_for_spawn: the entry was read a moment ago")
                    .entry
                    .credentials = SpawnIdentity::Resolved(credentials);
                Ok(credentials)
            }
        }
    }

    /// Registers one app as a member of the flock without spawning anything.
    ///
    /// The flock is a membership list, not a list of live processes: `stop`
    /// leaves a sheep registered and `Stopped`, `delete` ends membership. One
    /// entry per app rather than one per configured instance, at `instance: 0`,
    /// the slot `start` fills first. Idempotent by name.
    pub(super) fn register_at_rest(&mut self, app: &ResolvedApp) -> ProcessInfo {
        self.register_without_spawning(app, ProcStatus::Stopped, None)
            .into_info()
    }

    /// Registers one dog as a flock member without spawning it.
    ///
    /// Marks it disabled when `disabled` names it, and only when this call is
    /// what registered it: a dog or sheep already holding the name keeps the
    /// mark it has.
    pub(super) fn register_dog_at_rest(
        &mut self,
        app: &ResolvedApp,
        source: DogSource,
        disabled: &BTreeSet<String>,
    ) -> ProcessInfo {
        match self.register_without_spawning(app, ProcStatus::Stopped, Some(source)) {
            Registration::Fresh(info) => {
                if disabled.contains(&info.name) {
                    self.disabled.insert(info.name.clone());
                }
                self.with_mark(info)
            }
            Registration::AlreadyKnown(info) => info,
        }
    }

    /// [`assemble`], then through the sandbox dog when the app holds a
    /// `dogs.sandbox` table.
    ///
    /// The one door every real spawn takes. The preflight in
    /// [`Self::do_start`] reads no program, so it calls [`assemble`] alone.
    ///
    /// # Errors
    ///
    /// - [`AssembleError::DogMissing`]: the app is sandboxed by a dog, and
    ///   that dog is not adopted or is disabled. The command never runs bare.
    /// - Anything [`assemble`] refuses.
    pub(super) fn assemble_for_spawn(
        &self,
        app: &ResolvedApp,
        instance: u32,
        credentials: Option<Credentials>,
        secrets: &SecretView,
    ) -> Result<SpawnSpec, AssembleError> {
        let spec = assemble(app, instance, &self.paths, credentials, secrets)?;
        let config = app.config();
        if !config.dogs.contains_key(SANDBOX_DOG) {
            return Ok(spec);
        }
        match self.dog_binaries.get(SANDBOX_DOG) {
            Some(dog) if !self.disabled.contains(SANDBOX_DOG) => {
                Ok(through_dog(spec, dog, &self.paths.home, &config.name))
            }
            _ => Err(AssembleError::DogMissing {
                dog: SANDBOX_DOG.to_string(),
            }),
        }
    }

    /// The cgroup the sheep `id` in slot `instance` spawns into, or `None` when
    /// this shepherd has no delegated subtree to give it one from.
    pub(super) fn cgroup_for(&self, id: u32, instance: u32) -> Option<PathBuf> {
        #[cfg(target_os = "linux")]
        return self
            .cgroup_base
            .as_deref()
            .map(|base| crate::cgroup::sheep_dir(base, id, instance));
        #[cfg(not(target_os = "linux"))]
        {
            let _ = (id, instance, &self.cgroup_base);
            None
        }
    }

    /// The cgroup the sheep `id` spawns into and the limits to set in it.
    ///
    /// `memory.max` is `Some` only for `memory_enforce = "kernel"`, and that
    /// sheep also has its cgroup's `oom_kill` count read here, before the
    /// spawn, for [`Self::take_oom`] to compare at its exit. `cpu.max` is
    /// `Some` only for `max_cpu_cores`, and `pids.max` only for `max_tasks`.
    ///
    /// # Errors
    /// - [`AssembleError::CgroupUnavailable`] if the sheep wants the kernel to
    ///   enforce a limit and this shepherd has no cgroup to do it in. Never a
    ///   silent fall back to polling or to no cap.
    pub(super) fn cgroup_placement(
        &mut self,
        config: &AppConfig,
        id: u32,
        instance: u32,
    ) -> Result<CgroupPlacement, AssembleError> {
        let cgroup = self.cgroup_for(id, instance);
        let kernel = config.memory_enforce.is_kernel();
        let setting = if kernel {
            "memory_enforce = \"kernel\""
        } else if config.max_cpu_cores.is_some() {
            "max_cpu_cores"
        } else if config.max_tasks.is_some() {
            "max_tasks"
        } else {
            return Ok(CgroupPlacement {
                cgroup,
                memory_max: None,
                cpu_quota: None,
                pids_max: None,
            });
        };
        let Some(dir) = cgroup else {
            return Err(AssembleError::CgroupUnavailable {
                setting,
                reason: self
                    .cgroup_unavailable
                    .clone()
                    .unwrap_or_else(|| "this host has no cgroup v2".to_string()),
            });
        };
        #[cfg(target_os = "linux")]
        if kernel {
            self.oom_baselines
                .insert(id, crate::cgroup::oom_kills(&dir));
        }
        Ok(CgroupPlacement {
            cgroup: Some(dir),
            memory_max: config.max_memory.filter(|_| kernel).map(MemSize::bytes),
            cpu_quota: cpu_quota_of(config),
            pids_max: config.max_tasks,
        })
    }

    /// The secret view one spawn, or one batch of instances, resolves against.
    ///
    /// The store is read here rather than inside [`assemble`], the same way
    /// `credentials` is resolved by the caller: real I/O belongs to the caller.
    /// Read per spawn call rather than cached, so a `shep secret set` between
    /// two calls reaches the second. A store that cannot be read yields an
    /// empty view rather than failing here, and logs why.
    pub(super) fn secret_view(&self, app: &ResolvedApp) -> SecretView {
        let environment = app
            .config()
            .environment
            .clone()
            .unwrap_or_else(|| self.host_environment.clone());
        let store = shep_core::secrets::all(&self.paths.secrets).unwrap_or_else(|error| {
            tracing::warn!(
                path = %self.paths.secrets.display(),
                %error,
                "the secret store could not be read; every reference will refuse"
            );
            BTreeMap::new()
        });
        SecretView::new(environment, store, self.provider_secrets.snapshot())
    }

    /// The field names an operator has overridden for `name`, for a
    /// [`ProcessEntry`] about to be built from scratch.
    ///
    /// Checks a live sibling first and reads the override store only when none
    /// exists, so a scale-up costs no file access. An unreadable store answers
    /// empty rather than refusing: the worst case is a blank CFG cell.
    pub(super) fn overridden_for(&self, name: &str) -> Vec<String> {
        if let Some(slot) = self
            .sheep
            .values()
            .find(|slot| slot.entry.spec.config().name == name)
        {
            return slot.entry.overridden.clone();
        }
        overrides::get(&self.paths.overrides, name)
            .ok()
            .flatten()
            .map(|record| record.fields.keys().cloned().collect())
            .unwrap_or_default()
    }

    /// Registers one app as a flock member in `status`, spawning nothing.
    ///
    /// Registers the status it is handed: [`Self::register_at_rest`] passes
    /// `Stopped`, [`Self::do_start`] passes `Errored` when credential resolution
    /// fails under [`BatchPolicy::PerApp`]. The entry's identity is
    /// [`SpawnIdentity::Unresolved`] whatever the status, so a later `restart`
    /// resolves it. Idempotent by name.
    pub(super) fn register_without_spawning(
        &mut self,
        app: &ResolvedApp,
        status: ProcStatus,
        dog: Option<DogSource>,
    ) -> Registration {
        let name = &app.config().name;
        if let Some(slot) = self
            .sheep
            .values()
            .find(|slot| &slot.entry.spec.config().name == name)
        {
            return Registration::AlreadyKnown(to_info(&slot.entry, &self.smits));
        }

        let overridden = self.overridden_for(name);
        let id = self.next_id;
        self.next_id += 1;
        // Assembled for its log paths only: nothing is spawned, but the entry
        // has to name the files a later `restart` will append to. `describe`,
        // so an unresolvable `{{secret:...}}` still registers: `shep add`
        // exists to land a template whose secrets nobody has filled in yet.
        let described = describe(app, 0, &self.paths, None, &self.secret_view(app));
        let entry = ProcessEntry {
            id,
            spec: app.clone(),
            pending: None,
            pending_reidentifies: false,
            overridden,
            instance: 0,
            status,
            pid: None,
            restarts: 0,
            started_at: None,
            budget: RestartBudget::default(),
            reload: ReloadState::None,
            // `respawn` resolves it, so a restored app comes up under its
            // configured `user`.
            credentials: SpawnIdentity::Unresolved,
            out_file: described.out_file,
            err_file: described.err_file,
            dog,
            last_exit: None,
            spawn_failure: None,
        };
        let info = to_info(&entry, &self.smits);
        self.sheep.insert(id, SheepSlot::new(entry));
        Registration::Fresh(info)
    }

    /// Names the fields in which each app differs from the registered sheep
    /// of the same name, skipping every app that matches and every app the
    /// flock does not have.
    ///
    /// Several instances of one app share one config, so the first slot found
    /// under a name answers for all of them.
    pub(super) fn config_drift(&self, apps: &[ResolvedApp]) -> Vec<SheepDrift> {
        apps.iter()
            .filter_map(|app| {
                let incoming = app.config();
                let stored = self
                    .sheep
                    .values()
                    .find(|slot| slot.entry.spec.config().name == incoming.name)?
                    .entry
                    .spec
                    .config();
                let fields = stored.drifted_fields(incoming);
                (!fields.is_empty()).then(|| SheepDrift::new(&incoming.name, fields))
            })
            .collect()
    }

    /// Registers + spawns one brand-new instance (a fresh id, `restarts: 0`).
    ///
    /// Always inserts a [`SheepSlot`] before returning. A gated app lands
    /// `Starting` with a readiness task armed; an ungated one lands `Online`.
    /// An app is gated by `wait_ready` or a `readiness_probe`, or by its name
    /// being in `gate`. A gated heuristic app waits on `listen_timeout`.
    /// Failure lands `Errored` with no task. `dog` lands on the entry either way.
    pub(super) fn spawn_fresh(
        &mut self,
        app: &ResolvedApp,
        instance: u32,
        credentials: Option<Credentials>,
        secrets: &SecretView,
        dog: Option<DogSource>,
        gate: &BTreeSet<String>,
    ) -> Result<ProcessInfo, String> {
        // Read before the spawn: a scale-up's new instance must show the same
        // overrides its siblings do, not a blank cell until the next load.
        let overridden = self.overridden_for(&app.config().name);
        let id = self.next_id;
        self.next_id += 1;
        let assembled = self
            .assemble_for_spawn(app, instance, credentials, secrets)
            .and_then(|spec| {
                let placement = self.cgroup_placement(app.config(), id, instance)?;
                Ok(SpawnSpec {
                    dog_link: dog.is_some(),
                    listen: self.listen_for(app.config())?,
                    ..placement.into_spec(spec)
                })
            });
        let spec = match assembled {
            Ok(spec) => spec,
            Err(err) => {
                // Registered before the refusal is routed: a sheep that never
                // spawned still has to be visible, and `refuse_spawn` reads the
                // slot it lands in. Its log paths come from `describe`, since
                // `assemble` is what just refused.
                let described = describe(app, instance, &self.paths, credentials, secrets);
                let entry = ProcessEntry {
                    id,
                    spec: app.clone(),
                    pending: None,
                    pending_reidentifies: false,
                    overridden,
                    instance,
                    status: ProcStatus::Errored,
                    pid: None,
                    restarts: 0,
                    started_at: None,
                    budget: RestartBudget::default(),
                    reload: ReloadState::None,
                    credentials: SpawnIdentity::Resolved(credentials),
                    out_file: described.out_file,
                    err_file: described.err_file,
                    dog,
                    last_exit: None,
                    spawn_failure: None,
                };
                self.sheep.insert(id, SheepSlot::new(entry));
                let info = self.refuse_spawn(id, true, &err);
                // A retriable refusal is not a failed start: the sheep is
                // registered, waiting, and comes up on its own once the
                // namespace does, so the batch above must not tear down for
                // it. Only a key nobody has set is reported as a failure.
                return if err.is_retriable() {
                    Ok(info)
                } else {
                    Err(err.to_string())
                };
            }
        };

        // Cloned off the spec, which is the only place that knows whether the
        // app set an explicit `out_file`/`err_file` or takes the `merge_logs`
        // default. Both arms below register an entry.
        let out_file = spec.out_file.clone();
        let err_file = spec.err_file.clone();

        let source = ReadinessSource::of_normalized(app.config());
        // An app a later stage waits on is gated even with no signal of its
        // own: the wait then costs its `listen_timeout`, which is the field's
        // documented fallback, rather than costing nothing.
        let gated =
            !matches!(source, ReadinessSource::Heuristic) || gate.contains(&app.config().name);

        match self.runner.spawn(&spec) {
            Ok((proc, io)) => {
                let pid = proc.pid();
                let status = if gated {
                    ProcStatus::Starting
                } else {
                    ProcStatus::Online
                };
                let entry = ProcessEntry {
                    id,
                    spec: app.clone(),
                    pending: None,
                    pending_reidentifies: false,
                    overridden,
                    instance,
                    status,
                    pid: Some(pid),
                    restarts: 0,
                    started_at: Some(tokio::time::Instant::now()),
                    budget: RestartBudget::default(),
                    reload: ReloadState::None,
                    credentials: SpawnIdentity::Resolved(credentials),
                    out_file,
                    err_file,
                    dog,
                    last_exit: None,
                    spawn_failure: None,
                };
                let info = to_info(&entry, &self.smits);
                let log_ctl = io.log_ctl.clone();
                let to_child = io.to_child.clone();
                let to_stdin = io.to_stdin.clone();
                let pty = io.pty.clone();
                let handles = spawn_sheep_task::<R::Proc>(
                    id,
                    proc,
                    io,
                    app.clone(),
                    self.events.clone(),
                    self.tx.clone(),
                    self.lamb_sweep(),
                );
                let ready_tx = if gated {
                    Some(spawn_readiness_task(
                        id,
                        0,
                        // A `Start` is always a caller's own doing, matching
                        // the `manually: true` the ungated arm below emits.
                        true,
                        source,
                        app.config().listen_timeout.as_duration(),
                        spec_prober(&spec),
                        self.tx.clone(),
                    ))
                } else {
                    None
                };
                self.sheep.insert(
                    id,
                    SheepSlot {
                        ctl: Some(handles.ctl),
                        log_ctl: Some(log_ctl),
                        to_child: Some(to_child),
                        signals: Some(handles.signals),
                        to_stdin: Some(to_stdin),
                        pty,
                        ready_tx,
                        ..SheepSlot::new(entry)
                    },
                );
                self.emit(ProcessEventKind::Start, info.clone(), true);
                // A gated app goes `Online` later, from `handle_ready_result`.
                // `Start` is the bus's first word on this sheep either way.
                if !gated {
                    self.went_online(id, info.clone(), true);
                }
                Ok(info)
            }
            Err(error) => {
                let attempted = match self.runner.preflight(&spec) {
                    Preflight::Doubtful(reason) => reason,
                    _ => match &spec.cwd {
                        Some(cwd) => format!("tried `{}` in {}", spec.program, cwd.display()),
                        None => format!("tried `{}`", spec.program),
                    },
                };
                let message = format!("{error}; {attempted}");
                let entry = ProcessEntry {
                    id,
                    spec: app.clone(),
                    pending: None,
                    pending_reidentifies: false,
                    overridden,
                    instance,
                    status: ProcStatus::Errored,
                    pid: None,
                    restarts: 0,
                    started_at: None,
                    budget: RestartBudget::default(),
                    reload: ReloadState::None,
                    credentials: SpawnIdentity::Resolved(credentials),
                    out_file,
                    err_file,
                    dog,
                    last_exit: None,
                    spawn_failure: Some(format!("{}: {message}", app.config().name)),
                };
                let info = to_info(&entry, &self.smits);
                self.sheep.insert(id, SheepSlot::new(entry));
                self.emit(ProcessEventKind::Errored, info, true);
                Err(message)
            }
        }
    }

    /// Installs one sheep this image inherited rather than started.
    ///
    /// Nothing here spawns, signals or reopens anything, and nothing is
    /// emitted on the bus: the sheep never transitioned. `started_at` cannot
    /// cross the handover, since a `tokio::time::Instant` means nothing
    /// outside the runtime that read it, so it is re-derived via
    /// [`handover::uptime`](crate::handover::uptime).
    ///
    /// # Errors
    ///
    /// - [`AdoptError::Spec`] if the carried config does not normalize.
    /// - [`AdoptError::Runner`] if the runner refused the inherited handles.
    #[cfg(unix)]
    pub(super) fn install_adopted(
        &mut self,
        sheep: AdoptedSheep,
        reaper: &Arc<AdoptedReaper>,
    ) -> Result<(), AdoptError> {
        let AdoptedSheep {
            carried,
            out_pipe,
            err_pipe,
            out_log,
            err_log,
            stdin_pipe,
            channel,
            dog_link,
            pty,
        } = sheep;
        let app = normalize(carried.app().clone()).map_err(|source| AdoptError::Spec {
            sheep: carried.name().to_string(),
            source,
        })?;
        // Reused as resolved, never re-resolved: the value was pinned at the
        // predecessor's first spawn, so a passwd change cannot move a running
        // app's identity.
        let identity = carried.credentials();
        let credentials = identity.credentials();
        // Assembled for its log paths only: the entry has to name the files
        // this sheep is writing to, and a later rotation reopens them by path.
        // `describe`, so a store that moved under a running flock costs a log
        // path its rendering rather than costing the adoption a live sheep.
        let described = describe(
            &app,
            carried.instance(),
            &self.paths,
            credentials,
            &self.secret_view(&app),
        );
        let id = carried.id();
        // The predecessor's reading is gone with it, so the count it carries
        // now is the baseline. Anything it killed before the handover is not
        // charged to this life.
        #[cfg(target_os = "linux")]
        if app.config().memory_enforce.is_kernel()
            && let Some(dir) = self.cgroup_for(id, carried.instance())
        {
            self.oom_baselines
                .insert(id, crate::cgroup::oom_kills(&dir));
        }
        let status = carried.status();
        // `None` for a blob written before this daemon carried a swap; see
        // `CarriedSheep::reload`.
        let reload = carried.reload().unwrap_or(ReloadState::None);
        // Read here rather than at either `SheepSlot` literal below: the
        // readiness re-arm between them has to see it, since a `ready_failed`
        // instance is `Starting` by construction and must not get a wait.
        let ready_failed = carried.ready_failed().unwrap_or(false);
        // The mark is the app's, so it is set before the slot lands: nothing
        // the successor does to this instance can respawn it in between.
        if carried.disabled() == Some(true) {
            self.disabled.insert(app.config().name.clone());
        }
        // Restored as a pair with its reset flag: a parked config promoted
        // without it comes up on the identity the flag exists to replace.
        // A parked config that fails to normalize is dropped and warned about
        // rather than refusing the adoption, which would strand a live flock.
        let pending = carried
            .pending()
            .and_then(|parked| match normalize(parked.clone()) {
                Ok(app) => Some(app),
                Err(source) => {
                    tracing::warn!(
                        sheep = carried.name(),
                        %source,
                        "a config this sheep was owed did not survive the handover: this daemon \
                         will not accept it, so the change is gone and the file must be loaded \
                         again"
                    );
                    None
                }
            });
        // `false` when the config was dropped just above, and for a blob
        // written before the flag existed: nothing left to promote.
        let pending_reidentifies =
            pending.is_some() && carried.pending_reidentifies().unwrap_or(false);
        let mut entry = ProcessEntry {
            id,
            spec: app.clone(),
            pending,
            pending_reidentifies,
            instance: carried.instance(),
            status,
            pid: carried.pid(),
            restarts: carried.restarts(),
            // Filled in below for a sheep with a process, and left `None` for
            // one without, which is what a stopped slot carries anyway.
            started_at: None,
            // The count is carried, since losing it would hand a crash-looping
            // app amnesty, but the window it is counted over is wall-clock this
            // image did not observe.
            budget: RestartBudget::default(),
            // Restored: it decides where this instance's next exit goes.
            // `handle_exited` routes a `Drainee` to `reap_drainee` and reads a
            // `Replacement` out of the swap, while `None` takes
            // `decide_on_exit`.
            reload,
            credentials: identity,
            out_file: described.out_file.clone(),
            err_file: described.err_file.clone(),
            // Restored: it is the marker that keeps a dog out of the flock.
            // `matching_ids` passes a marked entry over for every selector but
            // an exact one, so dropping it would put the dog in `shep flock`.
            // `None` for a blob written before this daemon carried a dog.
            dog: carried.dog().cloned(),
            last_exit: carried.last_exit(),
            spawn_failure: carried.spawn_failure().map(str::to_string),
            // Not carried by `CarriedSheep`: a handover installs one sheep at a
            // time with no live sibling to ask, so this is one store read.
            overridden: self.overridden_for(&app.config().name),
        };

        let Some(pid) = carried.pid() else {
            // Registered and not running: adopting an absent process would ask
            // the reaper to wait on a pid this image never had.
            self.sheep.insert(
                id,
                SheepSlot {
                    // A marker is only claimed against a sheep with a live
                    // task: there is no ladder here to re-arm and no
                    // `Msg::Exited` coming to clear one.
                    manual: None,
                    // Restored: it needs no task to act on it, and the exit
                    // that consumes it is this slot's next spawn's.
                    pending_delete: carried.pending_delete().unwrap_or(false),
                    epoch: carried.epoch(),
                    // Restored: it needs no task to act on it, and `respawn`
                    // clears it at the spawn that answers it.
                    ready_failed,
                    // Restored verbatim so a second reload during the same
                    // wait does not start the delay over: the re-arm below
                    // computes a fresh timer from this absolute moment.
                    restart_due: carried.restart_due(),
                    ..SheepSlot::new(entry)
                },
            );
            // Nothing but this raises `Msg::RestartDue`, so a carried
            // `WaitingRestart` sheep would sit there for the daemon's life.
            // The timer is re-armed off the carried deadline, so the successor
            // sleeps out what is left of `restart_delay`.
            if status == ProcStatus::WaitingRestart {
                let delay = crate::backoff::adopted_restart_delay(
                    app.config(),
                    carried.restart_due(),
                    SystemTime::now(),
                );
                self.schedule_restart(id, carried.epoch(), delay);
            }
            return Ok(());
        };

        // A link on a sheep that is no dog is the one a dog launched it
        // holding.
        let launch_dog =
            (dog_link.is_some() && carried.dog().is_none()).then(|| SANDBOX_DOG.to_string());
        let (proc, io) = self
            .runner
            .adopt(AdoptSpec {
                name: carried.name().to_string(),
                pid,
                out_file: described.out_file.clone(),
                err_file: described.err_file.clone(),
                out_pipe,
                err_pipe,
                out_log,
                err_log,
                log_timestamps: described.log_timestamps,
                leader_only_stop: described.leader_only_stop,
                stdin_pipe,
                channel,
                dog_link,
                pty,
                dog_topics: carried.dog_topics().map(<[String]>::to_vec),
                launch_dog,
                reaper: Arc::clone(reaper),
            })
            .map_err(|source| AdoptError::Runner {
                sheep: carried.name().to_string(),
                source,
            })?;
        // Off the proc rather than off the blob, as both spawn paths take it:
        // the pid this entry reports has to be the one the runner will signal.
        entry.pid = Some(proc.pid());
        // Load-bearing: `handle_exited` reads `started_at` to tell a real exit
        // from a duplicate `Msg::Exited`, and an entry without it would sit
        // `Online` forever after its process died. Derived from the operating
        // system, since a `tokio::time::Instant` cannot cross the exec.
        entry.started_at = Some(crate::handover::uptime::started_at_of(proc.pid()));
        // `manually` reaches only the `Online` event's flag: `false` for a
        // `Starting` sheep this image did not spawn, `true` for a carried
        // `Replacement`, which is an operator's reload.
        let manually = matches!(reload, ReloadState::Replacement);
        // A carried `Starting` sheep has readiness unresolved and nothing else
        // moves it off, so `listen_timeout` starts again. `ready_failed` is the
        // exception: its verdict already stands, and a fresh wait would clear
        // the flag a rollback needs.
        let ready_tx = (status == ProcStatus::Starting && !ready_failed).then(|| {
            let source = ReadinessSource::of_normalized(app.config());
            spawn_readiness_task(
                id,
                carried.epoch(),
                manually,
                source,
                app.config().listen_timeout.as_duration(),
                spec_prober(&described),
                self.tx.clone(),
            )
        });
        let log_ctl = io.log_ctl.clone();
        let to_child = io.to_child.clone();
        let to_stdin = io.to_stdin.clone();
        let pty = io.pty.clone();
        let handles = spawn_sheep_task::<R::Proc>(
            id,
            proc,
            io,
            app.clone(),
            self.events.clone(),
            self.tx.clone(),
            self.lamb_sweep(),
        );
        self.sheep.insert(
            id,
            SheepSlot {
                ctl: Some(handles.ctl),
                log_ctl: Some(log_ctl),
                to_child: Some(to_child),
                signals: Some(handles.signals),
                to_stdin: Some(to_stdin),
                pty,
                // Re-claimed below rather than written in directly: restoring
                // the marker is only half of what a carried one means.
                manual: None,
                pending_delete: carried.pending_delete().unwrap_or(false),
                epoch: carried.epoch(),
                ready_tx,
                // Restored: `reload_eligible` reads it beside the status, so a
                // rollback reload can replace an instance that never reached
                // `Online`.
                ready_failed,
                // Restored verbatim, though always `None` in practice: a sheep
                // with a pid is not `WaitingRestart`.
                restart_due: carried.restart_due(),
                ..SheepSlot::new(entry)
            },
        );
        // The ladder that would kill a carried `manual` sheep went with the
        // predecessor's image, so it runs again from the polite rung. The cap
        // comes off the role: a carried drainee was asked under
        // `graceful_timeout`, the rest under `kill_timeout`.
        if let Some(manual) = carried.manual() {
            let cap = match reload {
                ReloadState::Drainee { .. } => LadderCap::Drain,
                ReloadState::None | ReloadState::Replacement => LadderCap::Stop,
            };
            self.claim_manual(id, manual, cap);
        }
        // A watch, a schedule or a memory limit this image did not arm is one
        // the app quietly stops having.
        if status == ProcStatus::Online {
            self.arm_extras(id);
        }
        Ok(())
    }

    /// Restores the reload jobs the blob carried, and re-arms every timer
    /// each of them was waiting on.
    ///
    /// Runs after the whole flock is installed, not per sheep: a job names two
    /// entries and reads an app's timings off one of them.
    /// [`Self::arm_reload_deadline`] is the only thing that removes a
    /// [`ReloadJob`] nothing else can finish; a job naming no entry is dropped.
    #[cfg(unix)]
    pub(super) fn install_carried_reloads(&mut self, reloads: Vec<CarriedReload>) {
        for carried in reloads {
            let CarriedReload {
                app,
                queue,
                mode,
                swap,
            } = carried;
            // The replacement first, as it is the half that exists in every
            // phase but `DrainFirst`. This is about which one is registered: a
            // serial reload deregisters its drainee at `ReapOld`.
            let anchor = swap
                .new_id
                .filter(|id| self.sheep.contains_key(id))
                .or_else(|| self.sheep.contains_key(&swap.old_id).then_some(swap.old_id));
            let Some(anchor) = anchor else {
                tracing::warn!(
                    name = app,
                    old_id = swap.old_id,
                    new_id = swap.new_id,
                    "a carried reload named no instance this shepherd was given, so it was \
                     dropped rather than left unfinishable"
                );
                continue;
            };
            self.reloads.insert(
                app.clone(),
                ReloadJob {
                    queue: queue.into_iter().collect(),
                    mode,
                    swap,
                    // Overwritten by the arm below, the one site that stamps a
                    // live watchdog.
                    deadline: 0,
                },
            );
            self.arm_reload_deadline(&app, anchor);
            if swap.phase == ReloadPhase::Verify
                && let Some(new_id) = swap.new_id
                && let Some(source) = self.post_drain_probe(new_id, mode)
            {
                self.spawn_verify_task(&app, new_id, source);
            }
        }
    }
}

/// Where a spawn's cgroup is and what to set in it, from
/// [`Actor::cgroup_placement`].
pub(super) struct CgroupPlacement {
    cgroup: Option<PathBuf>,
    memory_max: Option<u64>,
    cpu_quota: Option<u64>,
    pids_max: Option<u32>,
}

impl CgroupPlacement {
    /// `spec` joining this cgroup under these limits.
    pub(super) fn into_spec(self, spec: SpawnSpec) -> SpawnSpec {
        SpawnSpec {
            cgroup: self.cgroup,
            memory_max: self.memory_max,
            cpu_quota: self.cpu_quota,
            pids_max: self.pids_max,
            ..spec
        }
    }
}

/// `config`'s `max_cpu_cores` as the `cpu.max` quota that spells it, `None` off
/// Linux, where `normalize` has already refused the key.
pub(super) fn cpu_quota_of(config: &AppConfig) -> Option<u64> {
    #[cfg(target_os = "linux")]
    return config.max_cpu_cores.map(crate::cgroup::cpu_quota);
    #[cfg(not(target_os = "linux"))]
    {
        let _ = config;
        None
    }
}