shep 0.12.3

The shep binary: a process manager that keeps a flock of long-running processes alive on macOS, Linux and Windows, with logs, watch and cron restarts, and webhook alerts
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
use super::*;

/// fails if a restart that the shepherd refused an app of exits 0 with
/// that app's row simply absent, which is what shipped between #166 and
/// this: `shep restart all` is a deploy step, and exit 0 there says the
/// whole fold came back when part of it did not.
#[tokio::test]
async fn a_restart_the_shepherd_refused_an_app_of_names_it_and_exits_non_zero() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, _envelopes) = fake_client_answering(&path, move |request| match request {
        Request::Restart { .. } => Response::Restarted {
            accepted: vec![reloaded_api()],
            refused: vec![SheepRefusal::new(
                "db",
                "selector matched no registered sheep",
            )],
        },
        Request::ListFlock => Response::Flock(vec![reloaded_api()]),
        _ => Response::Pong,
    })
    .await;

    let (code, printed, said) = restart_against(&client, "all").await;

    assert_eq!(
        code,
        ExitCode::Failure,
        "a fold restarted around a refused app is not a success: {said}"
    );
    assert!(
        said.contains("did not restart")
            && said.contains("db")
            && said.contains("no registered sheep"),
        "the refused app and the shepherd's reason reach the operator: {said}"
    );
    assert!(
        printed.contains("api"),
        "and what did restart is still printed: {printed}"
    );
}

/// fails if an ordinary restart starts exiting non-zero: the refused list
/// is empty on every restart nothing was refused of, which is all of them
/// bar the staged walk.
#[tokio::test]
async fn a_restart_that_refused_nothing_still_exits_zero() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, _envelopes) = fake_client_answering(&path, move |request| match request {
        Request::Restart { .. } => Response::Restarted {
            accepted: vec![reloaded_api()],
            refused: Vec::new(),
        },
        Request::ListFlock => Response::Flock(vec![reloaded_api()]),
        _ => Response::Pong,
    })
    .await;

    let (code, printed, said) = restart_against(&client, "all").await;

    assert_eq!(code, ExitCode::Success, "{said}");
    assert!(printed.contains("api"), "{printed}");
    assert!(said.is_empty(), "nothing to say: {said}");
}

/// fails if a partially-refused restart prints two top-level JSON
/// objects for one invocation, the guard `reload` already carries: a
/// consumer piping the run through `jq` either takes a parse error or
/// reads the first object and believes the whole fold came back.
#[tokio::test]
async fn a_partly_refused_restart_prints_one_json_envelope_carrying_both_halves() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, _envelopes) = fake_client_answering(&path, move |request| match request {
        Request::Restart { .. } => Response::Restarted {
            accepted: vec![reloaded_api()],
            refused: vec![SheepRefusal::new(
                "db",
                "selector matched no registered sheep",
            )],
        },
        Request::ListFlock => Response::Flock(vec![reloaded_api()]),
        _ => Response::Pong,
    })
    .await;

    let (code, printed, said) = restart_against_in(&client, "all", Format::Json).await;

    assert_eq!(
        code,
        ExitCode::Failure,
        "the exit code is unchanged: {said}"
    );
    assert_eq!(
        objects_in(&printed),
        1,
        "one envelope per invocation, refusal or no refusal: {printed}"
    );
    assert!(
        said.is_empty(),
        "and no second object beside it on stderr: {said}"
    );

    let envelope: serde_json::Value = serde_json::from_str(&printed).unwrap();
    assert_eq!(envelope["command"], "restart", "{envelope}");
    assert_eq!(
        envelope["schema_version"], 1,
        "a key added beside `data` is additive: {envelope}"
    );
    assert_eq!(
        envelope["data"][0]["name"], "api",
        "what restarted is still the answer: {envelope}"
    );
    assert_eq!(
        envelope["refused"][0]["name"], "db",
        "and what did not is named in the same object: {envelope}"
    );
    assert_eq!(
        envelope["refused"][0]["reason"], "selector matched no registered sheep",
        "with the shepherd's own reason: {envelope}"
    );
}

/// fails if an ordinary restart's envelope grows a key: `refused` is
/// carried only by a run that had something to refuse, so every existing
/// consumer reads the same three fields it always did and
/// `SCHEMA_VERSION` stays 1.
#[tokio::test]
async fn a_restart_that_refused_nothing_carries_no_refused_key() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, _envelopes) = fake_client_answering(&path, move |request| match request {
        Request::Restart { .. } => Response::Restarted {
            accepted: vec![reloaded_api()],
            refused: Vec::new(),
        },
        Request::ListFlock => Response::Flock(vec![reloaded_api()]),
        _ => Response::Pong,
    })
    .await;

    let (code, printed, said) = restart_against_in(&client, "all", Format::Json).await;

    assert_eq!(code, ExitCode::Success, "{said}");
    let envelope: serde_json::Value = serde_json::from_str(&printed).unwrap();
    assert!(
        envelope.get("refused").is_none(),
        "nothing was refused, so nothing says so: {envelope}"
    );
}

/// fails if a respawn that could not exec takes the refused apps down
/// with it. Both failures land in one invocation: `api` came back
/// `errored`, so stdout stays empty and the `--format json` envelope
/// that would have carried `db` was never printed. One error object is
/// all `cli.rs` publishes, so `db` rides that object rather than being
/// dropped.
#[tokio::test]
async fn a_restart_that_both_failed_to_spawn_and_refused_an_app_names_both() {
    use shep_client::testing::fake_client_answering;
    use shep_core::status::ProcStatus;

    let dir = tempfile::tempdir().unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, _envelopes) = fake_client_answering(&path, move |request| match request {
        Request::Restart { .. } => Response::Restarted {
            accepted: vec![ProcessInfo::builder(1, "api", ProcStatus::Errored).build()],
            refused: vec![SheepRefusal::new(
                "db",
                "selector matched no registered sheep",
            )],
        },
        Request::ListFlock => Response::Flock(Vec::new()),
        _ => Response::Pong,
    })
    .await;

    let (code, printed, said) = restart_against(&client, "all").await;

    assert_eq!(
        code,
        ExitCode::SpawnFailed,
        "a child that could not exec is the louder failure: {said}"
    );
    assert!(
        said.contains("api") && said.contains("did not come back up"),
        "the sheep that could not spawn is named: {said}"
    );
    assert!(
        said.contains("db") && said.contains("did not restart"),
        "and so is the one the walk went around: {said}"
    );
    assert!(
        printed.is_empty(),
        "a failed verb prints no table: {printed}"
    );
}

/// fails if a reload that the shepherd refused an app of exits 0 with
/// that app's row simply absent: `shep reload all` is a deploy step, and
/// exit 0 there says the whole fold reloaded when part of it did not.
#[tokio::test]
async fn a_reload_the_shepherd_refused_an_app_of_names_it_and_exits_non_zero() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, _envelopes) = fake_client_answering(&path, move |request| match request {
        Request::Reload { .. } => Response::Reloading {
            accepted: vec![reloaded_api()],
            refused: vec![SheepRefusal::new("db", "db is already being reloaded")],
        },
        // The table a lifecycle verb prints is a fresh listing, not the
        // reply's own rows.
        Request::ListFlock => Response::Flock(vec![reloaded_api()]),
        _ => Response::Pong,
    })
    .await;

    let (code, printed, said) = reload_against(&client, "all").await;

    assert_eq!(
        code,
        ExitCode::Failure,
        "a fold reloaded around a refused app is not a success: {said}"
    );
    assert!(
        said.contains("db") && said.contains("already being reloaded"),
        "the refused app and the shepherd's reason reach the operator: {said}"
    );
    assert!(
        printed.contains("api"),
        "and what did reload is still printed: {printed}"
    );
}

/// fails if an ordinary reload starts exiting non-zero: the refused list
/// is empty on every reload nothing was refused of, which is all of them
/// bar the staged walk.
#[tokio::test]
async fn a_reload_that_refused_nothing_still_exits_zero() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, _envelopes) = fake_client_answering(&path, move |request| match request {
        Request::Reload { .. } => Response::Reloading {
            accepted: vec![reloaded_api()],
            refused: Vec::new(),
        },
        Request::ListFlock => Response::Flock(vec![reloaded_api()]),
        _ => Response::Pong,
    })
    .await;

    let (code, printed, said) = reload_against(&client, "all").await;

    assert_eq!(code, ExitCode::Success, "{said}");
    assert!(printed.contains("api"), "{printed}");
    assert!(said.is_empty(), "nothing to say: {said}");
}

/// fails if a partially-refused reload prints two top-level JSON
/// objects for one invocation: `cli.rs` publishes `--format json` as
/// one object per invocation, and a consumer piping the run through
/// `jq` either takes a parse error or reads the first object and
/// believes the whole fold reloaded.
#[tokio::test]
async fn a_partly_refused_reload_prints_one_json_envelope_carrying_both_halves() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, _envelopes) = fake_client_answering(&path, move |request| match request {
        Request::Reload { .. } => Response::Reloading {
            accepted: vec![reloaded_api()],
            refused: vec![SheepRefusal::new("db", "db is already being reloaded")],
        },
        Request::ListFlock => Response::Flock(vec![reloaded_api()]),
        _ => Response::Pong,
    })
    .await;

    let (code, printed, said) = reload_against_in(&client, "all", Format::Json).await;

    assert_eq!(
        code,
        ExitCode::Failure,
        "the exit code is unchanged: {said}"
    );
    assert_eq!(
        objects_in(&printed),
        1,
        "one envelope per invocation, refusal or no refusal: {printed}"
    );
    assert!(
        said.is_empty(),
        "and no second object beside it on stderr: {said}"
    );

    let envelope: serde_json::Value = serde_json::from_str(&printed).unwrap();
    assert_eq!(envelope["command"], "reload", "{envelope}");
    assert_eq!(
        envelope["schema_version"], 1,
        "a key added beside `data` is additive: {envelope}"
    );
    assert_eq!(
        envelope["data"][0]["name"], "api",
        "what reloaded is still the answer: {envelope}"
    );
    assert_eq!(
        envelope["refused"][0]["name"], "db",
        "and what did not is named in the same object: {envelope}"
    );
    assert_eq!(
        envelope["refused"][0]["reason"], "db is already being reloaded",
        "with the shepherd's own reason: {envelope}"
    );
}

/// fails if an ordinary reload's envelope grows a key: `refused` is
/// carried only by a run that had something to refuse, so every
/// existing consumer reads the same three fields it always did.
#[tokio::test]
async fn a_reload_that_refused_nothing_carries_no_refused_key() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, _envelopes) = fake_client_answering(&path, move |request| match request {
        Request::Reload { .. } => Response::Reloading {
            accepted: vec![reloaded_api()],
            refused: Vec::new(),
        },
        Request::ListFlock => Response::Flock(vec![reloaded_api()]),
        _ => Response::Pong,
    })
    .await;

    let (code, printed, said) = reload_against_in(&client, "all", Format::Json).await;

    assert_eq!(code, ExitCode::Success, "{said}");
    let envelope: serde_json::Value = serde_json::from_str(&printed).unwrap();
    assert!(
        envelope.get("refused").is_none(),
        "nothing was refused, so nothing says so: {envelope}"
    );
}

/// A load whose answer this client cannot read means the whole file went
/// nowhere, and a daemon-side fault takes its own class's code rather
/// than the refusal's.
#[tokio::test]
async fn a_load_that_failed_for_another_reason_exits_with_its_own_class() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let flockfile = dir.path().join("Flockfile.toml");
    std::fs::write(
        &flockfile,
        "[[app]]\nname = \"zam\"\nscript = \"./srv\"\nmax_restarts = 99\n",
    )
    .unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let flock = a_clustered_flock(&[0, 1, 2]);
    // `Pong` to an `ApplyConfig`. `Response` is `#[non_exhaustive]`, so
    // this is also the shape a newer daemon produces.
    let (client, _envelopes) = fake_client_answering(&path, move |request| match request {
        Request::ListFlock => Response::Flock(flock.clone()),
        _ => Response::Pong,
    })
    .await;

    let (code, _printed, said) = start_against(&client, flockfile.to_str().unwrap()).await;

    assert_eq!(
        code,
        ExitCode::Internal,
        "its own class, not the refusal code: {said}"
    );
    assert!(
        said.contains("not in effect"),
        "and the operator is told the edits went nowhere: {said}"
    );
}

#[test]
fn a_load_that_did_nothing_to_an_app_says_nothing_about_it() {
    let quiet = SheepApplied::new("zam", Vec::new(), Vec::new(), None);
    assert_eq!(applied_line(&quiet), None);

    let refused = SheepApplied::new(
        "zam",
        Vec::new(),
        Vec::new(),
        Some("zam is not registered".to_string()),
    );
    assert_eq!(
        applied_line(&refused).as_deref(),
        Some("zam: zam is not registered")
    );
}