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
use crate::systemd::dbus_manager;
use crate::systemd::dbus_unit;
use crate::systemd::UnitManager;
use crate::systemd::UnitStatus;

use crate::{error::Error, systemd::dbus_manager::ManagerProxy};
use std::str::FromStr;
use std::sync;
use std::thread;
use std::{collections::HashSet, result::Result, time::Duration};
use zbus::zvariant::OwnedObjectPath;

use super::SystemStatus;

pub struct DbusServiceManager<'a> {
    connection: &'a zbus::blocking::Connection,
    proxy: ManagerProxy<'a>,
}

pub struct DbusUnitManager<'a> {
    proxy: dbus_unit::UnitProxy<'a>, // Proxy<'static, &'a Connection>,
}

pub struct DbusUnitStatus {
    name: String,
    description: String,
    active_state: String,
    address: OwnedObjectPath,
}

impl UnitStatus for DbusUnitStatus {
    fn name(&self) -> &str {
        &self.name
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn active_state(&self) -> &str {
        &self.active_state
    }
}

#[derive(Debug)]
pub struct UnitFile {
    pub unit_name: String,
    pub status: String,
}

/// A tuple representation of `UnitStatus` for use in the dbus API.
type UnitStatusTuple = (
    String,
    String,
    String,
    String,
    String,
    String,
    OwnedObjectPath,
    u32,
    String,
    OwnedObjectPath,
);

#[derive(Hash, Eq, PartialEq)]
pub struct Job {
    path: OwnedObjectPath,
}

pub struct DbusJobSet<'a> {
    manager: &'a DbusServiceManager<'a>,
    job_removed_stream: Option<dbus_manager::JobRemovedIterator<'a>>,
    jobs: HashSet<Job>,
}

impl<'a> DbusJobSet<'a> {
    fn new(manager: &'a DbusServiceManager<'a>) -> Result<DbusJobSet<'a>, Error> {
        let job_removed_stream = Some(manager.proxy.receive_job_removed()?);
        Ok(DbusJobSet {
            manager,
            job_removed_stream,
            jobs: HashSet::new(),
        })
    }
}

impl<'a> super::JobSet for DbusJobSet<'a> {
    fn reload_unit(&mut self, unit_name: &str) -> Result<(), Error> {
        let path = self.manager.proxy.reload_unit(unit_name, "replace")?;
        self.jobs.insert(Job { path });
        Ok(())
    }

    fn restart_unit(&mut self, unit_name: &str) -> Result<(), Error> {
        let path = self.manager.proxy.restart_unit(unit_name, "replace")?;
        self.jobs.insert(Job { path });
        Ok(())
    }

    fn start_unit(&mut self, unit_name: &str) -> Result<(), Error> {
        let path = self.manager.proxy.start_unit(unit_name, "replace")?;
        self.jobs.insert(Job { path });
        Ok(())
    }

    fn stop_unit(&mut self, unit_name: &str) -> Result<(), Error> {
        let path = self.manager.proxy.stop_unit(unit_name, "replace")?;
        self.jobs.insert(Job { path });
        Ok(())
    }

    fn wait_for_all<F>(&mut self, job_handler: F, timeout: Duration) -> Result<(), Error>
    where
        F: Fn(&str, &str) + Send + 'static,
    {
        if self.jobs.is_empty() {
            return Ok(());
        }

        if let Some(job_removed_stream) = self.job_removed_stream.take() {
            let (tx, rx) = sync::mpsc::channel();

            thread::scope(|s| {
                let _: thread::ScopedJoinHandle<Result<(), Error>> = s.spawn(move || {
                    for job_removed in job_removed_stream {
                        let job = Job {
                            path: OwnedObjectPath::from(job_removed.args()?.job().clone()),
                        };
                        self.jobs.remove(&job);

                        if let Ok(args) = job_removed.args() {
                            job_handler(args.unit, args.result);
                        }

                        if self.jobs.is_empty() {
                            break;
                        }
                    }

                    let _ = tx.send(());

                    Ok(())
                });

                rx.recv_timeout(timeout)
                    .map_err(|e| Error::SdSwitch(e.to_string()))
            })
        } else {
            Ok(())
        }
    }
}

impl<'a> Drop for DbusServiceManager<'a> {
    fn drop(&mut self) {
        if let Err(err) = self.proxy.unsubscribe() {
            eprintln!("Error unsubscribing from proxy: {}", err);
        }
    }
}

impl<'a> DbusServiceManager<'a> {
    pub fn new(
        connection: &'a zbus::blocking::Connection,
    ) -> Result<DbusServiceManager<'a>, Error> {
        let proxy = ManagerProxy::new(connection)?;

        proxy.subscribe()?;

        Ok(DbusServiceManager { connection, proxy })
    }
}

fn to_unit_status(t: UnitStatusTuple) -> DbusUnitStatus {
    DbusUnitStatus {
        name: t.0,
        description: t.1,
        active_state: t.3,
        address: t.6,
    }
}

impl<'a> super::ServiceManager for &'a DbusServiceManager<'a> {
    type UnitManager = DbusUnitManager<'a>;
    type UnitStatus = DbusUnitStatus;
    type JobSet = DbusJobSet<'a>;

    fn system_status(&self) -> Result<SystemStatus, Error> {
        let state = &self.proxy.system_state()?;
        SystemStatus::from_str(state)
    }

    /// Performs a systemd daemon reload, blocking until complete.
    fn daemon_reload(&self) -> Result<(), Error> {
        let reloading = self.proxy.receive_reloading()?;

        self.proxy.reload()?;

        for result in reloading {
            match result.args() {
                Ok(args) if args.active => break,
                Ok(_) => {}
                Err(err) => {
                    eprintln!("Error listening for reload signal: {}. Assuming done.", err);
                    break;
                }
            }
        }

        Ok(())
    }

    fn reset_failed(&self) -> Result<(), Error> {
        self.proxy.reset_failed()?;
        Ok(())
    }

    /// Builds a unit manager for the unit with the given status.
    fn unit_manager(&self, status: &DbusUnitStatus) -> Result<DbusUnitManager<'a>, Error> {
        let proxy = dbus_unit::UnitProxy::builder(self.connection)
            .path(status.address.clone())?
            .build()?;

        Ok(DbusUnitManager { proxy })
    }

    fn new_job_set(&self) -> Result<DbusJobSet<'a>, Error> {
        DbusJobSet::new(self)
    }

    fn list_units_by_states(&self, states: &[&str]) -> Result<Vec<DbusUnitStatus>, Error> {
        let result = self
            .proxy
            .list_units_by_patterns(states, &[])?
            .drain(..)
            .map(to_unit_status)
            .collect();

        Ok(result)
    }
}

impl UnitManager for DbusUnitManager<'_> {
    fn refuse_manual_start(&self) -> Result<bool, Error> {
        Ok(self.proxy.refuse_manual_start()?)
    }

    fn refuse_manual_stop(&self) -> Result<bool, Error> {
        Ok(self.proxy.refuse_manual_stop()?)
    }
}