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
|
use dbus::blocking::{Proxy, SyncConnection, stdintf::org_freedesktop_dbus::Properties};
use std::{sync::Arc, time::Duration};
type Result<T> = std::result::Result<T, Error>;
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Failed to create a DBus connection")]
ConnectError(#[source] dbus::Error),
#[error("Failed to read SystemState property")]
ReadSystemStateError(#[source] dbus::Error),
}
const SYSTEMD_BUS: &str = "org.freedesktop.systemd1";
const SYSTEMD_PATH: &str = "/org/freedesktop/systemd1";
const MANAGER_INTERFACE: &str = "org.freedesktop.systemd1.Manager";
const SYSTEM_STATE: &str = "SystemState";
const SYSTEM_STATE_STARTING: &str = "starting";
const SYSTEM_STATE_INITIALIZING: &str = "initializing";
const SYSTEM_STATE_RUNNING: &str = "running";
const SYSTEM_STATE_DEGRADED: &str = "degraded";
const RPC_TIMEOUT: Duration = Duration::from_secs(1);
/// Returns true if the host is not shutting down or entering maintenance mode or some other weird
/// state.
pub fn is_host_running() -> Result<bool> {
Systemd::new()?.system_is_running()
}
struct Systemd {
pub dbus_connection: Arc<SyncConnection>,
}
impl Systemd {
fn new() -> Result<Self> {
Ok(Self {
dbus_connection: crate::get_connection().map_err(Error::ConnectError)?,
})
}
fn system_is_running(&self) -> Result<bool> {
self.as_manager_object()
.get(MANAGER_INTERFACE, SYSTEM_STATE)
.map(|state: String| {
![
SYSTEM_STATE_STARTING,
SYSTEM_STATE_INITIALIZING,
SYSTEM_STATE_RUNNING,
SYSTEM_STATE_DEGRADED,
]
.contains(&state.as_str())
})
.map_err(Error::ReadSystemStateError)
}
fn as_manager_object(&self) -> Proxy<'_, &SyncConnection> {
Proxy::new(
SYSTEMD_BUS,
SYSTEMD_PATH,
RPC_TIMEOUT,
&self.dbus_connection,
)
}
}
|