shep-daemon 0.22.0

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
//! Blobs an older image wrote, and the keys they do not carry.
//!
//! Every case builds a current blob, removes one key from its JSON, and
//! asserts both that the key survives when it is there and that its absence
//! loads as the documented default. An `Option` field that stopped loading
//! from an absent key would force [`VERSION`](super::super::VERSION) up, so
//! these are the closest thing the handover has to a wire-compatibility
//! suite.

use std::time::SystemTime;

use shep_core::protocol::DogSource;
use shep_core::status::ProcStatus;

use super::{handover_over, sample_handover};
use crate::entry::{ProcessEntry, ReloadState};
use crate::handover::fixtures::{carried, entry_fixture, fds_at};
use crate::handover::{CarriedSheep, Handover};
use crate::supervisor::{
    CarriedReload, CommandOrigin, ManualKind, PendingManual, ReloadMode, ReloadPhase, ReloadSwap,
};
use crate::testing::app_with;

#[test]
fn a_spawn_refusal_survives_a_handover_and_old_blobs_omit_it() {
    let mut entry = entry_fixture(|_| {});
    entry.status = ProcStatus::Errored;
    entry.pid = None;
    entry.spawn_failure = Some("kelpie: spawn refused".to_string());
    let mut value = serde_json::to_value(handover_over(&entry)).unwrap();
    assert_eq!(value["sheep"][0]["spawn_failure"], "kelpie: spawn refused");
    let loaded = Handover::load_value(value.clone()).unwrap();
    assert_eq!(
        loaded.sheep()[0].spawn_failure(),
        Some("kelpie: spawn refused")
    );

    value["sheep"][0]
        .as_object_mut()
        .unwrap()
        .remove("spawn_failure");
    let older = Handover::load_value(value).unwrap();
    assert_eq!(older.sheep()[0].spawn_failure(), None);
}

#[test]
fn a_blob_written_before_stdin_was_carried_still_loads() {
    let mut value = serde_json::to_value(sample_handover()).unwrap();
    let fds = value["sheep"][0]["fds"]
        .as_object_mut()
        .expect("a carried sheep names its descriptors");
    assert!(
        fds.remove("stdin").is_some(),
        "the field this case removes must be there to remove"
    );

    let loaded = Handover::load_value(value).expect("an older blob must still load");

    assert_eq!(loaded.sheep[0].fds.stdin, None);
    assert_eq!(
        loaded.sheep[0].fds.out_pipe,
        sample_handover().sheep[0].fds.out_pipe,
        "the other five are unchanged by the one that was absent"
    );
}

#[test]
fn a_blob_written_before_the_channel_was_carried_still_loads() {
    let mut value = serde_json::to_value(sample_handover()).unwrap();
    let fds = value["sheep"][0]["fds"]
        .as_object_mut()
        .expect("a carried sheep names its descriptors");
    assert!(
        fds.remove("channel").is_some(),
        "the field this case removes must be there to remove"
    );

    let loaded = Handover::load_value(value).expect("an older blob must still load");

    assert_eq!(loaded.sheep[0].fds.channel, None);
    assert_eq!(
        loaded.sheep[0].fds.stdin,
        sample_handover().sheep[0].fds.stdin,
        "the other five are unchanged by the one that was absent"
    );
}

#[test]
fn a_blob_written_before_pending_delete_was_carried_still_loads() {
    let mut value = serde_json::to_value(sample_handover()).unwrap();
    let sheep = value["sheep"][0]
        .as_object_mut()
        .expect("a carried sheep is an object");
    assert!(
        sheep.remove("pending_delete").is_some(),
        "the field this case removes must be there to remove"
    );

    let loaded = Handover::load_value(value).expect("an older blob must still load");

    assert_eq!(loaded.sheep[0].pending_delete(), None);
    assert_eq!(
        loaded.sheep[0].id(),
        sample_handover().sheep[0].id(),
        "the rest of the row is unchanged by the one field that was absent"
    );
}

#[test]
fn a_sheep_with_nothing_parked_carries_neither_parking_key() {
    let entry = entry_fixture(|_| {});
    assert!(
        entry.pending.is_none(),
        "fixture check: this case is about a sheep with nothing parked"
    );
    let blob = handover_over(&entry);

    let round_tripped = Handover::load_value(serde_json::to_value(&blob).unwrap())
        .expect("a blob this daemon wrote must load");
    assert_eq!(round_tripped.sheep[0].pending(), None);
    assert_eq!(
        round_tripped.sheep[0].pending_reidentifies(),
        None,
        "a reset flag with no parked config to apply it to is a key that means nothing"
    );
}

#[test]
fn a_blob_written_before_pending_was_carried_still_loads() {
    let mut entry = entry_fixture(|_| {});
    entry.pending = Some(app_with("web", |app| {
        app.env.insert("MODE".to_owned(), "blue".to_owned());
    }));
    entry.pending_reidentifies = true;
    let blob = handover_over(&entry);

    // A blob that has the two keys carries both.
    let round_tripped = Handover::load_value(serde_json::to_value(&blob).unwrap())
        .expect("a blob this daemon wrote must load");
    assert_eq!(
        round_tripped.sheep[0]
            .pending()
            .expect("the parked config crosses the exec")
            .env
            .get("MODE")
            .map(String::as_str),
        Some("blue")
    );
    assert_eq!(
        round_tripped.sheep[0].pending_reidentifies(),
        Some(true),
        "and its reset flag crosses with it: a config that arrived without one would \
         promote on the identity the flag exists to replace"
    );

    // An older blob, which has neither key.
    let mut value = serde_json::to_value(&blob).unwrap();
    let sheep = value["sheep"][0]
        .as_object_mut()
        .expect("a carried sheep is an object");
    for key in ["pending", "pending_reidentifies"] {
        assert!(
            sheep.remove(key).is_some(),
            "the field this case removes must be there to remove: {key}"
        );
    }

    let loaded = Handover::load_value(value).expect("an older blob must still load");

    assert_eq!(loaded.sheep[0].pending(), None);
    assert_eq!(loaded.sheep[0].pending_reidentifies(), None);
    assert_eq!(
        loaded.sheep[0].id(),
        blob.sheep[0].id(),
        "the rest of the row is unchanged by the two fields that were absent"
    );
}

#[test]
fn a_blob_written_before_a_manual_marker_was_carried_still_loads() {
    let marker = PendingManual {
        kind: ManualKind::Restart,
        origin: CommandOrigin::Automatic,
    };
    let mut blob = sample_handover();
    blob.sheep[0] = CarriedSheep::from_entry(
        &entry_fixture(|_| {}),
        7,
        fds_at(11),
        false,
        Some(marker),
        false,
        None,
    );
    let value = serde_json::to_value(&blob).unwrap();

    assert_eq!(
        Handover::load_value(value.clone())
            .expect("a current blob loads")
            .sheep[0]
            .manual(),
        Some(marker),
        "a marker on the wire must come back whole, kind and origin both"
    );

    let mut older = value;
    let sheep = older["sheep"][0]
        .as_object_mut()
        .expect("a carried sheep is an object");
    assert!(
        sheep.remove("manual").is_some(),
        "the field this case removes must be there to remove"
    );

    let loaded = Handover::load_value(older).expect("an older blob must still load");

    assert_eq!(loaded.sheep[0].manual(), None);
    assert_eq!(
        loaded.sheep[0].id(),
        blob.sheep[0].id(),
        "the rest of the row is unchanged by the one field that was absent"
    );
}

/// Both keys an older blob lacks: `sheep[].reload` and the top-level
/// `reloads`. The job is asserted as well as the marker.
#[test]
fn a_blob_written_before_a_swap_was_carried_still_loads() {
    let job = CarriedReload {
        app: "web".to_owned(),
        queue: vec![11, 12],
        mode: ReloadMode::Serial,
        swap: ReloadSwap {
            old_id: 1,
            new_id: Some(9),
            phase: ReloadPhase::AwaitReady,
        },
    };
    let mut blob = sample_handover();
    let mut drainee = entry_fixture(|_| {});
    drainee.reload = ReloadState::Drainee { new_id: Some(9) };
    blob.sheep[0] = carried(&drainee);
    blob.reloads = Some(vec![job.clone()]);
    let value = serde_json::to_value(&blob).unwrap();

    let current = Handover::load_value(value.clone()).expect("a current blob loads");
    assert_eq!(
        current.sheep[0].reload(),
        Some(ReloadState::Drainee { new_id: Some(9) }),
        "the marker on the wire must come back whole, role and linked id both"
    );
    assert_eq!(
        current.reloads(),
        &[job],
        "the job must come back whole: queue, mode and every field of the swap"
    );

    let mut older = value;
    let object = older.as_object_mut().expect("a blob is an object");
    assert!(
        object.remove("reloads").is_some(),
        "the field this case removes must be there to remove"
    );
    let sheep = older["sheep"][0]
        .as_object_mut()
        .expect("a carried sheep is an object");
    assert!(
        sheep.remove("reload").is_some(),
        "the field this case removes must be there to remove"
    );

    let loaded = Handover::load_value(older).expect("an older blob must still load");

    assert_eq!(loaded.sheep[0].reload(), None);
    assert!(loaded.reloads().is_empty());
    assert_eq!(
        loaded.sheep[0].id(),
        blob.sheep[0].id(),
        "the rest of the row is unchanged by the two fields that were absent"
    );
}

#[test]
fn a_blob_written_before_ready_failed_was_carried_still_loads() {
    let mut blob = sample_handover();
    blob.sheep[0] = CarriedSheep::from_entry(
        &entry_fixture(|_| {}),
        7,
        fds_at(11),
        false,
        None,
        true,
        None,
    );
    let value = serde_json::to_value(&blob).unwrap();

    assert_eq!(
        Handover::load_value(value.clone())
            .expect("a current blob loads")
            .sheep[0]
            .ready_failed(),
        Some(true),
        "a verdict on the wire must come back as one, or the rollback it keeps reachable \
         cannot reach anything"
    );

    let mut older = value;
    let sheep = older["sheep"][0]
        .as_object_mut()
        .expect("a carried sheep is an object");
    assert!(
        sheep.remove("ready_failed").is_some(),
        "the field this case removes must be there to remove"
    );

    let loaded = Handover::load_value(older).expect("an older blob must still load");

    assert_eq!(loaded.sheep[0].ready_failed(), None);
    assert_eq!(
        loaded.sheep[0].id(),
        blob.sheep[0].id(),
        "the rest of the row is unchanged by the one field that was absent"
    );
}

/// The whole `DogSource`, not a boolean: [`CarriedSheep::dog`] says what
/// the marker is read for.
#[test]
fn a_dogs_marker_crosses_the_blob() {
    let mut entry = entry_fixture(|_| {});
    entry.dog = Some(DogSource::Adopted {
        grants: None,
        path: "/opt/bin/shep-log-rotate".to_string(),
        channel: false,
    });
    let mut blob = sample_handover();
    blob.sheep[0] = CarriedSheep::from_entry(&entry, 7, fds_at(11), false, None, false, None);

    let loaded =
        Handover::load_value(serde_json::to_value(&blob).unwrap()).expect("a current blob loads");

    assert_eq!(
        loaded.sheep[0].dog(),
        Some(&DogSource::Adopted {
            grants: None,
            path: "/opt/bin/shep-log-rotate".to_string(),
            channel: false,
        }),
        "a dog that crossed the exec as an ordinary sheep is one `shep dogs` has lost"
    );
}

/// A status or dog kind this build cannot read must fail the load, as it
/// did before the wire enums grew a decode-only fallback: adopting it would
/// supervise a sheep in a state the shepherd cannot act on, and send
/// `"unrecognized"` to every client.
#[test]
fn a_blob_row_this_build_cannot_read_refuses_the_handover() {
    let mut entry = entry_fixture(|_| {});
    entry.dog = Some(DogSource::BuiltIn { grants: None });
    let mut blob = sample_handover();
    blob.sheep[0] = CarriedSheep::from_entry(&entry, 7, fds_at(11), false, None, false, None);
    let wire = serde_json::to_value(&blob).unwrap();

    let mut future_status = wire.clone();
    future_status["sheep"][0]["status"] = serde_json::json!("invented_next_year");
    assert!(Handover::load_value(future_status).is_err());

    let mut future_dog = wire;
    future_dog["sheep"][0]["dog"] = serde_json::json!({"kind": "invented_next_year"});
    assert!(Handover::load_value(future_dog).is_err());
}

/// Not implied by the case above: a `from_entry` that hardcoded a source
/// would pass that one and turn every carried app into a dog.
#[test]
fn a_plain_sheep_crosses_the_blob_without_one() {
    let mut blob = sample_handover();
    blob.sheep[0] = CarriedSheep::from_entry(
        &entry_fixture(|_| {}),
        7,
        fds_at(11),
        false,
        None,
        false,
        None,
    );

    let loaded =
        Handover::load_value(serde_json::to_value(&blob).unwrap()).expect("a current blob loads");

    assert_eq!(loaded.sheep[0].dog(), None);
}

#[test]
fn a_blob_written_before_a_dog_was_carried_still_loads() {
    let mut entry = entry_fixture(|_| {});
    entry.dog = Some(DogSource::BuiltIn { grants: None });
    let mut blob = sample_handover();
    blob.sheep[0] = CarriedSheep::from_entry(&entry, 7, fds_at(11), false, None, false, None);
    let value = serde_json::to_value(&blob).unwrap();

    assert_eq!(
        Handover::load_value(value.clone())
            .expect("a current blob loads")
            .sheep[0]
            .dog(),
        Some(&DogSource::BuiltIn { grants: None }),
        "a marker on the wire must come back as one"
    );

    let mut older = value;
    let sheep = older["sheep"][0]
        .as_object_mut()
        .expect("a carried sheep is an object");
    assert!(
        sheep.remove("dog").is_some(),
        "the field this case removes must be there to remove"
    );

    let loaded = Handover::load_value(older).expect("an older blob must still load");

    assert_eq!(loaded.sheep[0].dog(), None);
    assert_eq!(
        loaded.sheep[0].id(),
        blob.sheep[0].id(),
        "the rest of the row is unchanged by the one field that was absent"
    );
}

/// One entry owed a respawn, which is the only status the deadline is
/// carried for.
fn owed_a_restart() -> ProcessEntry {
    let mut entry = entry_fixture(|_| {});
    entry.status = ProcStatus::WaitingRestart;
    entry.pid = None;
    entry
}

/// A whole second of slack on the round trip: this pins the value rather
/// than the precision.
#[test]
fn a_blob_written_before_a_restart_deadline_was_carried_still_loads() {
    let due = SystemTime::now() + core::time::Duration::from_secs(600);
    let mut blob = sample_handover();
    blob.sheep[0] = CarriedSheep::from_entry(
        &owed_a_restart(),
        7,
        fds_at(11),
        false,
        None,
        false,
        Some(due),
    );
    let value = serde_json::to_value(&blob).unwrap();

    let carried = Handover::load_value(value.clone())
        .expect("a current blob loads")
        .sheep[0]
        .restart_due()
        .expect("a deadline on the wire must come back as one");
    let drift = carried
        .duration_since(due)
        .or_else(|_| due.duration_since(carried))
        .unwrap();
    assert!(
        drift < core::time::Duration::from_secs(1),
        "a moment that does not survive the wire is a moment the successor cannot re-arm \
         from: {drift:?} of drift"
    );

    let mut older = value;
    let sheep = older["sheep"][0]
        .as_object_mut()
        .expect("a carried sheep is an object");
    assert!(
        sheep.remove("restart_due").is_some(),
        "the field this case removes must be there to remove"
    );

    let loaded = Handover::load_value(older).expect("an older blob must still load");

    assert_eq!(loaded.sheep[0].restart_due(), None);
    assert_eq!(
        loaded.sheep[0].id(),
        blob.sheep[0].id(),
        "the rest of the row is unchanged by the one field that was absent"
    );
}

/// Both halves, since a gate that dropped the field unconditionally would
/// pass the second assertion on its own.
#[test]
fn a_deadline_is_carried_only_for_a_sheep_owed_a_respawn() {
    let due = SystemTime::now() + core::time::Duration::from_secs(600);

    let waiting = CarriedSheep::from_entry(
        &owed_a_restart(),
        7,
        fds_at(11),
        false,
        None,
        false,
        Some(due),
    );
    assert!(
        waiting.restart_due().is_some(),
        "a sheep that IS owed a respawn must carry its deadline, or there is nothing to gate"
    );

    let online = CarriedSheep::from_entry(
        &entry_fixture(|_| {}),
        7,
        fds_at(11),
        false,
        None,
        false,
        Some(due),
    );
    assert_eq!(
        online.restart_due(),
        None,
        "a running sheep must not carry a deadline left over from an earlier exit"
    );
}