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
|
use crate::{log::update_service, Config, Status, GLOBAL_ERROR, STATUS};
use anyhow::{anyhow, bail, Result};
use chrono::Utc;
use futures::{stream::FuturesUnordered, StreamExt};
use log::info;
use serde::Deserialize;
use std::{sync::Arc, time::Duration};
use tokio::{
process::Command,
time::{sleep, timeout},
};
use crate::dbus::*;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Check {
Systemd(String),
SystemdGlobal,
SystemdUser {
user: String,
name: String,
},
SystemdUserGlobal(String),
Pacman(String),
Http {
title: Option<String>,
url: String,
},
Shell {
title: String,
command: String,
#[serde(default)]
output: bool,
},
}
pub async fn check_loop(config: Arc<Config>, i: usize) {
loop {
check_service(&config, i).await;
sleep(Duration::from_secs(config.interval)).await;
}
}
async fn check_service(config: &Arc<Config>, i: usize) {
let service = &config.services[i];
let mut futs = FuturesUnordered::from_iter(service.checks.iter().enumerate().map(
|(j, check)| async move {
let r = match timeout(Duration::from_secs(30), check.check()).await {
Ok(Ok(succ)) => Ok(succ),
Ok(Err(e)) => Err(e),
Err(_) => Err(anyhow!("timed out")),
};
info!("check {i}:{j} => {r:?}");
let status = Status {
time: Utc::now(),
status: r.map_err(|e| format!("{e:?}")),
};
{
let mut g = STATUS.write().await;
g.insert((i, j), status.clone());
}
let config = config.clone();
tokio::task::spawn(async move {
if let Err(e) = update_service(config.clone(), i, j, status).await {
*GLOBAL_ERROR.write().await = Some(e);
}
})
},
));
while let Some(_) = futs.next().await {}
}
impl Check {
pub async fn check(&self) -> Result<String> {
match self {
Check::Pacman(package) => {
let output = Command::new("pacman")
.arg("-Q")
.arg(package)
.output()
.await?;
output.status.exit_ok()?;
Ok(String::from_utf8(output.stdout)?)
}
Check::Systemd(name) => {
check_systemd_unit(None, name).await
}
Check::SystemdGlobal => {
check_systemd_all(None).await
}
Check::SystemdUser { user, name } => {
check_systemd_unit(Some(user), name).await
}
Check::SystemdUserGlobal(user) => {
check_systemd_all(Some(user)).await
}
Check::Shell {
command, output, ..
} => {
let args = shlex::split(&command).ok_or(anyhow!("command syntax invalid"))?;
let status = Command::new(args.get(0).ok_or(anyhow!("argv0 missing"))?)
.args(&args[1..])
.output()
.await;
if *output {
match status {
Ok(status) if status.status.success() => {
Ok(String::from_utf8_lossy(&status.stdout).to_string())
}
Ok(status) => bail!("{}", String::from_utf8_lossy(&status.stdout)),
Err(e) => bail!("command failed to execute: {e}"),
}
} else {
match status {
Ok(status) if status.status.success() => Ok(Default::default()),
Ok(status) => {
bail!("failed with code {}", status.status.code().unwrap_or(1))
}
Err(e) => bail!("command failed to execute: {e}"),
}
}
}
Check::Http { url, .. } => {
let r = reqwest::get(url).await?;
let s = format!(
"{} {}",
r.status().as_str(),
r.status().canonical_reason().unwrap_or_default()
);
if r.status().is_success() {
Ok(s)
} else {
bail!("{s}")
}
}
}
}
}
impl Check {
pub fn display(&self) -> String {
match self {
Check::Systemd(_) => "Service".to_string(),
Check::Http { title, .. } => title.clone().unwrap_or("HTTP".to_string()),
Check::Shell { title, .. } => title.to_owned(),
Check::Pacman(_) => "Installed".to_string(),
Check::SystemdGlobal => "System Services".to_string(),
Check::SystemdUser { user, .. } => format!("User service for {user}"),
Check::SystemdUserGlobal(username) => format!("User services for {username}"),
}
}
}
|