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
|
// This module defines unit settings parsing logig
//
// NOTE: ON UNIT PARSING LOGIC
// when parsing a unit in /etc/vigil/units/ we shoul ignore
// ANY broken/bad constructed toml unit configuration file
// without "crashing" logic.
//
// NOTE: ON GENERAL SERVICE LOGGING
// when vigil starts service, it should send out logs to vigil?
// or logs in such init systems are just taking the stdout+stderr
// of service and showing its output? idk 4 now, look into how its supposed to be
use crate::{RUNLEVEL_STATE, log_warning};
use serde::Deserialize;
use std::{
fs::{read_dir, read_to_string},
process::{Child, ExitStatus},
time::Duration,
};
/*
[info]
name = "name"
description = "description"
version = "version"
[config]
exec = "path to exec"
runlevel =
restart=always|never
*/
#[derive(Deserialize, PartialEq, Clone)]
enum Restart {
#[serde(alias = "always")]
Always,
#[serde(alias = "never")]
Never,
}
#[derive(Deserialize, PartialEq, Eq)]
pub enum Runlevel {
/// The system is shutting down, runlevel int: 0
Shutdown,
/// One-user system debug-mode, runlevel int: 1
OneUser,
/// Multi-user CLI (TTY) with no network, runlevel int: 2
MultiNoNetwork,
/// Multi-user CLI with network, runlevel int: 3
MultiNetwork,
/// Multi-user mode with GUI, runlevel int: 5
MultiGUINetwork,
/// Runlevel is not critical for running the service, runlevel int: 4
Undefined,
/// System going too reboot, runlevel int: 6
Reboot,
}
#[allow(dead_code)]
#[derive(Deserialize)]
pub struct ServiceInfo {
/// Service name
name: String,
/// Service description
description: String,
/// Service version
version: String,
}
#[allow(dead_code)]
#[derive(Deserialize)]
pub struct ServiceConfig {
/// Execution command, like ExecStart in sysd
exec: String,
/// Runlevel, like after=*.target
runlevel: Runlevel,
/// Restart service: Always|Never
restart: Restart,
}
/// Main Unit-file struct
#[allow(dead_code)]
#[derive(Deserialize)]
pub struct Unit {
info: ServiceInfo,
config: ServiceConfig,
}
#[allow(dead_code)]
impl Restart {
pub fn as_str(&self) -> &'static str {
match self {
Restart::Always => "always",
Restart::Never => "never",
}
}
}
/// Function:
/// 1. starting services declared in `/etc/vigil/units/`
/// 2. checks services for dropping and if ts true to restarting it
/// max restart count: 3
///
/// Based on the global runlevel variable, should be runned as second thread
// TODO: More logs && better errors processing && fix clippy warnings
pub fn services_mainloop() -> Result<(), Box<dyn std::error::Error + Send>> {
let unit_list = parse_all_units()?;
let mut pids: Vec<(Child, String, Restart, u8)> = vec![];
loop {
match *RUNLEVEL_STATE.lock().unwrap() {
Runlevel::Undefined => {
for unit in &unit_list {
if unit.config.runlevel == Runlevel::Undefined {
let child = std::process::Command::new(unit.config.exec.clone())
.spawn()
.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send>)?;
pids.push((
child,
unit.config.exec.clone(),
unit.config.restart.clone(),
0,
));
}
}
}
Runlevel::Reboot => {
for unit in &unit_list {
if unit.config.runlevel == Runlevel::Reboot {
let child = std::process::Command::new(unit.config.exec.clone())
.spawn()
.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send>)?;
pids.push((
child,
unit.config.exec.clone(),
unit.config.restart.clone(),
0,
));
}
}
}
Runlevel::Shutdown => {
for unit in &unit_list {
if unit.config.runlevel == Runlevel::Shutdown {
let child = std::process::Command::new(unit.config.exec.clone())
.spawn()
.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send>)?;
pids.push((
child,
unit.config.exec.clone(),
unit.config.restart.clone(),
0,
));
}
}
}
Runlevel::OneUser => {
for unit in &unit_list {
if unit.config.runlevel == Runlevel::OneUser {
let child = std::process::Command::new(unit.config.exec.clone())
.spawn()
.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send>)?;
pids.push((
child,
unit.config.exec.clone(),
unit.config.restart.clone(),
0,
));
}
}
}
Runlevel::MultiNoNetwork => {
for unit in &unit_list {
if unit.config.runlevel == Runlevel::MultiNoNetwork {
let child = std::process::Command::new(unit.config.exec.clone())
.spawn()
.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send>)?;
pids.push((
child,
unit.config.exec.clone(),
unit.config.restart.clone(),
0,
));
}
}
}
Runlevel::MultiNetwork => {
for unit in &unit_list {
if unit.config.runlevel == Runlevel::MultiNetwork {
let child = std::process::Command::new(unit.config.exec.clone())
.spawn()
.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send>)?;
pids.push((
child,
unit.config.exec.clone(),
unit.config.restart.clone(),
0,
));
}
}
}
Runlevel::MultiGUINetwork => {
for unit in &unit_list {
if unit.config.runlevel == Runlevel::MultiGUINetwork {
let child = std::process::Command::new(unit.config.exec.clone())
.spawn()
.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send>)?;
pids.push((
child,
unit.config.exec.clone(),
unit.config.restart.clone(),
0,
));
}
}
}
}
for i in 0..pids.len() {
match pids[i].0.try_wait() {
Ok(Some(status)) => {
if pids[i].2 == Restart::Always && pids[i].3 < 3 && status.code() != Some(0) {
let new_child = std::process::Command::new(pids[i].1.clone())
.spawn()
.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send>)?;
log_warning(&format!(
"One of units dropped with Error {};\n Restarting it. Attempt: {}",
status,
pids[i].3 + 1
));
pids.push((
new_child,
pids[i].1.clone(),
pids[i].2.clone(),
pids[i].3 + 1,
));
pids.remove(i);
} else {
log_warning(&format!(
"Unit {} has reached maximum restart attempts or restart policy is not Always, not restarting.",
pids[i].1
));
continue;
}
}
Ok(None) => continue,
Err(e) => log_warning(&format!("Error occurred while checking services: {}", e)),
}
}
std::thread::sleep(Duration::from_secs(15));
}
}
fn parse_all_units() -> Result<Vec<Unit>, Box<dyn std::error::Error + Send>> {
let mut units: Vec<Unit> = Vec::new();
for unit in read_dir("/etc/vigil/units")
.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send>)?
{
let unit_path = unit
.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send>)?
.path();
let unit_str: String = match read_to_string(unit_path) {
Ok(content) => content,
Err(e) => {
log_warning(&format!("Error while reading unit: {}", e));
continue;
}
};
let deserialized: Result<Unit, _> = toml::from_str(&unit_str);
match deserialized {
Ok(unit) => {
units.push(unit);
}
Err(e) => {
log_warning(&format!("Error while parsing unit: {}", e));
continue;
}
};
}
Ok(units)
}
|