shep 0.1.0-alpha.1

The shep binary: a process manager that keeps a flock of long-running processes alive on macOS and Linux, 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
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
//! Renders a [`super::Reading`] as Prometheus text exposition.
//!
//! [`render`] is what `dog::metrics::handle_connection` calls to answer
//! `/metrics`.

use core::fmt::{self, Write as _};

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

use super::Reading;

/// Every [`ProcStatus`] value, in a fixed order — the order [`render`]'s
/// one-series-per-state `shep_sheep_status` rendering walks, so a scrape's
/// series order is stable across calls.
const ALL_STATUSES: [ProcStatus; 6] = [
    ProcStatus::Starting,
    ProcStatus::Online,
    ProcStatus::Stopping,
    ProcStatus::Stopped,
    ProcStatus::Errored,
    ProcStatus::WaitingRestart,
];

/// One `# HELP`/`# TYPE` block and the series beneath it.
struct MetricGroup {
    name: &'static str,
    help: &'static str,
    kind: &'static str,
    series: Vec<String>,
}

impl MetricGroup {
    fn new(name: &'static str, help: &'static str, kind: &'static str) -> Self {
        Self {
            name,
            help,
            kind,
            series: Vec::new(),
        }
    }

    /// Appends one series line, `label_str` already formatted by
    /// [`labels`] (including its own braces, or empty for a label-less
    /// metric).
    fn push(&mut self, label_str: &str, value: impl fmt::Display) {
        let name = self.name;
        let _ = writeln!(self.series_line(), "{name}{label_str} {value}");
    }

    fn series_line(&mut self) -> &mut String {
        self.series.push(String::new());
        self.series.last_mut().expect("just pushed")
    }

    /// Renders this group's `# HELP`/`# TYPE` pair and series, or nothing
    /// at all when it has no series — a metric with no data this scrape
    /// contributes no lines, not an empty pair a scraper would still have
    /// to parse.
    fn render_into(&self, out: &mut String) {
        if self.series.is_empty() {
            return;
        }
        let _ = writeln!(out, "# HELP {} {}", self.name, self.help);
        let _ = writeln!(out, "# TYPE {} {}", self.name, self.kind);
        for line in &self.series {
            out.push_str(line);
        }
    }
}

/// Escapes a label value per the Prometheus text exposition format:
/// backslash, double quote, and newline are the only three characters that
/// need it, and they need it in that order — escaping the backslashes a
/// prior pass introduced would double-escape them.
fn escape_label_value(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for ch in value.chars() {
        match ch {
            '\\' => escaped.push_str(r"\\"),
            '"' => escaped.push_str(r#"\""#),
            '\n' => escaped.push_str(r"\n"),
            other => escaped.push(other),
        }
    }
    escaped
}

/// Formats a label list as `{k1="v1",k2="v2"}`, or an empty string for no
/// labels — the shape a label-less series like `shep_daemon_pid` needs, so
/// [`MetricGroup::push`] can format both cases the same way.
fn labels(pairs: &[(&str, &str)]) -> String {
    if pairs.is_empty() {
        return String::new();
    }
    let mut out = String::from("{");
    for (i, (key, value)) in pairs.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        let _ = write!(out, "{key}=\"{}\"", escape_label_value(value));
    }
    out.push('}');
    out
}

/// `DogSource`'s label value. `DogSource` is `#[non_exhaustive]`, so a kind
/// this client predates renders `unknown` rather than failing to build
/// against a future daemon — the same fallback `output::rows::dog_source_
/// label` uses for the same reason, kept as its own copy here since that
/// one is private to its own module.
fn dog_source_label(source: &DogSource) -> &'static str {
    match source {
        DogSource::BuiltIn => "built-in",
        DogSource::Adopted { .. } => "adopted",
        _ => "unknown",
    }
}

/// Renders `reading` as Prometheus text exposition, format version 0.0.4.
///
/// One `# HELP`/`# TYPE` pair per metric name, every series of a name
/// grouped beneath it, and a trailing newline — the three things a scraper
/// is entitled to and the three a hand-rolled renderer gets wrong.
///
/// Label values are escaped per the exposition format (`\\`, `"`, `\n`).
/// A sheep's name is operator-supplied and reaches this function verbatim,
/// so an unescaped quote in one name would corrupt every series after it in
/// the same response.
#[must_use]
pub fn render(reading: &Reading) -> String {
    let mut cpu = MetricGroup::new(
        "shep_sheep_cpu_percent",
        "Tree CPU as a percentage of one core, over the last sampling window.",
        "gauge",
    );
    let mut memory = MetricGroup::new(
        "shep_sheep_memory_bytes",
        "Tree resident set size in bytes.",
        "gauge",
    );
    let mut restarts = MetricGroup::new(
        "shep_sheep_restart_total",
        "Restart count since registration.",
        "counter",
    );
    let mut uptime = MetricGroup::new(
        "shep_sheep_uptime_seconds",
        "Seconds since this sheep's last successful start.",
        "gauge",
    );
    let mut status = MetricGroup::new(
        "shep_sheep_status",
        "1 for the status this sheep is currently in, 0 for every other status.",
        "gauge",
    );
    let mut dog_up = MetricGroup::new(
        "shep_dog_up",
        "1 when this dog is online, 0 otherwise.",
        "gauge",
    );
    let mut daemon_up = MetricGroup::new(
        "shep_daemon_up",
        "Always 1: the scrape reached the shepherd.",
        "gauge",
    );
    let mut daemon_pid = MetricGroup::new(
        "shep_daemon_pid",
        "The shepherd's own pid, so a restart is visible as a step change.",
        "gauge",
    );
    let mut host_memory_total = MetricGroup::new(
        "shep_host_memory_total_bytes",
        "Total physical memory on the host.",
        "gauge",
    );
    let mut host_memory_used = MetricGroup::new(
        "shep_host_memory_used_bytes",
        "Memory in use on the host, as the platform reports it.",
        "gauge",
    );
    let mut host_processes = MetricGroup::new(
        "shep_host_processes",
        "Number of processes running on the host, the flock included.",
        "gauge",
    );
    let mut host_uptime = MetricGroup::new(
        "shep_host_uptime_seconds",
        "Seconds since the host booted.",
        "gauge",
    );

    for info in &reading.flock {
        if let Some(source) = &info.dog {
            let pairs = [
                ("dog", info.name.as_str()),
                ("source", dog_source_label(source)),
            ];
            let up = i32::from(info.status == ProcStatus::Online);
            dog_up.push(&labels(&pairs), up);
            continue;
        }

        let fold = info.fold.as_deref().unwrap_or("");
        let id_string = info.id.to_string();
        let sheep_pairs = [
            ("sheep", info.name.as_str()),
            ("id", id_string.as_str()),
            ("fold", fold),
        ];
        let sheep_labels = labels(&sheep_pairs);

        if let Some(cpu_percent) = info.cpu_percent {
            cpu.push(&sheep_labels, cpu_percent);
        }
        if let Some(memory_bytes) = info.memory_bytes {
            memory.push(&sheep_labels, memory_bytes);
        }
        restarts.push(&sheep_labels, info.restarts);
        uptime.push(&sheep_labels, info.uptime_ms / 1000);

        for candidate in ALL_STATUSES {
            let candidate_string = candidate.to_string();
            let status_pairs = [
                ("sheep", info.name.as_str()),
                ("id", id_string.as_str()),
                ("fold", fold),
                ("status", candidate_string.as_str()),
            ];
            let value = i32::from(info.status == candidate);
            status.push(&labels(&status_pairs), value);
        }
    }

    daemon_up.push(&labels(&[("version", reading.daemon_version.as_str())]), 1);
    daemon_pid.push("", reading.daemon_pid);

    if let Some(host) = &reading.host {
        host_memory_total.push("", host.memory_total_bytes);
        host_memory_used.push("", host.memory_used_bytes);
        host_processes.push("", host.processes);
        host_uptime.push("", host.uptime_seconds);
    }

    let mut out = String::new();
    for group in [
        &cpu,
        &memory,
        &restarts,
        &uptime,
        &status,
        &dog_up,
        &daemon_up,
        &daemon_pid,
        &host_memory_total,
        &host_memory_used,
        &host_processes,
        &host_uptime,
    ] {
        group.render_into(&mut out);
    }
    out
}

#[cfg(test)]
mod tests {
    use shep_core::protocol::{DogSource, ProcessInfo};
    use shep_core::status::ProcStatus;

    use super::super::{HostReading, Reading};
    use super::render;

    /// A sheep fixture shared by every test below: id `3`, fold `backend`,
    /// online, with a real CPU/memory sample. Fixed rather than
    /// name-derived so the id/fold literals the brief's own assertions
    /// spell out (`id="3"`, `fold="backend"`) stay true regardless of which
    /// test calls this.
    fn sample_info(name: &str) -> ProcessInfo {
        ProcessInfo::builder(3, name, ProcStatus::Online)
            .pid(Some(4242))
            .restarts(2)
            .uptime_ms(65_000)
            .fold(Some("backend".to_string()))
            .cpu_percent(Some(1.5))
            .memory_bytes(Some(2048))
            .build()
    }

    /// A baseline [`Reading`] with an empty flock, a real handshake and a
    /// real host sample — every test overrides only what it cares about via
    /// `..reading()`.
    fn reading() -> Reading {
        Reading {
            flock: vec![],
            daemon_version: "9.9.9".to_string(),
            daemon_pid: 12345,
            host: Some(HostReading {
                memory_total_bytes: 16_000_000_000,
                memory_used_bytes: 8_000_000_000,
                processes: 200,
                uptime_seconds: 3600,
            }),
        }
    }

    /// fails if a sheep with no reading is rendered as a zero. A Grafana
    /// panel averaging invented zeros reports a flock idler than it is, and
    /// the daemon says `None` precisely when it will not make that claim.
    #[test]
    fn a_sheep_with_no_reading_contributes_no_series() {
        let mut info = sample_info("web");
        info.cpu_percent = None;
        info.memory_bytes = None;
        let text = render(&Reading {
            flock: vec![info],
            ..reading()
        });
        assert!(!text.contains("shep_sheep_cpu_percent{"));
        assert!(!text.contains("shep_sheep_memory_bytes{"));
        // The counters do not depend on a sample and must still be there.
        assert!(text.contains("shep_sheep_restart_total{"));
    }

    /// fails if a status becomes an ordinal. `shep_sheep_status 4` is not a
    /// metric anyone can write an alert against without the enum's
    /// declaration order in front of them.
    #[test]
    fn status_is_a_label_with_one_series_per_state() {
        let mut info = sample_info("web");
        info.status = ProcStatus::Errored;
        let text = render(&Reading {
            flock: vec![info],
            ..reading()
        });
        assert!(text.contains(
            r#"shep_sheep_status{sheep="web",id="3",fold="backend",status="errored"} 1"#
        ));
        assert!(text.contains(r#"status="online"} 0"#));
    }

    /// fails if a label value goes out unescaped. A sheep's name is
    /// operator-supplied and reaches the renderer verbatim; one quote in one
    /// name corrupts every series after it in the same response, and the
    /// scraper reports a parse error rather than a bad name.
    #[test]
    fn a_label_value_is_escaped_so_one_odd_name_cannot_corrupt_the_response() {
        let text = render(&Reading {
            flock: vec![sample_info(r#"we"b\x"#)],
            ..reading()
        });
        // Every line must parse as `name{labels} value` — checked before
        // the exact-string assertion below, so a broken escape reddens
        // *here* rather than only on that literal check (Step 5's own
        // instruction: the loop has to be the one doing the catching).
        //
        // Escape-aware, not the brief's literal `line.matches('"').count()
        // % 2` — that naive count is invariant to escaping (a `\"` keeps
        // the same one quote character an unescaped `"` would have;
        // escaping only ever inserts backslashes, it never removes or
        // pairs a quote), so for this exact fixture (one embedded quote —
        // an odd count) it is 7 either way, and the naive assertion
        // reddens on a *correct* implementation just as readily as a
        // broken one — verified with a standalone script before writing
        // this, not assumed. Counting only quotes not preceded by a
        // backslash is what actually distinguishes "three real delimiters,
        // six real quotes, balanced" (this implementation) from "an extra
        // real delimiter, seven, unbalanced" (the Step 5 mutation below).
        for line in text
            .lines()
            .filter(|l| !l.starts_with('#') && !l.is_empty())
        {
            let mut real_quotes = 0;
            let mut chars = line.chars();
            while let Some(ch) = chars.next() {
                if ch == '\\' {
                    chars.next(); // escaped char, not a delimiter
                } else if ch == '"' {
                    real_quotes += 1;
                }
            }
            assert_eq!(real_quotes % 2, 0, "unbalanced quotes: {line}");
        }
        assert!(text.contains(r#"sheep="we\"b\\x""#));
    }

    /// fails if a dog that is registered and dead reports nothing. "Is the
    /// monitoring up" is the one question monitoring cannot answer about
    /// itself, and a missing series is not an answer an alert can fire on.
    /// The fixture is a dog whose binary would not spawn — registered and
    /// `Errored`, which is exactly what a bad `adopt` produces.
    #[test]
    fn a_dog_that_is_down_reports_zero_rather_than_nothing() {
        let mut dead = sample_info("bark");
        dead.status = ProcStatus::Errored;
        dead.dog = Some(DogSource::BuiltIn);
        let text = render(&Reading {
            flock: vec![dead],
            ..reading()
        });
        assert!(text.contains(r#"shep_dog_up{dog="bark",source="built-in"} 0"#));
        assert!(
            !text.contains(r#"shep_sheep_status{sheep="bark""#),
            "a dog is not reported as a sheep"
        );
    }

    /// fails if a metric name is emitted without exactly one HELP and one
    /// TYPE, or if a name's series are not contiguous. Both are format
    /// requirements a scraper rejects the whole response over, and both are
    /// what a renderer built one series at a time gets wrong.
    #[test]
    fn every_metric_name_carries_one_help_one_type_and_contiguous_series() {
        let mut dog = sample_info("bark");
        dog.dog = Some(DogSource::BuiltIn);
        let mut idle = sample_info("worker");
        idle.cpu_percent = None;
        idle.memory_bytes = None;
        let text = render(&Reading {
            flock: vec![sample_info("web"), idle, dog],
            ..reading()
        });
        let lines: Vec<&str> = text.lines().collect();

        let names = [
            "shep_sheep_cpu_percent",
            "shep_sheep_memory_bytes",
            "shep_sheep_restart_total",
            "shep_sheep_uptime_seconds",
            "shep_sheep_status",
            "shep_dog_up",
            "shep_daemon_up",
            "shep_daemon_pid",
            "shep_host_memory_total_bytes",
            "shep_host_memory_used_bytes",
            "shep_host_processes",
            "shep_host_uptime_seconds",
        ];

        let is_series_for = |line: &str, name: &str| {
            line.strip_prefix(name)
                .is_some_and(|rest| rest.starts_with('{') || rest.starts_with(' '))
        };

        for name in names {
            let help_count = lines
                .iter()
                .filter(|l| l.starts_with(&format!("# HELP {name} ")))
                .count();
            let type_count = lines
                .iter()
                .filter(|l| l.starts_with(&format!("# TYPE {name} ")))
                .count();
            assert_eq!(help_count, 1, "{name} must carry exactly one HELP line");
            assert_eq!(type_count, 1, "{name} must carry exactly one TYPE line");

            let series_indices: Vec<usize> = lines
                .iter()
                .enumerate()
                .filter(|(_, l)| is_series_for(l, name))
                .map(|(i, _)| i)
                .collect();
            assert!(
                !series_indices.is_empty(),
                "{name} must have at least one series in this fixture"
            );
            let first = *series_indices.first().unwrap();
            let last = *series_indices.last().unwrap();
            assert_eq!(
                last - first + 1,
                series_indices.len(),
                "{name}'s series are not contiguous: {series_indices:?}"
            );
        }
        assert!(text.ends_with('\n'), "exposition must end with a newline");
    }

    /// The escaping helper, tested directly per the brief's own Step 3.
    #[test]
    fn escape_label_value_handles_backslash_quote_and_newline() {
        assert_eq!(super::escape_label_value("plain"), "plain");
        assert_eq!(super::escape_label_value(r#"a"b"#), r#"a\"b"#);
        assert_eq!(super::escape_label_value(r"a\b"), r"a\\b");
        assert_eq!(super::escape_label_value("a\nb"), r"a\nb");
        assert_eq!(super::escape_label_value(r#"we"b\x"#), r#"we\"b\\x"#);
    }
}