Skip to main content

systemd_transient/
reusable.rs

1use crate::error::SystemdTransientError;
2use crate::{SystemdTransientManager, TransientUnitHandle, UnitExit, UnitProperty};
3
4pub(crate) struct Opts {
5  pub(crate) name: String,
6  pub(crate) props: Vec<UnitProperty>,
7}
8
9pub struct ReusableTransientUnit {
10  pub(crate) opts: Opts,
11  pub(crate) unit_handle: Option<TransientUnitHandle>,
12  pub(crate) systemd_manager: SystemdTransientManager,
13}
14
15impl ReusableTransientUnit {
16  pub async fn start(&mut self) -> Result<(), SystemdTransientError> {
17    if self.unit_handle.is_some() {
18      return Err(SystemdTransientError::UnitAlreadyRunning {
19        name: self.opts.name.to_owned(),
20      });
21    }
22
23    let handle = self
24      .systemd_manager
25      .start(self.opts.name.to_owned(), self.opts.props.to_vec())
26      .await?;
27
28    self.unit_handle = Some(handle);
29
30    Ok(())
31  }
32
33  pub async fn stop(&mut self) -> Result<(), SystemdTransientError> {
34    match self.unit_handle.take() {
35      Some(handle) => handle.stop().await?,
36      None => {
37        return Err(SystemdTransientError::UnitNotRunning {
38          name: self.opts.name.to_owned(),
39        });
40      }
41    };
42
43    Ok(())
44  }
45
46  pub async fn wait_for_exit(&self) -> Result<UnitExit, SystemdTransientError> {
47    let handle =
48      self
49        .unit_handle
50        .as_ref()
51        .ok_or_else(|| SystemdTransientError::UnitNotRunning {
52          name: self.opts.name.to_owned(),
53        })?;
54
55    handle.wait_for_exit().await
56  }
57}