refactor: group modules by data-flow stage behind a thin main
This commit is contained in:
1 parent
f9cc94c633
commit
2191a27b82
38 files changed
+104
-88
No files matched your search
@@ -0,0 +1,255 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
mem,
|
||||
os::fd::{AsFd, BorrowedFd},
|
||||
process,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use dbus::Path;
|
||||
|
||||
use crate::{
|
||||
boot_model::{BootState, HANDOFF_UNIT, JobKind, Phase},
|
||||
systemd_link::{
|
||||
link_error::Error,
|
||||
monotonic_clock::monotonic_now,
|
||||
switch_root::Sysroot,
|
||||
systemd_bus::{Scope, Session, Signal},
|
||||
},
|
||||
};
|
||||
|
||||
const RECONNECT_PATIENCE: Duration = Duration::from_secs(60);
|
||||
const SWITCH_ROOT_UNIT: &str = "initrd-switch-root.service";
|
||||
const SHUTDOWN_ROOTS: [&str; 5] = [
|
||||
"poweroff.target",
|
||||
"reboot.target",
|
||||
"halt.target",
|
||||
"kexec.target",
|
||||
"soft-reboot.target",
|
||||
];
|
||||
const SHUTDOWN_FALLBACK_ROOT: &str = "shutdown.target";
|
||||
const SILENT_STATUS: &str = "no";
|
||||
const CONFIGURED_STATUS: &str = "";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum RootRequest {
|
||||
Named(String),
|
||||
ManagerDefault,
|
||||
}
|
||||
|
||||
enum Link {
|
||||
Connected(Session),
|
||||
Connecting { deadline: Instant },
|
||||
}
|
||||
|
||||
impl Link {
|
||||
fn connecting() -> Self {
|
||||
Self::Connecting {
|
||||
deadline: Instant::now() + RECONNECT_PATIENCE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum RootFs {
|
||||
Initrd,
|
||||
SwitchingTo(Sysroot),
|
||||
Host,
|
||||
}
|
||||
|
||||
pub struct Feed {
|
||||
pub connections: u32,
|
||||
scope: Scope,
|
||||
target: RootRequest,
|
||||
link: Link,
|
||||
unit_paths: HashMap<Path<'static>, String>,
|
||||
root_fs: RootFs,
|
||||
gave_origin: bool,
|
||||
}
|
||||
|
||||
impl Feed {
|
||||
#[must_use]
|
||||
pub fn new(phase: Phase, scope: Scope, target: RootRequest) -> Self {
|
||||
Self {
|
||||
connections: 0,
|
||||
root_fs: if phase == Phase::Initrd {
|
||||
RootFs::Initrd
|
||||
} else {
|
||||
RootFs::Host
|
||||
},
|
||||
scope,
|
||||
target,
|
||||
link: Link::connecting(),
|
||||
unit_paths: HashMap::new(),
|
||||
gave_origin: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn session_fd(&self) -> Option<BorrowedFd<'_>> {
|
||||
match &self.link {
|
||||
Link::Connected(session) => Some(session.as_fd()),
|
||||
Link::Connecting { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pump(&mut self, state: &mut BootState) -> Result<(), Error> {
|
||||
if state.manager_exited_at.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
match mem::replace(&mut self.link, Link::connecting()) {
|
||||
Link::Connecting { deadline } => self.connect(state, deadline),
|
||||
Link::Connected(session) => match session.receive() {
|
||||
Ok(signals) => {
|
||||
signals
|
||||
.into_iter()
|
||||
.for_each(|signal| self.apply(&session, state, signal));
|
||||
self.link = Link::Connected(session);
|
||||
Ok(())
|
||||
}
|
||||
Err(_) => self.lose_connection(state),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn connect(&mut self, state: &mut BootState, deadline: Instant) -> Result<(), Error> {
|
||||
match self.open_session(state) {
|
||||
Ok(session) => {
|
||||
self.link = Link::Connected(session);
|
||||
self.connections += 1;
|
||||
Ok(())
|
||||
}
|
||||
Err(_) if Instant::now() < deadline => {
|
||||
self.link = Link::Connecting { deadline };
|
||||
Ok(())
|
||||
}
|
||||
Err(_) => Err(Error::ManagerUnreachable),
|
||||
}
|
||||
}
|
||||
|
||||
fn lose_connection(&mut self, state: &mut BootState) -> Result<(), Error> {
|
||||
match &self.root_fs {
|
||||
RootFs::SwitchingTo(sysroot) => {
|
||||
sysroot.enter()?;
|
||||
self.root_fs = RootFs::Host;
|
||||
self.unit_paths.clear();
|
||||
state.switch_root(monotonic_now());
|
||||
}
|
||||
RootFs::Initrd | RootFs::Host if state.phase == Phase::Shutdown => {
|
||||
state.manager_exited_at = Some(monotonic_now());
|
||||
}
|
||||
RootFs::Initrd | RootFs::Host => state.forget_jobs(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_session(&mut self, state: &mut BootState) -> Result<Session, Error> {
|
||||
let session = Session::open(self.scope)?;
|
||||
session.subscribe()?;
|
||||
if self.scope == Scope::System {
|
||||
session.set_show_status(SILENT_STATUS).ok();
|
||||
}
|
||||
let shutting_down = state.phase == Phase::Shutdown;
|
||||
let jobs: Vec<_> = session
|
||||
.list_jobs()?
|
||||
.into_iter()
|
||||
.filter(|job| shutting_down || job.kind == JobKind::BringsUp)
|
||||
.collect();
|
||||
let requested_root = match &self.target {
|
||||
RootRequest::Named(target) => target.clone(),
|
||||
RootRequest::ManagerDefault if shutting_down => SHUTDOWN_ROOTS
|
||||
.into_iter()
|
||||
.find(|root| {
|
||||
jobs.iter()
|
||||
.any(|job| job.unit == *root && job.kind == JobKind::BringsUp)
|
||||
})
|
||||
.unwrap_or(SHUTDOWN_FALLBACK_ROOT)
|
||||
.to_owned(),
|
||||
RootRequest::ManagerDefault => session.default_target()?,
|
||||
};
|
||||
let milestones = state.milestone_targets.clone();
|
||||
if !self.gave_origin {
|
||||
state.origin = if session.boot_in_progress()? {
|
||||
Duration::ZERO
|
||||
} else {
|
||||
monotonic_now()
|
||||
};
|
||||
self.gave_origin = true;
|
||||
}
|
||||
let root = self
|
||||
.track(&session, state, &requested_root)
|
||||
.unwrap_or(requested_root);
|
||||
if let Some(handoff) = self.track(&session, state, HANDOFF_UNIT) {
|
||||
state.set_handoff(handoff);
|
||||
}
|
||||
jobs.iter()
|
||||
.map(|job| job.unit.as_str())
|
||||
.chain(milestones.iter().map(String::as_str))
|
||||
.for_each(|unit| {
|
||||
self.track(&session, state, unit);
|
||||
});
|
||||
state.set_root(root.clone());
|
||||
let now = monotonic_now();
|
||||
jobs.iter()
|
||||
.for_each(|job| state.queue_job(job.id, &job.unit, job.kind, now));
|
||||
eprintln!(
|
||||
"bootvine: watching {root} in {} as pid {} over {}",
|
||||
state.phase.label(),
|
||||
process::id(),
|
||||
if session.peer_to_peer {
|
||||
"the private socket"
|
||||
} else {
|
||||
"the bus"
|
||||
},
|
||||
);
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
fn track(&mut self, session: &Session, state: &mut BootState, unit: &str) -> Option<String> {
|
||||
if let Some(known) = self.unit_paths.values().find(|known| *known == unit) {
|
||||
return Some(known.clone());
|
||||
}
|
||||
let fetched = session.fetch_unit(unit).ok()?;
|
||||
let canonical = fetched.facts.name.clone();
|
||||
if self.unit_paths.values().any(|known| *known == canonical) {
|
||||
return Some(canonical);
|
||||
}
|
||||
self.unit_paths.insert(fetched.path, canonical.clone());
|
||||
state.track_unit(fetched.facts, fetched.activity);
|
||||
Some(canonical)
|
||||
}
|
||||
|
||||
fn apply(&mut self, session: &Session, state: &mut BootState, signal: Signal) {
|
||||
match signal {
|
||||
Signal::JobNew { id, job, unit } => {
|
||||
let kind = session.job_kind(&job).unwrap_or(JobKind::Unknown);
|
||||
if kind == JobKind::TakesDown && state.phase != Phase::Shutdown {
|
||||
return;
|
||||
}
|
||||
let unit = self.track(session, state, &unit).unwrap_or(unit);
|
||||
if matches!(self.root_fs, RootFs::Initrd)
|
||||
&& unit == SWITCH_ROOT_UNIT
|
||||
&& let Ok(sysroot) = Sysroot::hold()
|
||||
{
|
||||
self.root_fs = RootFs::SwitchingTo(sysroot);
|
||||
}
|
||||
state.queue_job(id, &unit, kind, monotonic_now());
|
||||
}
|
||||
Signal::JobRemoved { id, result } => state.finish_job(id, result, monotonic_now()),
|
||||
Signal::UnitChanged { path, activity } => {
|
||||
if let Some(unit) = self.unit_paths.get(&path) {
|
||||
state.update_activity(unit, activity);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Feed {
|
||||
fn drop(&mut self) {
|
||||
if let Link::Connected(session) = &self.link
|
||||
&& self.scope == Scope::System
|
||||
{
|
||||
session.set_show_status(CONFIGURED_STATUS).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use std::io;
|
||||
|
||||
use dbus::{Error as BusError, arg::TypeMismatchError};
|
||||
use rustix::io::Errno;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("systemd bus: {0}")]
|
||||
Bus(#[from] BusError),
|
||||
#[error("unexpected reply from systemd: {0}")]
|
||||
Reply(#[from] TypeMismatchError),
|
||||
#[error("could not build a method call")]
|
||||
MalformedCall,
|
||||
#[error("the service manager closed the connection")]
|
||||
Disconnected,
|
||||
#[error("console: {0}")]
|
||||
Console(#[from] io::Error),
|
||||
#[error("entering the new root: {0}")]
|
||||
RootSwitch(#[from] Errno),
|
||||
#[error("the service manager did not come back")]
|
||||
ManagerUnreachable,
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use rustix::time::{ClockId, clock_gettime};
|
||||
|
||||
#[must_use]
|
||||
pub fn monotonic_now() -> Duration {
|
||||
let now = clock_gettime(ClockId::Monotonic);
|
||||
Duration::new(
|
||||
now.tv_sec.cast_unsigned(),
|
||||
u32::try_from(now.tv_nsec).unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
use std::os::fd::OwnedFd;
|
||||
|
||||
use rustix::{
|
||||
fs::{Mode, OFlags, open},
|
||||
io::Errno,
|
||||
process::{chdir, chroot, fchdir},
|
||||
};
|
||||
|
||||
const SYSROOT: &str = "/sysroot";
|
||||
pub const INITRD_RELEASE: &str = "/etc/initrd-release";
|
||||
|
||||
pub struct Sysroot {
|
||||
directory: OwnedFd,
|
||||
}
|
||||
|
||||
impl Sysroot {
|
||||
pub fn hold() -> Result<Self, Errno> {
|
||||
let directory = open(
|
||||
SYSROOT,
|
||||
OFlags::DIRECTORY | OFlags::RDONLY | OFlags::CLOEXEC,
|
||||
Mode::empty(),
|
||||
)?;
|
||||
Ok(Self { directory })
|
||||
}
|
||||
|
||||
pub fn enter(&self) -> Result<(), Errno> {
|
||||
fchdir(&self.directory)?;
|
||||
chroot(".")?;
|
||||
chdir("/")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
use std::{
|
||||
iter,
|
||||
os::fd::{AsFd, BorrowedFd},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use dbus::{
|
||||
Message, MessageType, Path,
|
||||
arg::{AppendAll, PropMap, RefArg, Variant},
|
||||
channel::{BusType, Channel},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
boot_model::{ActiveState, Activity, JobKind, JobResult, UnitFacts},
|
||||
systemd_link::link_error::Error,
|
||||
};
|
||||
|
||||
const DESTINATION: &str = "org.freedesktop.systemd1";
|
||||
const MANAGER_PATH: &str = "/org/freedesktop/systemd1";
|
||||
const MANAGER_INTERFACE: &str = "org.freedesktop.systemd1.Manager";
|
||||
const UNIT_INTERFACE: &str = "org.freedesktop.systemd1.Unit";
|
||||
const JOB_INTERFACE: &str = "org.freedesktop.systemd1.Job";
|
||||
const PROPERTIES_INTERFACE: &str = "org.freedesktop.DBus.Properties";
|
||||
const PEER_INTERFACE: &str = "org.freedesktop.DBus.Peer";
|
||||
const BUS_DESTINATION: &str = "org.freedesktop.DBus";
|
||||
const BUS_PATH: &str = "/org/freedesktop/DBus";
|
||||
const PRIVATE_SOCKET: &str = "unix:path=/run/systemd/private";
|
||||
const SIGNAL_RULE: &str = "type='signal',path_namespace='/org/freedesktop/systemd1'";
|
||||
const STOP_JOB: &str = "stop";
|
||||
const CALL_TIMEOUT: Duration = Duration::from_secs(1);
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Scope {
|
||||
System,
|
||||
User,
|
||||
}
|
||||
|
||||
pub enum Signal {
|
||||
JobNew {
|
||||
id: u32,
|
||||
job: Path<'static>,
|
||||
unit: String,
|
||||
},
|
||||
JobRemoved {
|
||||
id: u32,
|
||||
result: JobResult,
|
||||
},
|
||||
UnitChanged {
|
||||
path: Path<'static>,
|
||||
activity: Activity,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct FetchedUnit {
|
||||
pub path: Path<'static>,
|
||||
pub facts: UnitFacts,
|
||||
pub activity: Activity,
|
||||
}
|
||||
|
||||
pub struct JobListing {
|
||||
pub id: u32,
|
||||
pub unit: String,
|
||||
pub kind: JobKind,
|
||||
}
|
||||
|
||||
type ListedJob = (u32, String, String, String, Path<'static>, Path<'static>);
|
||||
|
||||
impl From<ListedJob> for JobListing {
|
||||
fn from((id, unit, kind, ..): ListedJob) -> Self {
|
||||
Self {
|
||||
id,
|
||||
unit,
|
||||
kind: job_kind(&kind),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn job_kind(raw: &str) -> JobKind {
|
||||
if raw == STOP_JOB {
|
||||
JobKind::TakesDown
|
||||
} else {
|
||||
JobKind::BringsUp
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Session {
|
||||
channel: Channel,
|
||||
pub peer_to_peer: bool,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn open(scope: Scope) -> Result<Self, Error> {
|
||||
if scope == Scope::System
|
||||
&& let Ok(channel) = Channel::open_private(PRIVATE_SOCKET)
|
||||
{
|
||||
send_authentication_carrier(&channel)?;
|
||||
return Ok(Self::watching(channel, true));
|
||||
}
|
||||
let bus = match scope {
|
||||
Scope::System => BusType::System,
|
||||
Scope::User => BusType::Session,
|
||||
};
|
||||
let session = Self::watching(Channel::get_private(bus)?, false);
|
||||
session.call(
|
||||
BUS_DESTINATION,
|
||||
BUS_PATH,
|
||||
BUS_DESTINATION,
|
||||
"AddMatch",
|
||||
(SIGNAL_RULE,),
|
||||
)?;
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
fn watching(mut channel: Channel, peer_to_peer: bool) -> Self {
|
||||
channel.set_watch_enabled(true);
|
||||
Self {
|
||||
channel,
|
||||
peer_to_peer,
|
||||
}
|
||||
}
|
||||
|
||||
fn call(
|
||||
&self,
|
||||
destination: &str,
|
||||
path: &str,
|
||||
interface: &str,
|
||||
member: &str,
|
||||
arguments: impl AppendAll,
|
||||
) -> Result<Message, Error> {
|
||||
let Ok(mut call) = Message::new_method_call(destination, path, interface, member) else {
|
||||
return Err(Error::MalformedCall);
|
||||
};
|
||||
call.append_all(arguments);
|
||||
Ok(self.channel.send_with_reply_and_block(call, CALL_TIMEOUT)?)
|
||||
}
|
||||
|
||||
pub fn subscribe(&self) -> Result<(), Error> {
|
||||
self.call(
|
||||
DESTINATION,
|
||||
MANAGER_PATH,
|
||||
MANAGER_INTERFACE,
|
||||
"Subscribe",
|
||||
(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_show_status(&self, mode: &str) -> Result<(), Error> {
|
||||
self.call(
|
||||
DESTINATION,
|
||||
MANAGER_PATH,
|
||||
MANAGER_INTERFACE,
|
||||
"SetShowStatus",
|
||||
(mode,),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn default_target(&self) -> Result<String, Error> {
|
||||
let reply = self.call(
|
||||
DESTINATION,
|
||||
MANAGER_PATH,
|
||||
MANAGER_INTERFACE,
|
||||
"GetDefaultTarget",
|
||||
(),
|
||||
)?;
|
||||
Ok(reply.read1()?)
|
||||
}
|
||||
|
||||
pub fn boot_in_progress(&self) -> Result<bool, Error> {
|
||||
let reply = self.call(
|
||||
DESTINATION,
|
||||
MANAGER_PATH,
|
||||
PROPERTIES_INTERFACE,
|
||||
"Get",
|
||||
(MANAGER_INTERFACE, "FinishTimestampMonotonic"),
|
||||
)?;
|
||||
let finished: Variant<u64> = reply.read1()?;
|
||||
Ok(finished.0 == 0)
|
||||
}
|
||||
|
||||
pub fn list_jobs(&self) -> Result<Vec<JobListing>, Error> {
|
||||
let reply = self.call(DESTINATION, MANAGER_PATH, MANAGER_INTERFACE, "ListJobs", ())?;
|
||||
let listed: Vec<ListedJob> = reply.read1()?;
|
||||
Ok(listed.into_iter().map(JobListing::from).collect())
|
||||
}
|
||||
|
||||
pub fn job_kind(&self, job: &Path) -> Result<JobKind, Error> {
|
||||
let reply = self.call(
|
||||
DESTINATION,
|
||||
job,
|
||||
PROPERTIES_INTERFACE,
|
||||
"Get",
|
||||
(JOB_INTERFACE, "JobType"),
|
||||
)?;
|
||||
let kind: Variant<String> = reply.read1()?;
|
||||
Ok(job_kind(&kind.0))
|
||||
}
|
||||
|
||||
pub fn fetch_unit(&self, name: &str) -> Result<FetchedUnit, Error> {
|
||||
let path: Path<'static> = self
|
||||
.call(
|
||||
DESTINATION,
|
||||
MANAGER_PATH,
|
||||
MANAGER_INTERFACE,
|
||||
"GetUnit",
|
||||
(name,),
|
||||
)?
|
||||
.read1()?;
|
||||
let properties: PropMap = self
|
||||
.call(
|
||||
DESTINATION,
|
||||
&path,
|
||||
PROPERTIES_INTERFACE,
|
||||
"GetAll",
|
||||
(UNIT_INTERFACE,),
|
||||
)?
|
||||
.read1()?;
|
||||
let text = |property: &str| {
|
||||
properties
|
||||
.get(property)
|
||||
.and_then(|value| value.0.as_str())
|
||||
.map(ToOwned::to_owned)
|
||||
};
|
||||
let names = |property: &str| {
|
||||
properties
|
||||
.get(property)
|
||||
.and_then(|value| value.0.as_iter())
|
||||
.map(|items| {
|
||||
items
|
||||
.filter_map(|item| item.as_str().map(ToOwned::to_owned))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
Ok(FetchedUnit {
|
||||
facts: UnitFacts {
|
||||
name: text("Id").unwrap_or_else(|| name.to_owned()),
|
||||
description: text("Description").unwrap_or_default(),
|
||||
after: names("After"),
|
||||
before: names("Before"),
|
||||
},
|
||||
activity: activity_from(&properties),
|
||||
path,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn receive(&self) -> Result<Vec<Signal>, Error> {
|
||||
if self.channel.read_write(Some(Duration::ZERO)).is_err() || !self.channel.is_connected() {
|
||||
return Err(Error::Disconnected);
|
||||
}
|
||||
Ok(iter::from_fn(|| self.channel.pop_message())
|
||||
.filter_map(|message| parse_signal(&message))
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
impl AsFd for Session {
|
||||
fn as_fd(&self) -> BorrowedFd<'_> {
|
||||
unsafe { BorrowedFd::borrow_raw(self.channel.watch().fd) }
|
||||
}
|
||||
}
|
||||
|
||||
fn send_authentication_carrier(channel: &Channel) -> Result<(), Error> {
|
||||
let Ok(mut ping) = Message::new_method_call(DESTINATION, MANAGER_PATH, PEER_INTERFACE, "Ping")
|
||||
else {
|
||||
return Err(Error::MalformedCall);
|
||||
};
|
||||
ping.set_no_reply(true);
|
||||
if channel.send(ping).is_err() {
|
||||
return Err(Error::Disconnected);
|
||||
}
|
||||
channel.flush();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_signal(message: &Message) -> Option<Signal> {
|
||||
if message.msg_type() != MessageType::Signal {
|
||||
return None;
|
||||
}
|
||||
let interface = message.interface()?;
|
||||
let member = message.member()?;
|
||||
match &*interface {
|
||||
MANAGER_INTERFACE => parse_job_signal(message, &member),
|
||||
PROPERTIES_INTERFACE if &*member == "PropertiesChanged" => parse_unit_change(message),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_job_signal(message: &Message, member: &str) -> Option<Signal> {
|
||||
match member {
|
||||
"JobNew" => {
|
||||
let (id, job, unit): (u32, Path<'static>, String) = message.read3().ok()?;
|
||||
Some(Signal::JobNew { id, job, unit })
|
||||
}
|
||||
"JobRemoved" => {
|
||||
let (id, _job, _unit, result): (u32, Path<'static>, String, String) =
|
||||
message.read4().ok()?;
|
||||
Some(Signal::JobRemoved {
|
||||
id,
|
||||
result: JobResult::parse(&result),
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_unit_change(message: &Message) -> Option<Signal> {
|
||||
let (changed_interface, changed, _invalidated): (String, PropMap, Vec<String>) =
|
||||
message.read3().ok()?;
|
||||
if changed_interface != UNIT_INTERFACE {
|
||||
return None;
|
||||
}
|
||||
Some(Signal::UnitChanged {
|
||||
path: message.path()?.into_static(),
|
||||
activity: activity_from(&changed),
|
||||
})
|
||||
}
|
||||
|
||||
fn activity_from(properties: &PropMap) -> Activity {
|
||||
let monotonic = |property: &str| {
|
||||
properties
|
||||
.get(property)
|
||||
.and_then(|value| value.0.as_u64())
|
||||
.filter(|micros| *micros != 0)
|
||||
.map(Duration::from_micros)
|
||||
};
|
||||
Activity {
|
||||
state: properties
|
||||
.get("ActiveState")
|
||||
.and_then(|value| value.0.as_str())
|
||||
.map(ActiveState::parse),
|
||||
inactive_exit: monotonic("InactiveExitTimestampMonotonic"),
|
||||
active_enter: monotonic("ActiveEnterTimestampMonotonic"),
|
||||
active_exit: monotonic("ActiveExitTimestampMonotonic"),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user