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
//! Tests for taking over processes a previous shepherd left running.
//!
//! An adopted sheep keeps its pid, its id, its counters and its last exit, and
//! a dog stays a dog. From the first exit onwards it travels the ordinary path.

use super::adopt_fixtures::{
    AdoptingRunner, adoptable_child, carried, carried_marked, counters, flock_until, respawnable,
    without_handles,
};
use super::*;
use crate::supervisor::error::AdoptError;
use shep_core::config::NormalizeError;
mod disabled;
mod dogs;

/// The wait that would resolve it belonged to a task of the predecessor's,
/// which the `execve` took. Nothing else moves a sheep off `Starting`
/// except its own exit, so a successor that adopts one without re-arming
/// leaves it there with none of `arm_extras`'s watch, cron or memory
/// limits, which fire at the `Online` transition. Nothing here writes
/// `{"kind":"ready"}` and `handle_ready_result` puts a timed-out sheep
/// `Online` anyway, so reaching `Online` at all proves a wait was armed.
#[cfg(unix)]
#[tokio::test(start_paused = true)]
async fn an_adopted_sheep_that_was_still_starting_reaches_online() {
    let dir = tempfile::tempdir().unwrap();
    let (events, _rx) = crate::bus::test_bus(64);
    let sup = SupervisorBuilder::new(AdoptingRunner, test_paths(&dir), events)
        .spawn_adopted(
            vec![without_handles(carried("web", 7, Some(4242), |entry| {
                let mut app = AppConfig::minimal("web", "./srv");
                app.autorestart = false;
                app.wait_ready = true;
                entry.spec = normalize(app).unwrap();
                entry.status = ProcStatus::Starting;
            }))],
            counters(9),
            Vec::new(),
        )
        .expect("a carried flock installs");

    assert_eq!(
        sup.list().await[0].status,
        ProcStatus::Starting,
        "the blob said this sheep was still starting, so the successor must agree"
    );

    flock_until(
        &sup,
        |info| info[0].status == ProcStatus::Online,
        "an adopted sheep left `Starting` must still have a readiness wait over it",
    )
    .await;
}

/// Every row of a listing by id, which is the order these cases name
/// their sheep in.
#[cfg(unix)]
fn by_id(mut info: Vec<ProcessInfo>) -> Vec<ProcessInfo> {
    info.sort_unstable_by_key(|row| row.id);
    info
}

/// A sheep whose pid moved was respawned.
#[cfg(unix)]
#[tokio::test(start_paused = true)]
async fn an_adopted_flock_keeps_its_pids_and_ids() {
    let dir = tempfile::tempdir().unwrap();
    let (events, _rx) = crate::bus::test_bus(64);
    let sup = SupervisorBuilder::new(AdoptingRunner, test_paths(&dir), events)
        .spawn_adopted(
            vec![
                without_handles(carried("web", 7, Some(4242), |_| {})),
                without_handles(carried("api", 8, Some(4243), |_| {})),
            ],
            counters(9),
            Vec::new(),
        )
        .expect("a carried flock installs");

    let info = by_id(sup.list().await);

    assert_eq!(
        info.iter().map(|row| row.id).collect::<Vec<_>>(),
        vec![7, 8],
        "the successor reissued ids instead of carrying them"
    );
    assert_eq!(
        info.iter().map(|row| row.pid).collect::<Vec<_>>(),
        vec![Some(4242), Some(4243)],
        "a sheep whose pid moved was respawned"
    );
}

/// Losing the marker is invisible to a pid check: the dog runs on. What
/// changes is that `matching_ids` stops passing it by, so `shep restart all`
/// reaches it and `shep dogs` loses it entirely.
///
/// A `stop` over a kennel with no sheep in it, so nothing waits on a kill
/// ladder and `NotFound` answers the wildcard. With the marker dropped the
/// wildcard parks on an exit `StandInProc` never delivers.
#[cfg(unix)]
#[tokio::test(start_paused = true)]
async fn an_adopted_dog_keeps_its_marker_and_stays_out_of_a_wildcard() {
    let dir = tempfile::tempdir().unwrap();
    let (events, _rx) = crate::bus::test_bus(64);
    let sup = SupervisorBuilder::new(AdoptingRunner, test_paths(&dir), events)
        .spawn_adopted(
            vec![without_handles(carried(
                "log-rotate",
                7,
                Some(4242),
                |entry| {
                    entry.dog = Some(DogSource::Adopted {
                        grants: None,
                        path: "/opt/bin/shep-log-rotate".to_string(),
                        channel: false,
                        events: Vec::new(),
                    });
                },
            ))],
            counters(9),
            Vec::new(),
        )
        .expect("a carried flock installs");

    let info = sup.list().await;
    assert_eq!(
        info[0].dog,
        Some(DogSource::Adopted {
            grants: None,
            path: "/opt/bin/shep-log-rotate".to_string(),
            channel: false,
            events: Vec::new(),
        }),
        "a dog adopted as an ordinary sheep is one `shep dogs` has lost"
    );

    let swept = tokio::time::timeout(Duration::from_secs(5), sup.stop(ProcessSelector::All))
        .await
        .expect("a wildcard over a flock of nothing but dogs must answer rather than hang");
    assert!(
        matches!(swept, Err(SupervisorError::NotFound)),
        "`all` is the flock, not the kennel: {swept:?}"
    );
}

/// Losing these is silent. `restarts` resetting to zero hands a
/// crash-looping app amnesty it did not earn, and a lost `last_exit`
/// answers "why did it stop" with nothing.
#[cfg(unix)]
#[tokio::test(start_paused = true)]
async fn an_adopted_sheep_keeps_its_counters_and_last_exit() {
    let dir = tempfile::tempdir().unwrap();
    let (events, _rx) = crate::bus::test_bus(64);
    let sup = SupervisorBuilder::new(AdoptingRunner, test_paths(&dir), events)
        .spawn_adopted(
            vec![without_handles(carried("web", 7, Some(4242), |entry| {
                entry.restarts = 4;
                entry.last_exit = Some(ExitInfo {
                    code: Some(2),
                    signal: None,
                });
            }))],
            counters(9),
            Vec::new(),
        )
        .expect("a carried flock installs");

    let info = sup.list().await;

    assert_eq!(info[0].restarts, 4, "the restart count was reset");
    assert_eq!(
        info[0].last_exit,
        Some(ExitInfo {
            code: Some(2),
            signal: None
        }),
        "the last exit was lost"
    );
}

/// An adopted sheep that exits must reach `handle_exited` and be judged by
/// `decide_on_exit` like any other, not sit there `Online` forever.
///
/// A real child and the real runner, since a scripted exit would prove the
/// fake rather than the targeted `waitpid` an adopted pid needs. `/bin/sh`
/// is spawned by `std::process::Command`, so tokio holds no `Child` for it
/// and nothing but the reaper waits on it.
#[cfg(unix)]
#[tokio::test]
#[expect(
    clippy::zombie_processes,
    reason = "the adopted flock's reaper collects this status; a Child::wait would take it first"
)]
async fn an_adopted_sheeps_exit_flows_through_the_ordinary_path() {
    let dir = tempfile::tempdir().unwrap();
    let (events, _rx) = crate::bus::test_bus(64);
    let child = std::process::Command::new("/bin/sh")
        .args(["-c", "sleep 30"])
        .spawn()
        .expect("a test host can spawn a shell");
    let pid = child.id();
    let sup = SupervisorBuilder::new(TokioRunner::new(), test_paths(&dir), events)
        .spawn_adopted(
            vec![without_handles(carried("web", 7, Some(pid), |_| {}))],
            counters(9),
            Vec::new(),
        )
        .expect("a carried flock installs");

    nix::sys::signal::kill(
        nix::unistd::Pid::from_raw(i32::try_from(pid).unwrap()),
        nix::sys::signal::Signal::SIGKILL,
    )
    .expect("the adopted child is signalable");

    let info = flock_until(
        &sup,
        |info| info[0].status == ProcStatus::Stopped,
        "an adopted sheep's exit reaches the actor",
    )
    .await;

    assert_eq!(
        info[0].last_exit,
        Some(ExitInfo {
            code: None,
            signal: Some(9)
        }),
        "the exit must be recorded, not lost"
    );
}

/// [`handover::fitness`] carries a pending delete rather than refusing it,
/// so a sheep whose delete was in flight when the predecessor exec'd must
/// still be deregistered on its next exit, not left registered or
/// respawned. A real child and the real runner: an adopted pid has no
/// `Child` handle, and only the reaper's `Msg::Exited` proves the carried
/// marker reaches `handle_exited`.
#[cfg(unix)]
#[tokio::test]
#[expect(
    clippy::zombie_processes,
    reason = "the adopted flock's reaper collects this status; a Child::wait would take it first"
)]
async fn a_carried_pending_delete_deregisters_on_the_next_exit() {
    let dir = tempfile::tempdir().unwrap();
    let (events, _rx) = crate::bus::test_bus(64);
    let child = std::process::Command::new("/bin/sh")
        .args(["-c", "sleep 30"])
        .spawn()
        .expect("a test host can spawn a shell");
    let pid = child.id();
    let sup = SupervisorBuilder::new(TokioRunner::new(), test_paths(&dir), events)
        .spawn_adopted(
            vec![without_handles(carried_marked(
                "web",
                7,
                Some(pid),
                true,
                None,
                false,
                |_| {},
            ))],
            counters(9),
            Vec::new(),
        )
        .expect("a carried flock installs");

    nix::sys::signal::kill(
        nix::unistd::Pid::from_raw(i32::try_from(pid).unwrap()),
        nix::sys::signal::Signal::SIGKILL,
    )
    .expect("the adopted child is signalable");

    let info = flock_until(
        &sup,
        |info| info.is_empty(),
        "a carried pending delete must deregister the sheep on its next exit, not merely \
         stop it",
    )
    .await;

    assert!(
        info.is_empty(),
        "the deleted sheep must be gone, not just stopped"
    );
}

/// The ladder ran inside the predecessor's sheep task and the `execve`
/// took it, so the sheep reaching a terminal status is what proves the
/// re-arm. `decide_on_exit` reads the marker as `manual_stop`, and this
/// app has `autorestart` on, so a ladder armed without it would kill the
/// sheep and then respawn it. A real child and the real runner: only the
/// reaper's `Msg::Exited` proves a carried marker reaches `handle_exited`.
#[cfg(unix)]
#[tokio::test]
async fn a_carried_manual_stop_stops_the_sheep_instead_of_respawning_it() {
    let dir = tempfile::tempdir().unwrap();
    let (events, _rx) = crate::bus::test_bus(64);
    let pid = adoptable_child("sleep 30");
    let sup = SupervisorBuilder::new(TokioRunner::new(), test_paths(&dir), events)
        .spawn_adopted(
            vec![without_handles(carried_marked(
                "web",
                7,
                Some(pid),
                false,
                Some(PendingManual {
                    kind: ManualKind::Stop,
                    origin: CommandOrigin::Operator,
                }),
                false,
                respawnable(|app| app.autorestart = true),
            ))],
            counters(9),
            Vec::new(),
        )
        .expect("a carried flock installs");

    let info = flock_until(
        &sup,
        |info| info[0].status == ProcStatus::Stopped,
        "a carried manual stop must still stop the sheep after the exec",
    )
    .await;

    assert_eq!(
        info[0].restarts, 0,
        "a stop must not come back as a respawn"
    );
    assert_eq!(
        info[0].last_exit,
        Some(ExitInfo {
            code: None,
            signal: Some(15)
        }),
        "the re-armed ladder starts at its polite rung, not at SIGKILL"
    );
    assert_eq!(info[0].pid, None, "a stopped sheep holds no pid");
}

/// A handover changes no answer, so the successor announces none of the
/// tables its flock carried in. The start after it is the control: the
/// same actor does announce a name it did not inherit.
#[cfg(unix)]
#[tokio::test(start_paused = true)]
async fn an_adopted_flock_announces_none_of_the_tables_it_carried() {
    let dir = tempfile::tempdir().unwrap();
    let (events, mut rx) = crate::bus::test_bus(64);
    let with_jobs = |name: &str| {
        let mut app = AppConfig::minimal(name, "./srv");
        app.autorestart = false;
        let mut table = serde_json::Map::new();
        table.insert("concurrency".to_string(), serde_json::json!(2));
        app.dogs.insert("jobs".to_string(), DogTable::from(table));
        normalize(app).unwrap()
    };
    let sup = SupervisorBuilder::new(AdoptingRunner, test_paths(&dir), events)
        .spawn_adopted(
            vec![without_handles(carried("web", 7, Some(4242), |entry| {
                entry.spec = with_jobs("web");
            }))],
            counters(9),
            Vec::new(),
        )
        .expect("a carried flock installs");

    let started = tokio::time::timeout(Duration::from_secs(5), sup.start(vec![with_jobs("api")]))
        .await
        .expect("a start must answer rather than hang");
    assert!(started.is_ok(), "{started:?}");
    // A fence: the actor announces after each message, so once this
    // answers, the start's announcement is queued.
    let fence = tokio::time::timeout(Duration::from_secs(5), sup.list_checked()).await;
    assert!(matches!(fence, Ok(Ok(_))), "{fence:?}");

    let mut announced = Vec::new();
    while let Ok(event) = rx.try_recv() {
        if let BusEvent::DogSheepSettingsChanged { dog, sheep } = event.to_event() {
            announced.push((dog, sheep));
        }
    }
    assert_eq!(
        announced,
        [("jobs".to_string(), "api".to_string())],
        "web's table crossed the handover and is not news"
    );
}

/// A v0.22 shepherd handed over by a raw signal, past the CLI's check, carries
/// a sheep whose config still sets `sandbox`. Fails if the successor adopts it
/// and so runs a restart of it without the sandbox the operator asked for.
#[cfg(unix)]
#[tokio::test(start_paused = true)]
async fn a_carried_sheep_that_sets_the_removed_sandbox_key_is_refused_not_unsandboxed() {
    let mut blob = serde_json::to_value(carried("boxed", 0, Some(4242), |_| {})).unwrap();
    blob["app"]["sandbox"] = serde_json::json!("box.json");
    let crossed: CarriedSheep = serde_json::from_value(blob).unwrap();

    let dir = tempfile::tempdir().unwrap();
    let (events, _rx) = crate::bus::test_bus(64);
    let refused = SupervisorBuilder::new(AdoptingRunner, test_paths(&dir), events)
        .spawn_adopted(vec![without_handles(crossed)], counters(1), Vec::new())
        .expect_err("a carried sheep that sets the removed key must be refused");

    assert!(
        matches!(
            &refused,
            AdoptError::Spec { sheep, source }
                if sheep == "boxed"
                    && matches!(source, NormalizeError::SandboxKeyRemoved { .. })
        ),
        "{refused:?}"
    );
}