Skip to main content

daemon_detect/
identity.rs

1//! The service identity a daemon detects itself under.
2
3use crate::markers::DaemonMarkers;
4use crate::state::DaemonState;
5
6/// How this process is named as an OS service.
7///
8/// Combines the binary name (used by systemd and Windows), a
9/// reverse-DNS label prefix (used by launchd), and an instance
10/// discriminator (a port, an identity key, …) so one binary can run
11/// multiple service instances.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct ServiceIdentity {
14    binary_name: String,
15    launchd_prefix: String,
16    instance: String,
17}
18
19impl ServiceIdentity {
20    /// Describe a service instance.
21    ///
22    /// - `binary_name` — the installed binary, e.g. `my-daemon`;
23    /// - `launchd_prefix` — the reverse-DNS launchd prefix, e.g.
24    ///   `com.example.my-daemon`;
25    /// - `instance` — the per-instance suffix, e.g. an HTTP port or a node
26    ///   identity key.
27    #[must_use]
28    pub fn new(
29        binary_name: impl Into<String>,
30        launchd_prefix: impl Into<String>,
31        instance: impl Into<String>,
32    ) -> Self {
33        Self {
34            binary_name: binary_name.into(),
35            launchd_prefix: launchd_prefix.into(),
36            instance: instance.into(),
37        }
38    }
39
40    /// The macOS launchd label: `{launchd_prefix}.{instance}`.
41    #[must_use]
42    pub fn launchd_label(&self) -> String {
43        format!("{}.{}", self.launchd_prefix, self.instance)
44    }
45
46    /// The Linux systemd template-unit name:
47    /// `{binary_name}@{instance}.service`.
48    #[must_use]
49    pub fn systemd_unit_name(&self) -> String {
50        format!("{}@{}.service", self.binary_name, self.instance)
51    }
52
53    /// The Windows service name: `{binary_name}-{instance}`.
54    #[must_use]
55    pub fn windows_service_name(&self) -> String {
56        format!("{}-{}", self.binary_name, self.instance)
57    }
58
59    /// The service label for the platform this process runs on.
60    #[must_use]
61    pub fn service_label(&self) -> String {
62        if cfg!(target_os = "macos") {
63            self.launchd_label()
64        } else if cfg!(windows) {
65            self.windows_service_name()
66        } else {
67            self.systemd_unit_name()
68        }
69    }
70
71    /// Full daemon detection for this identity: whether the process
72    /// is a daemon and, when it is, the derived service label and
73    /// system-versus-user mode.
74    #[must_use]
75    pub fn detect(&self, markers: &DaemonMarkers) -> DaemonState {
76        crate::platform::detect_impl(self, markers)
77    }
78}