shep-daemon 0.2.3

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
//! Spawn assembly: pure functions that build [`SpawnSpec`] from app config.
//!
//! The assembler takes a validated `ResolvedApp` and produces a fully-resolved
//! [`SpawnSpec`] ready for [`ProcessRunner::spawn`](crate::runner::ProcessRunner::spawn).
//! No I/O here: all defaults, env vars, and paths are pre-resolved by the
//! daemon before assembler is called (environment comes in via `ResolvedApp`).
//!
//! Public for its two out-of-crate readers and nothing else: `tests/real_runner.rs`
//! calls [`assemble`] to build a spec it then spawns for real, and
//! [`instance_slots`]'s doc example is compiled as its own crate.

use std::collections::BTreeMap;
use std::path::PathBuf;

use shep_core::config::ResolvedApp;
use shep_core::config::template;
use shep_core::paths::ShepPaths;

use crate::privilege::Credentials;
use crate::runner::SpawnSpec;

/// Finds the `count` lowest-free instance slot numbers from an existing set.
///
/// Used to allocate instance slots for clustered apps. Assumes `existing` is
/// sorted; returns a new vector of `count` distinct slots, smallest first,
/// none of which appear in `existing`.
///
/// # Examples
///
/// ```
/// use shep_daemon::assemble::instance_slots;
///
/// assert_eq!(instance_slots(&[], 3), vec![0, 1, 2]);
/// assert_eq!(instance_slots(&[0, 2], 2), vec![1, 3]);
/// ```
#[must_use]
pub fn instance_slots(existing: &[u32], count: u32) -> Vec<u32> {
    let mut result = Vec::with_capacity(count as usize);
    let mut candidate = 0u32;

    for _ in 0..count {
        while existing.contains(&candidate) || result.contains(&candidate) {
            candidate += 1;
        }
        result.push(candidate);
        candidate += 1;
    }

    result
}

/// The env every spawned child starts from, before the app's own `env` map
/// is folded on top (app config always wins on conflict).
///
/// Without a `PATH` here, a bare program or interpreter name can never be
/// found by exec. Reads the daemon's own environment once, so this stays a
/// pure function of process state, not I/O.
fn base_env() -> BTreeMap<String, String> {
    let mut env = BTreeMap::new();
    // An empty PATH ("PATH=") is treated as absent: `Ok("")` would
    // otherwise slip through `unwrap_or_else`, and an empty PATH resolves a
    // bare program against the cwd instead of searching.
    let path = std::env::var("PATH")
        .ok()
        .filter(|value| !value.is_empty())
        .unwrap_or_else(|| DEFAULT_PATH.to_string());
    env.insert("PATH".to_string(), path);
    for key in INHERITED {
        if let Ok(value) = std::env::var(key) {
            env.insert(key.to_string(), value);
        }
    }
    env
}

/// The `PATH` a child gets when the daemon itself has none.
#[cfg(unix)]
const DEFAULT_PATH: &str = "/usr/local/bin:/usr/bin:/bin";
/// The `PATH` a child gets when the daemon itself has none.
///
/// Not expanded via `%SystemRoot%`: these literal paths are correct on
/// every standard Windows install and need no variable to resolve.
#[cfg(windows)]
const DEFAULT_PATH: &str = r"C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem";

/// Variables inherited from the daemon's own environment, on top of `PATH`.
#[cfg(unix)]
const INHERITED: &[&str] = &["HOME", "USER", "LANG", "TZ"];

/// Variables inherited from the daemon's own environment, on top of `PATH`.
///
/// Longer than the unix list because Windows children need it: many Win32
/// APIs read `%SystemRoot%` directly, and `PATHEXT`/`COMSPEC` let a child
/// resolve and run `.cmd` files at all. `TEMP`/`TMP` and the
/// `USERPROFILE`/`APPDATA`/`LOCALAPPDATA` trio are where most runtimes keep
/// per-user state. Still a closed allowlist, not inherit-everything.
#[cfg(windows)]
const INHERITED: &[&str] = &[
    "SystemRoot",
    "windir",
    "SystemDrive",
    "COMSPEC",
    "PATHEXT",
    "TEMP",
    "TMP",
    "USERPROFILE",
    "HOMEDRIVE",
    "HOMEPATH",
    "APPDATA",
    "LOCALAPPDATA",
    "PROCESSOR_ARCHITECTURE",
    "NUMBER_OF_PROCESSORS",
    "OS",
    "LANG",
    "TZ",
];

/// Assembles a [`SpawnSpec`] from a validated app config and instance slot.
///
/// `credentials` is resolved by the caller, since passwd/group lookups are
/// real I/O and this function otherwise stays pure. `interpreter = None` or
/// `Some("none")` runs the script directly; `Some(path)` runs `path` with
/// `[script, ...args]`.
///
/// Explicit `out_file`/`err_file` win over the default log path and render
/// through the same `{{instance}}`/`{{name}}` grammar as `env` and `args`;
/// normalize already refused a path that collides across instances unless
/// `merge_logs` asked for it. `SpawnSpec::stdin` carries `config.stdin`
/// straight through: unlike `channel`, nothing else turns it on.
#[must_use]
pub fn assemble(
    app: &ResolvedApp,
    instance: u32,
    paths: &ShepPaths,
    credentials: Option<Credentials>,
) -> SpawnSpec {
    let config = app.config();
    let name = config.name.clone();

    // Args carry the `{{instance}}`/`{{name}}` grammar too, rendered once
    // here before the interpreter logic below decides where they land.
    let rendered_args: Vec<String> = config
        .args
        .iter()
        .map(|value| template::render(value, &name, instance))
        .collect();

    let (program, args) = match &config.interpreter {
        None => (config.script.clone(), rendered_args),
        Some(interp) if interp == "none" => (config.script.clone(), rendered_args),
        Some(interp) => {
            let mut interp_args = vec![config.script.clone()];
            interp_args.extend(rendered_args);
            (interp.clone(), interp_args)
        }
    };

    // Anything not seeded here is invisible to the child: tokio_runner.rs
    // calls env_clear() then envs(&spec.env). Each value renders through
    // the {{instance}}/{{name}} grammar as it is inserted.
    let mut env = base_env();
    env.extend(
        config
            .env
            .iter()
            .map(|(key, value)| (key.clone(), template::render(value, &name, instance))),
    );
    // Fixed names, always injected: an app that wants the slot under its
    // own var can template it, e.g. `MY_VAR = "{{instance}}"`.
    env.insert("SHEP_INSTANCE".to_string(), instance.to_string());
    env.insert("SHEP_NAME".to_string(), name.clone());

    let cwd = config.cwd.as_ref().map(PathBuf::from);

    let log_stem = if config.merge_logs {
        format!("{}-", name)
    } else {
        format!("{}-{}-", name, instance)
    };

    let out_file = if let Some(ref explicit) = config.out_file {
        PathBuf::from(template::render(explicit, &name, instance))
    } else {
        paths.logs.join(format!("{}out.log", log_stem))
    };

    let err_file = if let Some(ref explicit) = config.err_file {
        PathBuf::from(template::render(explicit, &name, instance))
    } else {
        paths.logs.join(format!("{}err.log", log_stem))
    };

    // Also implied by wait_ready or shutdown_with_message: widening this
    // must keep every term, or dropping one silently stops opening fd 3 for
    // an app that relied on it implying the channel.
    let channel = config.channel || config.wait_ready || config.shutdown_with_message;

    SpawnSpec {
        name,
        program,
        args,
        cwd,
        env,
        out_file,
        err_file,
        channel,
        stdin: config.stdin,
        credentials,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use shep_core::config::{AppConfig, normalize};

    fn test_paths() -> ShepPaths {
        ShepPaths {
            home: PathBuf::from("/home/ada/.shep"),
            daemon_config: PathBuf::from("/home/ada/.shep/shep.toml"),
            dogs_config: PathBuf::from("/home/ada/.shep/dogs.toml"),
            snapshot: PathBuf::from("/home/ada/.shep/flock.json"),
            logs: PathBuf::from("/home/ada/.shep/logs"),
            pids: PathBuf::from("/home/ada/.shep/pids"),
            run: PathBuf::from("/home/ada/.shep/run"),
            socket: PathBuf::from("/home/ada/.shep/run/shep.sock"),
            barks: PathBuf::from("/home/ada/.shep/barks.jsonl"),
            kv: PathBuf::from("/home/ada/.shep/kv.json"),
            overrides: PathBuf::from("/home/ada/.shep/overrides.json"),
        }
    }

    #[test]
    fn slots_empty_request() {
        let result = instance_slots(&[], 3);
        assert_eq!(result, vec![0, 1, 2]);
    }

    #[test]
    fn slots_skip_occupied() {
        let result = instance_slots(&[0, 2], 2);
        assert_eq!(result, vec![1, 3]);
    }

    #[test]
    fn env_adds_shep_instance() {
        let app_config = AppConfig {
            name: "web".to_string(),
            script: "/usr/bin/python3".to_string(),
            args: vec!["app.py".to_string()],
            interpreter: Some("none".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 1, &paths, None);

        assert!(spec.env.contains_key("SHEP_INSTANCE"));
        assert_eq!(spec.env.get("SHEP_INSTANCE").map(|s| s.as_str()), Some("1"));
    }

    #[test]
    fn every_child_learns_its_slot_and_its_name() {
        let app = normalize(AppConfig {
            name: "worker".to_string(),
            script: "bin/worker".to_string(),
            ..Default::default()
        })
        .unwrap();
        let spec = assemble(&app, 3, &test_paths(), None);
        assert_eq!(spec.env.get("SHEP_INSTANCE").map(String::as_str), Some("3"));
        assert_eq!(
            spec.env.get("SHEP_NAME").map(String::as_str),
            Some("worker")
        );
    }

    #[test]
    fn interpreter_none_runs_script_directly() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "/opt/bin/server".to_string(),
            args: vec!["--port".to_string(), "8080".to_string()],
            interpreter: None,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None);

        assert_eq!(spec.program, "/opt/bin/server");
        assert_eq!(spec.args, vec!["--port", "8080"]);
    }

    #[test]
    fn interpreter_explicit_none_runs_script_directly() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "server.py".to_string(),
            args: vec!["--verbose".to_string()],
            interpreter: Some("none".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None);

        assert_eq!(spec.program, "server.py");
        assert_eq!(spec.args, vec!["--verbose"]);
    }

    #[test]
    fn interpreter_path_prepends_script() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app.js".to_string(),
            args: vec!["--debug".to_string(), "true".to_string()],
            interpreter: Some("node".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None);

        assert_eq!(spec.program, "node");
        assert_eq!(spec.args, vec!["app.js", "--debug", "true"]);
    }

    #[test]
    fn merge_logs_false_uses_instance_suffix() {
        let app_config = AppConfig {
            name: "web".to_string(),
            script: "app".to_string(),
            args: vec![],
            merge_logs: false,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 2, &paths, None);

        assert_eq!(
            spec.out_file,
            PathBuf::from("/home/ada/.shep/logs/web-2-out.log")
        );
        assert_eq!(
            spec.err_file,
            PathBuf::from("/home/ada/.shep/logs/web-2-err.log")
        );
    }

    #[test]
    fn merge_logs_true_omits_instance_suffix() {
        let app_config = AppConfig {
            name: "api".to_string(),
            script: "api".to_string(),
            args: vec![],
            merge_logs: true,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 1, &paths, None);

        assert_eq!(
            spec.out_file,
            PathBuf::from("/home/ada/.shep/logs/api-out.log")
        );
        assert_eq!(
            spec.err_file,
            PathBuf::from("/home/ada/.shep/logs/api-err.log")
        );
    }

    #[test]
    fn explicit_out_file_wins() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            merge_logs: false,
            out_file: Some("/var/log/myapp.log".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None);

        assert_eq!(spec.out_file, PathBuf::from("/var/log/myapp.log"));
        assert_eq!(
            spec.err_file,
            PathBuf::from("/home/ada/.shep/logs/app-0-err.log")
        );
    }

    // fails if the gate drops the `channel` term from the disjunction
    #[test]
    fn channel_enabled_by_its_own_field() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            channel: true,
            wait_ready: false,
            shutdown_with_message: false,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None);

        assert!(spec.channel);
    }

    // fails if the gate drops the `wait_ready` term from the disjunction
    #[test]
    fn channel_enabled_by_wait_ready() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            channel: false,
            wait_ready: true,
            shutdown_with_message: false,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None);

        assert!(spec.channel);
    }

    // fails if the gate drops the `shutdown_with_message` term from the
    // disjunction
    #[test]
    fn channel_enabled_by_shutdown_with_message() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            channel: false,
            wait_ready: false,
            shutdown_with_message: true,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None);

        assert!(spec.channel);
    }

    // Catches a stuck-open gate (e.g. `|| true`), since all three flags are
    // false here, unlike the three positive tests above.
    #[test]
    fn channel_disabled_when_all_three_flags_are_false() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            channel: false,
            wait_ready: false,
            shutdown_with_message: false,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None);

        assert!(!spec.channel);
    }

    #[test]
    fn assembled_env_always_carries_a_path() {
        // tokio_runner.rs's env_clear() + envs(&spec.env) means this map IS
        // the child's whole env: no PATH here, and a bare interpreter name
        // (node, python3, sh, ...) can never be found by exec.
        let app_config = AppConfig {
            name: "web".to_string(),
            script: "app.js".to_string(),
            args: vec![],
            interpreter: Some("node".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let spec = assemble(&app, 0, &test_paths(), None);
        let path = spec
            .env
            .get("PATH")
            .expect("PATH must survive env_clear()+envs(&spec.env)");
        assert!(
            !path.is_empty(),
            "an empty PATH is exactly the ENOENT failure mode"
        );
    }

    #[test]
    fn an_explicit_app_path_overrides_the_seeded_default() {
        let mut app_config = AppConfig {
            name: "web".to_string(),
            script: "app.js".to_string(),
            args: vec![],
            interpreter: Some("node".to_string()),
            ..Default::default()
        };
        app_config
            .env
            .insert("PATH".to_string(), "/opt/custom/bin".to_string());
        let app = normalize(app_config).unwrap();
        let spec = assemble(&app, 0, &test_paths(), None);
        assert_eq!(
            spec.env.get("PATH").map(String::as_str),
            Some("/opt/custom/bin")
        );
    }

    /// The one field on the way to the runner whose default is "closed":
    /// a regression here would silently give an opted-in app `/dev/null`.
    #[test]
    fn the_stdin_flag_reaches_the_spawn_spec() {
        let mut app = AppConfig::minimal("repl", "./repl");
        app.stdin = true;
        let spec = assemble(&normalize(app).unwrap(), 0, &test_paths(), None);
        assert!(spec.stdin);
    }

    #[test]
    fn templates_render_per_instance_in_env_and_args() {
        let mut config = AppConfig {
            name: "z-worker".to_string(),
            script: "bin/worker".to_string(),
            instances: 4,
            args: vec!["--metrics-port".to_string(), "91{{instance}}".to_string()],
            ..Default::default()
        };
        config
            .env
            .insert("Z_WORKER_ID".to_string(), "z-{{instance}}".to_string());
        config.env.insert(
            "Z_DEVICE_ID".to_string(),
            "{{name}}-{{instance}}d".to_string(),
        );

        let app = normalize(config).unwrap();
        let spec = assemble(&app, 2, &test_paths(), None);

        assert_eq!(spec.env.get("Z_WORKER_ID").map(String::as_str), Some("z-2"));
        assert_eq!(
            spec.env.get("Z_DEVICE_ID").map(String::as_str),
            Some("z-worker-2d")
        );
        assert!(spec.args.contains(&"912".to_string()), "{:?}", spec.args);
    }

    #[test]
    fn a_templated_log_path_renders_per_instance() {
        let app = normalize(AppConfig {
            name: "web".to_string(),
            script: "./srv".to_string(),
            instances: 3,
            out_file: Some("/var/log/web-{{instance}}.log".to_string()),
            ..Default::default()
        })
        .unwrap();
        let spec = assemble(&app, 2, &test_paths(), None);
        assert_eq!(spec.out_file, PathBuf::from("/var/log/web-2.log"));
    }

    /// Unlike `channel` (implied by `wait_ready`/`shutdown_with_message`),
    /// nothing implies `stdin`.
    #[test]
    fn nothing_else_turns_stdin_on() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.channel = true;
        app.wait_ready = true;
        app.shutdown_with_message = true;
        let spec = assemble(&normalize(app).unwrap(), 0, &test_paths(), None);
        assert!(spec.channel, "the fixture should still open a channel");
        assert!(!spec.stdin);
    }
}