Skip to main content

sys_lib/process/
launch.rs

1//! How the program was started: so a service can choose its behaviour without
2//! configuration. Each answer carries its evidence, and environment variables
3//! are weak evidence: any parent can set them.
4
5use std::{
6    io::{IsTerminal, stdin, stdout},
7    sync::OnceLock,
8};
9
10use crate::virt::{Evidence, Strength};
11
12/// What started this program.
13#[derive(Clone, Debug, PartialEq, Eq)]
14#[non_exhaustive]
15pub struct Launch {
16    /// The launcher.
17    pub by: Launcher,
18    /// "site.service", the launchd label, the Windows service name.
19    pub unit: Option<&'static str>,
20    /// systemd's `NOTIFY_SOCKET` is set: readiness can be reported. Sending the
21    /// message is the service kernel's job.
22    pub notify_socket: bool,
23    /// What the answer rests on.
24    pub evidence: Vec<Evidence>,
25}
26
27/// What started this program.
28#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
29#[non_exhaustive]
30pub enum Launcher {
31    /// systemd.
32    Systemd,
33    /// launchd.
34    Launchd,
35    /// The Windows service control manager.
36    WindowsService,
37    /// This program is the init process of a container.
38    ContainerInit,
39    /// This program is the init process of the machine.
40    Init,
41    /// A terminal.
42    Terminal,
43    /// An SSH session.
44    Ssh,
45    /// cron.
46    Cron,
47    /// None of these.
48    Unknown,
49}
50
51/// What a platform found, for [`decide`].
52#[derive(Clone, Debug, Default, PartialEq, Eq)]
53pub(crate) struct LaunchFacts {
54    /// A service manager: the launcher, its unit, and how sure.
55    pub(crate) service: Option<(Launcher, Option<String>, Strength)>,
56    /// This process is process 1.
57    pub(crate) is_pid1: bool,
58    /// `NOTIFY_SOCKET` is set.
59    pub(crate) notify_socket: bool,
60    /// `SSH_CONNECTION` is set.
61    pub(crate) ssh: bool,
62    /// Strong evidence of cron (the `cron.service` cgroup).
63    pub(crate) cron: bool,
64}
65
66/// How this program was started. Decided at the first call.
67///
68/// ```
69/// use sys_lib as sys;
70///
71/// match sys::process::launch().by {
72///     sys::process::Launcher::Systemd => { /* JSON logs to the journal; report readiness */ }
73///     sys::process::Launcher::Terminal => { /* human-readable logs */ }
74///     _ => {}
75/// }
76/// ```
77#[must_use]
78pub fn launch() -> &'static Launch {
79    static FACTS: OnceLock<Launch> = OnceLock::new();
80    FACTS.get_or_init(|| {
81        decide(
82            crate::sys::launch(),
83            crate::virt::is_container(),
84            stdin().is_terminal() || stdout().is_terminal(),
85        )
86    })
87}
88
89/// Started by a service manager or an orchestrator.
90#[must_use]
91pub fn is_service() -> bool {
92    matches!(
93        launch().by,
94        Launcher::Systemd | Launcher::Launchd | Launcher::WindowsService | Launcher::ContainerInit
95    )
96}
97
98/// Standard input and output are both a terminal. A live reading: a program can
99/// have its streams redirected.
100#[must_use]
101pub fn is_interactive() -> bool {
102    stdin().is_terminal() && stdout().is_terminal()
103}
104
105/// The first answer wins: a service manager and an init role are facts about
106/// this process; a terminal, SSH, and the like describe how it is attached.
107pub(crate) fn decide(facts: LaunchFacts, in_container: bool, terminal: bool) -> Launch {
108    let mut evidence = Vec::new();
109    let mut note = |check, strength| evidence.push(Evidence { check, strength });
110    let mut unit = None;
111    let by = if let Some((by, name, strength)) = facts.service {
112        unit = name.map(crate::os::keep);
113        note("service manager", strength);
114        by
115    } else if facts.is_pid1 && in_container {
116        note("process id 1 in a container", Strength::Strong);
117        Launcher::ContainerInit
118    } else if facts.is_pid1 {
119        note("process id 1", Strength::Strong);
120        Launcher::Init
121    } else if facts.cron {
122        note("cron.service cgroup", Strength::Strong);
123        Launcher::Cron
124    } else if terminal && facts.ssh {
125        note("SSH_CONNECTION", Strength::Weak);
126        Launcher::Ssh
127    } else if terminal {
128        note("terminal", Strength::Strong);
129        Launcher::Terminal
130    } else if facts.ssh {
131        note("SSH_CONNECTION", Strength::Weak);
132        Launcher::Ssh
133    } else {
134        Launcher::Unknown
135    };
136    Launch {
137        by,
138        unit,
139        notify_socket: facts.notify_socket,
140        evidence,
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn test_launch_order() {
150        let service = LaunchFacts {
151            service: Some((
152                Launcher::Systemd,
153                Some("site.service".into()),
154                Strength::Strong,
155            )),
156            notify_socket: true,
157            ..LaunchFacts::default()
158        };
159        let l = decide(service, true, true);
160        assert_eq!(l.by, Launcher::Systemd);
161        assert_eq!(l.unit, Some("site.service"));
162        assert!(l.notify_socket);
163
164        let pid1 = LaunchFacts {
165            is_pid1: true,
166            ..LaunchFacts::default()
167        };
168        assert_eq!(
169            decide(pid1.clone(), true, false).by,
170            Launcher::ContainerInit
171        );
172        assert_eq!(decide(pid1, false, false).by, Launcher::Init);
173
174        let cron = LaunchFacts {
175            cron: true,
176            ..LaunchFacts::default()
177        };
178        assert_eq!(decide(cron, false, false).by, Launcher::Cron);
179
180        let ssh = LaunchFacts {
181            ssh: true,
182            ..LaunchFacts::default()
183        };
184        let l = decide(ssh, false, true);
185        assert_eq!(l.by, Launcher::Ssh);
186        assert_eq!(l.evidence[0].strength, Strength::Weak);
187
188        assert_eq!(
189            decide(LaunchFacts::default(), false, true).by,
190            Launcher::Terminal
191        );
192        let l = decide(LaunchFacts::default(), false, false);
193        assert_eq!(l.by, Launcher::Unknown);
194        assert!(l.evidence.is_empty());
195    }
196
197    #[test]
198    fn test_launch_live_is_cached() {
199        assert!(std::ptr::eq(launch(), launch()));
200        let _ = (is_service(), is_interactive());
201    }
202}