shep-daemon 0.18.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
//! What a dog is, and the process spec the daemon spawns it as.
//!
//! [`dog_app`] assembles the same [`ResolvedApp`] a Flockfile entry would,
//! and the supervisor supervises it as a sheep. Both [`DogSpec::source`]
//! kinds run at the daemon's own trust level. [`spawn_enabled_dogs`] is the
//! boot-time caller: it starts every configured dog and never fails the boot
//! over one that would not start.

use core::fmt;
use std::collections::BTreeSet;
use std::path::PathBuf;

use shep_core::config::template::RenderError;
use shep_core::config::{AppConfig, ResolvedApp, normalize};
use shep_core::paths::ShepPaths;
use shep_core::protocol::DogSource;
use shep_core::protocol::ProcessInfo;
use shep_core::status::ProcStatus;

use crate::bus::Bus;
use crate::supervisor::SupervisorHandle;

use super::narrate::narrate;
use super::secrets::StoreFault;

/// One dog the daemon knows about: its name, and where its binary comes from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DogSpec {
    /// The dog's name: the `[<name>]` key and the entry's name.
    pub name: String,
    /// Where its binary comes from.
    pub source: DogSource,
}

/// The sentence this shepherd answers a request to delete a built-in dog with.
///
/// A built-in dog is an argv branch of the shep binary, so nothing removes it:
/// `delete` has no registration to forget and no binary to lose. `disable` is
/// the verb that exists for it, and the refusal names it.
///
/// Public because `shep-cli` reports it for a shepherd that is not running and
/// cannot be asked, so an operator reads one sentence either way.
#[must_use]
pub fn built_in_dog_refusal(name: &str) -> String {
    format!("{name} is built in: `shep disable {name}`")
}

/// Error assembling a dog's app config, or reading its section
///
/// `Debug` needs no redaction: a path, a normalizer complaint, or a TOML
/// parser message, never a value read out of a parsed `[<name>]` table. The
/// two secret variants hold a key path, a reference as written, an
/// environment name and a [`StoreFault`], so no field can hold a resolved
/// value (IR-41). A syntax error can quote a line of the section's own
/// source, but only to the peer that asked, which peer-cred auth already
/// established owns the file.
///
/// [`Self::NoBinary`] and [`Self::Io`] wrap their [`std::io::Error`] rather
/// than rendering it, which costs this enum `Clone`, `PartialEq` and `Eq`.
#[non_exhaustive]
#[derive(Debug)]
pub enum DogError {
    /// A built-in dog has no program it can be spawned with: either
    /// [`std::env::current_exe`] failed, or handover-target resolution refused
    /// every candidate.
    NoBinary(std::io::Error),
    /// The dog's binary comes from a source this build cannot spawn (carries
    /// the source as `Debug` renders it). [`DogSource`] is `#[non_exhaustive]`,
    /// so a name enabled by a newer shep can reach an older daemon.
    UnsupportedSource(String),
    /// The assembled config failed `normalize`, or the file read is not
    /// valid `shep.toml`, or the section it holds cannot be rendered back to
    /// TOML (carries the rejection message)
    Config(String),
    /// The file exists and could not be read
    Io(std::io::Error),
    /// A `{{secret:...}}` in the section cannot be resolved: it names no
    /// value, names a namespace no provider has pushed, or is outside the
    /// reference grammar
    Reference {
        /// Where the string sits in the section, as `sinks.local.url` or
        /// `rules[1].url`
        key_path: String,
        /// Which reference, and why. Holds the reference as written and the
        /// environment, never a value.
        source: RenderError,
    },
    /// The section names a reference and the secret store could not be read
    SecretStore {
        /// Where the first reference in the section sits
        key_path: String,
        /// What went wrong, without the store's own message
        fault: StoreFault,
    },
}

impl fmt::Display for DogError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoBinary(err) => write!(f, "this binary's own path is unresolvable: {err}"),
            Self::UnsupportedSource(source) => {
                write!(f, "no way to spawn a dog from source {source}")
            }
            Self::Config(msg) => write!(f, "dog configuration is unusable: {msg}"),
            Self::Io(err) => write!(f, "dog configuration could not be read: {err}"),
            Self::Reference { key_path, source } => write!(f, "`{key_path}`: {source}"),
            Self::SecretStore { key_path, fault } => write!(
                f,
                "`{key_path}`: the secret store could not be read ({fault})"
            ),
        }
    }
}

impl core::error::Error for DogError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::NoBinary(err) | Self::Io(err) => Some(err),
            Self::Reference { source, .. } => Some(source),
            Self::UnsupportedSource(_) | Self::Config(_) | Self::SecretStore { .. } => None,
        }
    }
}

/// The program a built-in dog is spawned as: this binary's own resolved path.
///
/// Through `handover::exec_target` rather than [`std::env::current_exe`],
/// which on Linux answers `"<path> (deleted)"` once a package manager has
/// replaced the running binary, and that cannot be exec'd. A respawned dog
/// can therefore run newer code than the shepherd currently has loaded, if
/// the binary was replaced before this shepherd reloaded or handed over.
#[cfg(unix)]
fn builtin_program() -> Result<PathBuf, DogError> {
    crate::handover::exec_target().map_err(DogError::NoBinary)
}

/// The program a built-in dog is spawned as, on a platform with no handover.
///
/// Windows refuses to replace a running executable, so no unlinked inode can
/// exist for `current_exe` to name.
#[cfg(windows)]
fn builtin_program() -> Result<PathBuf, DogError> {
    std::env::current_exe().map_err(DogError::NoBinary)
}

/// The app config the daemon spawns `spec` from.
///
/// A built-in dog is `<this binary> dog <name>`; an adopted one is the
/// operator's binary with no arguments. The environment carries `SHEP_HOME`
/// and `SHEP_DOG_NAME`, never a `[<name>]` value: a dog asks for its section
/// over the socket. An adopted dog that asked for the shepherd channel gets
/// `channel` and `shutdown_with_message`, and so the channel's own
/// variables too; every other dog gets neither.
///
/// # Errors
/// - [`DogError::NoBinary`] if a built-in dog has no program to run.
/// - [`DogError::UnsupportedSource`] if the source is a kind this build does
///   not know how to spawn.
/// - [`DogError::Config`] if the assembled config failed `normalize`.
pub fn dog_app(spec: &DogSpec, paths: &ShepPaths) -> Result<ResolvedApp, DogError> {
    let (script, args, channel) = match &spec.source {
        DogSource::BuiltIn { .. } => (
            builtin_program()?.display().to_string(),
            vec!["dog".to_string(), spec.name.clone()],
            false,
        ),
        // No arguments: an adopted dog is somebody else's binary, and an argv
        // shep invented for it is one more thing it has to agree with.
        DogSource::Adopted { path, channel, .. } => (path.clone(), Vec::new(), *channel),
        source => return Err(DogError::UnsupportedSource(format!("{source:?}"))),
    };

    let mut config = AppConfig::minimal(&spec.name, &script);
    config.args = args;
    config.channel = channel;
    config.shutdown_with_message = channel;
    config
        .env
        .insert("SHEP_HOME".to_string(), paths.home.display().to_string());
    // The `[<name>]` key this dog's section lives beneath, and so the `name`
    // it puts in `Request::DogConfig`. An adopted dog has no argv to read it
    // from, so this is its only channel.
    config
        .env
        .insert(shep_core::dogs::DOG_NAME_VAR.to_string(), spec.name.clone());
    normalize(config).map_err(|err| DogError::Config(err.to_string()))
}

/// Registers every dog in `known` and `enabled` at rest, so the flock lists
/// it whether or not it runs.
///
/// A dog outside `enabled` is registered `Stopped` and disabled; one in it is
/// registered `Stopped` all the same, for [`spawn_enabled_dogs`] to start.
/// A dog already registered under its name, running or a sheep, keeps its row
/// and its mark, except for the ones `stop_unenabled_dogs` takes back: every
/// dog row this config does not enable that is not already stopped and marked.
/// Entries land in the order given, `enabled` first, so a dog's id does not
/// depend on which of two lists named it.
///
/// Never fails the boot, for [`spawn_enabled_dogs`]'s reason: a dog that
/// cannot be assembled is warned about and left out.
pub async fn register_dogs_at_rest(
    known: &[DogSpec],
    enabled: &[DogSpec],
    paths: &ShepPaths,
    supervisor: &SupervisorHandle,
) {
    let mut seen = BTreeSet::new();
    let mut dogs = Vec::new();
    for spec in enabled.iter().chain(known) {
        if !seen.insert(spec.name.as_str()) {
            continue;
        }
        match dog_app(spec, paths) {
            Ok(app) => dogs.push((app, spec.source.clone())),
            Err(err) => tracing::warn!(dog = %spec.name, %err, "a dog was not listed"),
        }
    }
    let disabled: BTreeSet<String> = known
        .iter()
        .map(|spec| spec.name.clone())
        .filter(|name| !enabled.iter().any(|spec| spec.name == *name))
        .collect();
    if let Err(err) = supervisor.register_dogs_at_rest(dogs, disabled).await {
        tracing::warn!(%err, "the dogs were not listed");
        return;
    }
    // The flock, and not what this call handed the actor: a dog whose own
    // config failed to assemble never reached the actor at all, and a carried
    // one is running there regardless.
    let flock = match supervisor.list_checked().await {
        Ok(flock) => flock,
        Err(err) => {
            tracing::warn!(%err, "the flock could not be read to check its dogs against");
            return;
        }
    };
    stop_unenabled_dogs(&flock, enabled, supervisor).await;
}

/// Stops and marks every dog row in `flock` that `enabled` does not name,
/// except one already stopped and marked.
///
/// The case is a handover successor's. A predecessor booted while `shep.toml`
/// named the dog, ran it, and carried it across the `execve`; this boot read a
/// file that has since dropped the name, by hand or through `shep disable`
/// against a shepherd that has since been replaced. The successor owns the
/// dog's row now, and a row it inherited running is not one its config says
/// should run: it goes down through the operator's own door, which marks the
/// app as it stops it, so `shep flock` reads `disabled` and
/// `shep enable <name>` is the way back. A dog an operator stopped with
/// `shep stop` and the config then dropped is marked by the same call, so the
/// row does not go on reading as startable.
///
/// Reads the whole flock rather than the rows this boot registered, so a
/// carried dog whose own config failed to assemble is stopped too: the process
/// is in the flock and the assembly that would have described it is the half
/// that failed. A cold boot never reaches the stop: it spawns only the dogs it
/// enables, so every dog it registers at rest is already in the shape this
/// passes by.
///
/// Awaits each dog's kill ladder, since the reply the supervisor owes is the
/// exit's. Bounded by the dog's own `shutdown_timeout` and `kill_timeout`, and
/// it delays the readiness this boot reports by that much.
async fn stop_unenabled_dogs(
    flock: &[ProcessInfo],
    enabled: &[DogSpec],
    supervisor: &SupervisorHandle,
) {
    for info in flock {
        let named = enabled.iter().any(|spec| spec.name == info.name);
        let parked = info.disabled == Some(true) && info.status == ProcStatus::Stopped;
        if info.dog.is_none() || named || parked {
            continue;
        }
        if let Err(err) = supervisor.disable_dog(info.name.clone()).await {
            tracing::warn!(
                dog = %info.name,
                %err,
                "a dog this shepherd's config does not enable was left running"
            );
        }
    }
}

/// Starts every dog in `specs`, warning and carrying on for each one that
/// will not start.
///
/// Never fails the boot: a dog that cannot be spawned is a monitoring gap, and
/// refusing to bring the flock up over it turns that gap into an outage.
/// [`SupervisorHandle::start_dog`] is idempotent by name for a dog that runs,
/// so an `Ok` reply carrying no `dog` means a sheep already held the name and
/// nothing started.
pub async fn spawn_enabled_dogs(
    specs: &[DogSpec],
    paths: &ShepPaths,
    supervisor: &SupervisorHandle,
    events: &Bus,
) {
    for spec in specs {
        let app = match dog_app(spec, paths) {
            Ok(app) => app,
            Err(err) => {
                tracing::warn!(dog = %spec.name, %err, "a dog did not start");
                continue;
            }
        };
        // Read before `start_dog` takes the app: this is the one place that
        // knows which file the spawn resolved to.
        let script = app.config().script.clone();
        match supervisor.start_dog(app, spec.source.clone()).await {
            Ok(info) if info.dog.is_none() => tracing::warn!(
                dog = %spec.name,
                "a sheep is already registered under this name; the dog did not start"
            ),
            Ok(info) => {
                // `start_dog` is idempotent by name, so this reply may be a
                // dog that was already running: the wording is about the
                // binary this shepherd resolved, not about a spawn.
                narrate(
                    events,
                    &info,
                    &format!("shep has this dog enabled, running the binary at {script}"),
                )
                .await;
            }
            Err(err) => tracing::warn!(dog = %spec.name, %err, "a dog did not start"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::test_paths;

    /// `current_exe` cannot safely be made to return `" (deleted)"`, so this
    /// pins what `builtin_program` does with the answer it gets: it is the
    /// shared resolution's, which is never a deleted inode and always a file.
    #[cfg(unix)]
    #[test]
    fn a_built_in_dogs_program_is_the_resolved_exec_target_and_never_a_deleted_inode() {
        let program = builtin_program().expect("the test binary resolves");

        assert_eq!(program, crate::handover::exec_target().unwrap());
        assert!(program.is_file(), "{}", program.display());
        assert!(
            !program.to_string_lossy().ends_with(" (deleted)"),
            "{}",
            program.display()
        );
    }

    #[test]
    fn an_unresolvable_binary_says_so_and_keeps_the_refusal_as_its_source() {
        use core::error::Error as _;

        let refusal = std::io::Error::new(std::io::ErrorKind::NotFound, "no binary to exec");
        let err = DogError::NoBinary(refusal);

        assert_eq!(
            err.to_string(),
            "this binary's own path is unresolvable: no binary to exec"
        );
        assert_eq!(err.source().unwrap().to_string(), "no binary to exec");
    }

    /// Asserted over the assembled spec rather than the config, because
    /// `assemble` is where an env map would be merged. `SHEP_DOG_NAME` is no
    /// exception to the rule: it is the key a dog needs to ask for its section
    /// at all.
    #[test]
    fn a_dogs_child_environment_carries_shep_home_and_its_name_and_no_configuration() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        std::fs::write(
            &paths.dogs_config,
            "[bark]\nwebhook = \"https://example.invalid/hook\"\n",
        )
        .unwrap();
        let spec = DogSpec {
            name: "bark".to_string(),
            source: DogSource::BuiltIn { grants: None },
        };
        let app = dog_app(&spec, &paths).unwrap();
        // A dog's config is built by `dog_app`, never operator-templated,
        // so an empty view resolves everything it holds.
        let assembled = crate::assemble::assemble(
            &app,
            0,
            &paths,
            None,
            &shep_core::secrets::SecretView::empty("production".to_string()),
        )
        .expect("a dog's own config carries no template to refuse");
        assert_eq!(
            assembled.env.get("SHEP_HOME"),
            Some(&paths.home.display().to_string())
        );
        assert_eq!(
            assembled.env.get("SHEP_DOG_NAME"),
            Some(&"bark".to_string()),
            "a dog is told the name its own section lives under"
        );
        assert!(
            !assembled
                .env
                .values()
                .any(|v| v.contains("example.invalid")),
            "a dog's configuration never travels in its environment: {:?}",
            assembled.env
        );
    }

    #[test]
    fn a_built_in_dog_runs_this_binary_and_an_adopted_one_runs_its_own() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);

        let built_in = dog_app(
            &DogSpec {
                name: "metrics".to_string(),
                source: DogSource::BuiltIn { grants: None },
            },
            &paths,
        )
        .unwrap();
        assert_eq!(
            built_in.config().script,
            std::env::current_exe().unwrap().display().to_string()
        );
        assert_eq!(built_in.config().args, vec!["dog", "metrics"]);

        let adopted = dog_app(
            &DogSpec {
                name: "otel".to_string(),
                source: DogSource::Adopted {
                    grants: None,
                    path: "/usr/local/bin/shep-otel".to_string(),
                    channel: false,
                },
            },
            &paths,
        )
        .unwrap();
        assert_eq!(adopted.config().script, "/usr/local/bin/shep-otel");
        assert!(adopted.config().args.is_empty());
        assert_eq!(
            adopted.config().name,
            "otel",
            "the NAME is the config key, never the filename"
        );
    }

    /// A dog's log also holds shep's narration, which `narrate` always
    /// stamps, so the dog's own lines must carry the stamp too.
    #[test]
    fn a_dogs_own_log_lines_are_stamped() {
        let dir = tempfile::tempdir().unwrap();
        let spec = DogSpec {
            name: "metrics".to_string(),
            source: DogSource::BuiltIn { grants: None },
        };

        assert!(
            dog_app(&spec, &test_paths(&dir))
                .unwrap()
                .config()
                .log_timestamps
        );
    }

    #[test]
    fn only_an_adopted_dog_that_asked_gets_the_channel_and_a_stop_by_message() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        let adopted = |channel| DogSource::Adopted {
            grants: None,
            path: "/usr/local/bin/shep-otel".to_string(),
            channel,
        };

        for (source, expected) in [
            (adopted(true), true),
            (adopted(false), false),
            (DogSource::BuiltIn { grants: None }, false),
        ] {
            let spec = DogSpec {
                name: "otel".to_string(),
                source: source.clone(),
            };
            let app = dog_app(&spec, &paths).unwrap();
            let config = app.config();
            assert_eq!(config.channel, expected, "{source:?}");
            assert_eq!(config.shutdown_with_message, expected, "{source:?}");
        }
    }

    /// An adopted dog is given no argv, so the environment is its only
    /// channel, and a mismatch looks exactly like a dog with no configuration.
    /// The name is the one the operator chose, not the binary's file stem.
    #[test]
    fn an_adopted_dog_is_told_the_name_it_was_registered_under() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);

        let adopted = dog_app(
            &DogSpec {
                name: "telemetry".to_string(),
                source: DogSource::Adopted {
                    grants: None,
                    path: "/usr/local/bin/shep-otel".to_string(),
                    channel: false,
                },
            },
            &paths,
        )
        .unwrap();

        assert!(
            adopted.config().args.is_empty(),
            "the name arrives without shep inventing an argv for a foreign binary"
        );
        assert_eq!(
            adopted.config().env.get("SHEP_DOG_NAME"),
            Some(&"telemetry".to_string())
        );
    }
}