device-daemon-core 0.0.1

Reusable async daemon and MQTT infrastructure for device clients
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
//! Shared operating-system service management for device daemons.

use anyhow::{bail, Context, Result};
use service_manager::{
    RestartPolicy, ServiceInstallCtx, ServiceLabel, ServiceManager, ServiceStartCtx, ServiceStatus,
    ServiceStatusCtx, ServiceStopCtx, ServiceUninstallCtx,
};
use std::{
    collections::BTreeSet,
    ffi::OsString,
    path::{Path, PathBuf},
    process::Command,
    str::FromStr,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServiceAction {
    Install,
    Uninstall,
    Start,
    Stop,
    Status,
    List,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServiceScope {
    User,
    System,
}

impl ServiceScope {
    const fn as_service_level(self) -> service_manager::ServiceLevel {
        match self {
            Self::User => service_manager::ServiceLevel::User,
            Self::System => service_manager::ServiceLevel::System,
        }
    }
}

/// Application-specific values used by the shared service operations.
#[derive(Debug, Clone)]
pub struct ServiceDefinition {
    /// Base name used for the default service and for finding its instances.
    pub application: String,
    /// Explicit service name; listing actions interpret this as a prefix.
    pub name: Option<String>,
    pub scope: ServiceScope,
    /// User account for a system-wide service.
    pub run_as: Option<String>,
    /// Launch details are required only when installing.
    pub launch: Option<ServiceLaunch>,
}

#[derive(Debug, Clone)]
pub struct ServiceLaunch {
    pub program: PathBuf,
    pub args: Vec<OsString>,
    pub working_directory: Option<PathBuf>,
}

impl ServiceLaunch {
    /// Create a launch builder with the current executable and a config path.
    ///
    /// The default arguments contain `--config <absolute-path>`, and the
    /// working directory is set to the config file's parent directory.
    pub fn builder(config_path: impl AsRef<Path>) -> Result<ServiceLaunchBuilder> {
        let program = std::env::current_exe().context("Cannot determine the executable path")?;
        let config_path = absolute_path(config_path.as_ref())?;
        let working_directory = config_path.parent().map(PathBuf::from);
        let args = vec![OsString::from("--config"), config_path.into_os_string()];

        Ok(ServiceLaunchBuilder {
            launch: Self {
                program,
                args,
                working_directory,
            },
        })
    }
}

/// Builder for a service launch initialized from a configuration file.
pub struct ServiceLaunchBuilder {
    launch: ServiceLaunch,
}

impl ServiceLaunchBuilder {
    /// Override the executable used to launch the service.
    pub fn program(mut self, program: impl Into<PathBuf>) -> Self {
        self.launch.program = program.into();
        self
    }

    /// Replace the launch arguments, including the default config argument.
    pub fn args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<OsString>,
    {
        self.launch.args = args.into_iter().map(Into::into).collect();
        self
    }

    /// Append an application-specific launch argument.
    pub fn arg(mut self, arg: impl Into<OsString>) -> Self {
        self.launch.args.push(arg.into());
        self
    }

    /// Override the launch working directory; pass `None` to unset it.
    pub fn working_directory(mut self, path: Option<PathBuf>) -> Self {
        self.launch.working_directory = path;
        self
    }

    /// Finish building the service launch.
    pub fn build(self) -> ServiceLaunch {
        self.launch
    }
}

pub fn manage(action: ServiceAction, definition: &ServiceDefinition) -> Result<()> {
    validate_application_name(&definition.application)?;
    let mut manager = <dyn ServiceManager>::native()
        .context("Cannot detect a supported operating-system service manager")?;
    manager
        .set_level(definition.scope.as_service_level())
        .context("Service manager does not support the requested scope")?;

    match action {
        ServiceAction::Install => {
            let label = service_label(
                definition
                    .name
                    .as_deref()
                    .unwrap_or(&definition.application),
            )?;
            install(manager.as_ref(), label, definition)
        }
        ServiceAction::Uninstall => {
            let Some(label) = definition.name.as_deref().map(service_label).transpose()? else {
                list_services(manager.as_ref(), definition, None)?;
                bail!("Specify --name to uninstall a service; no service was removed");
            };
            let status = manager
                .status(ServiceStatusCtx {
                    label: label.clone(),
                })
                .with_context(|| format!("Cannot read status for service {label}"))?;
            if status == ServiceStatus::Running {
                manager
                    .stop(ServiceStopCtx {
                        label: label.clone(),
                    })
                    .with_context(|| format!("Cannot stop service {label}"))?;
            }
            manager
                .uninstall(ServiceUninstallCtx {
                    label: label.clone(),
                })
                .with_context(|| format!("Cannot uninstall service {label}"))?;
            log::info!("Service {label} uninstalled");
            Ok(())
        }
        ServiceAction::Start => {
            let label = required_service_label(definition, "start")?;
            manager
                .start(ServiceStartCtx {
                    label: label.clone(),
                })
                .with_context(|| format!("Cannot start service {label}"))?;
            log::info!("Service {label} started");
            Ok(())
        }
        ServiceAction::Stop => {
            let label = required_service_label(definition, "stop")?;
            manager
                .stop(ServiceStopCtx {
                    label: label.clone(),
                })
                .with_context(|| format!("Cannot stop service {label}"))?;
            log::info!("Service {label} stopped");
            Ok(())
        }
        ServiceAction::Status => {
            if let Some(name) = definition.name.as_deref() {
                let label = service_label(name)?;
                let status = manager
                    .status(ServiceStatusCtx {
                        label: label.clone(),
                    })
                    .with_context(|| format!("Cannot read status for service {label}"))?;
                println!("{label}: {status:?}");
                Ok(())
            } else {
                list_services(manager.as_ref(), definition, None)
            }
        }
        ServiceAction::List => {
            list_services(manager.as_ref(), definition, definition.name.as_deref())
        }
    }
}

fn validate_application_name(application: &str) -> Result<()> {
    if application.trim().is_empty() {
        bail!("Service application name must not be empty");
    }
    service_label(application)?;
    Ok(())
}

fn required_service_label(definition: &ServiceDefinition, action: &str) -> Result<ServiceLabel> {
    let name = definition
        .name
        .as_deref()
        .with_context(|| format!("Specify --name to {action} a service"))?;
    service_label(name)
}

fn service_label(name: &str) -> Result<ServiceLabel> {
    ServiceLabel::from_str(name).with_context(|| format!("Invalid service name '{name}'"))
}

fn list_services(
    manager: &dyn ServiceManager,
    definition: &ServiceDefinition,
    name_prefix: Option<&str>,
) -> Result<()> {
    let mut command = Command::new("systemctl");
    match definition.scope {
        ServiceScope::User => {
            command.arg("--user");
        }
        ServiceScope::System => {
            command.arg("--system");
        }
    }
    let output = command
        .args([
            "list-unit-files",
            "--type=service",
            "--no-legend",
            "--no-pager",
        ])
        .output()
        .context("Cannot run systemctl to list application services")?;
    if !output.status.success() {
        let error = String::from_utf8_lossy(&output.stderr);
        bail!("systemctl could not list services: {}", error.trim());
    }

    let services = matching_systemd_service_names(
        &String::from_utf8_lossy(&output.stdout),
        &definition.application,
        name_prefix,
    );
    if services.is_empty() {
        println!(
            "No matching {} services found in {:?} scope.",
            definition.application, definition.scope
        );
        return Ok(());
    }
    for name in services {
        let label = service_label(&name)?;
        let status = manager
            .status(ServiceStatusCtx {
                label: label.clone(),
            })
            .with_context(|| format!("Cannot read status for service {label}"))?;
        println!("{label}: {status:?}");
    }
    Ok(())
}

fn matching_systemd_service_names(
    output: &str,
    application: &str,
    name_prefix: Option<&str>,
) -> BTreeSet<String> {
    output
        .lines()
        .filter_map(|line| line.split_whitespace().next())
        .filter_map(|unit| unit.strip_suffix(".service"))
        .filter(|name| *name == application || name.starts_with(&format!("{application}-")))
        .filter(|name| name_prefix.is_none_or(|prefix| name.starts_with(prefix)))
        .filter(|name| !name.ends_with('@'))
        .map(str::to_owned)
        .collect()
}

fn install(
    manager: &dyn ServiceManager,
    label: ServiceLabel,
    definition: &ServiceDefinition,
) -> Result<()> {
    let launch = definition
        .launch
        .as_ref()
        .context("Service launch details are required for installation")?;
    let username = match definition.scope {
        ServiceScope::User => {
            if definition.run_as.is_some() {
                bail!("--run-as is only valid with --scope system");
            }
            None
        }
        ServiceScope::System => Some(
            definition
                .run_as
                .as_ref()
                .filter(|username| !username.trim().is_empty())
                .context("--run-as USER is required for a system-wide service")?
                .clone(),
        ),
    };

    let context = ServiceInstallCtx {
        label: label.clone(),
        program: launch.program.clone(),
        args: launch.args.clone(),
        contents: None,
        username,
        working_directory: launch.working_directory.clone(),
        environment: None,
        autostart: true,
        restart_policy: RestartPolicy::Always {
            delay_secs: Some(30),
        },
    };
    manager
        .install(context)
        .with_context(|| format!("Cannot install service {label}"))?;
    manager
        .start(ServiceStartCtx {
            label: label.clone(),
        })
        .with_context(|| format!("Service {label} installed but failed to start"))?;
    log::info!("Service {label} installed and started");
    Ok(())
}

/// Make a relative configuration path absolute for a service launch command.
pub fn absolute_path(path: &Path) -> Result<PathBuf> {
    if path.is_absolute() {
        Ok(path.to_owned())
    } else {
        Ok(std::env::current_dir()
            .context("Cannot determine current directory")?
            .join(path))
    }
}

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

    #[test]
    fn service_launch_builder_sets_and_overrides_defaults() {
        let config_path = Path::new("config.yml");
        let absolute_config_path = absolute_path(config_path).unwrap();
        let launch = ServiceLaunch::builder(config_path)
            .unwrap()
            .arg("daemon")
            .build();

        assert_eq!(launch.program, std::env::current_exe().unwrap());
        assert_eq!(
            launch.args,
            vec![
                OsString::from("--config"),
                absolute_config_path.clone().into_os_string(),
                OsString::from("daemon"),
            ]
        );
        assert_eq!(
            launch.working_directory,
            absolute_config_path.parent().map(PathBuf::from)
        );

        let launch = ServiceLaunch::builder(config_path)
            .unwrap()
            .program("/custom/program")
            .args(["--custom"])
            .working_directory(None)
            .build();
        assert_eq!(launch.program, PathBuf::from("/custom/program"));
        assert_eq!(launch.args, vec![OsString::from("--custom")]);
        assert_eq!(launch.working_directory, None);
    }

    #[test]
    fn service_listing_matches_configured_application_names_only() {
        let output = "\
steca-mqtt.service enabled enabled
steca-mqtt-test.service disabled enabled
steca-mqtt@.service disabled enabled
abl-evcc.service enabled enabled
other.service enabled enabled
";

        assert_eq!(
            matching_systemd_service_names(output, "steca-mqtt", None),
            BTreeSet::from(["steca-mqtt".to_owned(), "steca-mqtt-test".to_owned()])
        );
        assert_eq!(
            matching_systemd_service_names(output, "abl-evcc", Some("abl-evcc")),
            BTreeSet::from(["abl-evcc".to_owned()])
        );
    }
}