1pub mod config;
18#[cfg(feature = "backends")]
19pub mod engine;
20pub mod probe;
21pub mod rules;
22pub mod sinks;
23
24use std::collections::HashMap;
25use std::sync::{Arc, Mutex};
26use std::time::{Duration, Instant};
27
28use serde::{Deserialize, Serialize};
29use serde_json::Value;
30use weirdnet_rules::{RuleSpec, ThenAction, compare, syntax};
31
32pub use config::AlertsConfig;
33#[cfg(feature = "push")]
34pub use sinks::PushSink;
35pub use sinks::{LogSink, MemorySink, Sink, SmtpSink, WebhookSink};
36
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39pub struct Observation {
40 pub kind: String,
41 #[serde(default)]
42 pub fields: Value,
43}
44
45impl Observation {
46 pub fn new(kind: impl Into<String>, fields: Value) -> Self {
47 Self { kind: kind.into(), fields }
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(tag = "do", rename_all = "snake_case")]
55#[non_exhaustive]
56pub enum Action {
57 Fail {
59 key: String,
60 title: String,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
63 repeat_secs: Option<u64>,
64 },
65 Ok { key: String, title: String },
67 Event {
69 key: String,
70 title: String,
71 #[serde(default, skip_serializing_if = "Option::is_none")]
72 repeat_secs: Option<u64>,
73 },
74}
75
76impl ThenAction for Action {
77 fn verb(&self) -> &'static str {
78 match self {
79 Action::Fail { .. } => "fail",
80 Action::Ok { .. } => "ok",
81 Action::Event { .. } => "event",
82 }
83 }
84}
85
86pub type AlertRule = RuleSpec<Action>;
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "snake_case")]
90#[non_exhaustive]
91pub enum AlertStatus {
92 Failing,
93 Recovered,
94 Event,
95}
96
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99pub struct Alert {
100 pub key: String,
101 pub status: AlertStatus,
102 pub host: String,
103 pub title: String,
104 pub observation: Observation,
106 pub at: String,
108}
109
110impl Alert {
111 pub fn subject(&self, product: &str) -> String {
113 let tag = match self.status {
114 AlertStatus::Failing => "ALERT",
115 AlertStatus::Recovered => "OK",
116 AlertStatus::Event => "NOTE",
117 };
118 format!("[{product} {}] {tag}: {}", self.host, self.title)
119 }
120
121 pub fn body(&self) -> String {
122 let fields = serde_json::to_string_pretty(&self.observation.fields).unwrap_or_default();
123 format!("{}\n\nHost: {}\nWhen: {}\nKey: {}\nObserved: {}\n{}\n", self.title, self.host, self.at, self.key, self.observation.kind, fields)
124 }
125}
126
127#[derive(Debug, Default)]
128struct KeyState {
129 failing: bool,
130 last_sent: Option<Instant>,
131}
132
133pub struct Alerter {
135 host: String,
136 product: String,
137 rules: Vec<AlertRule>,
138 sinks: Vec<Arc<dyn Sink>>,
139 repeat: Duration,
140 state: Mutex<HashMap<String, KeyState>>,
141}
142
143impl Alerter {
144 pub fn new(host: impl Into<String>, rules: Vec<AlertRule>, sinks: Vec<Arc<dyn Sink>>) -> Self {
145 Self { host: host.into(), product: "weirdnet".into(), rules, sinks, repeat: Duration::from_secs(3600), state: Mutex::new(HashMap::new()) }
146 }
147
148 pub fn with_repeat(mut self, repeat: Duration) -> Self {
150 self.repeat = repeat;
151 self
152 }
153
154 pub fn with_product(mut self, product: impl Into<String>) -> Self {
156 self.product = product.into();
157 self
158 }
159
160 pub fn product(&self) -> &str {
161 &self.product
162 }
163
164 pub fn failing(&self) -> Vec<String> {
166 let mut v: Vec<String> =
167 self.state.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|(_, s)| s.failing).map(|(k, _)| k.clone()).collect();
168 v.sort();
169 v
170 }
171
172 pub fn evaluate(&self, obs: &Observation, now: Instant) -> Vec<Alert> {
174 let mut fields = obs.fields.clone();
175 if let Value::Object(m) = &mut fields {
176 m.entry("host").or_insert_with(|| Value::String(self.host.clone()));
177 } else {
178 fields = serde_json::json!({"host": self.host, "value": fields});
179 }
180 let local = chrono::Local::now();
181 let mut out = Vec::new();
182 let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
183 for rule in &self.rules {
184 if !rule.on.iter().any(|p| syntax::matches_kind(p, &obs.kind)) {
185 continue;
186 }
187 if !rule.when.iter().all(|c| compare::compare(compare::path(&fields, &c.field), c.op, &c.value)) {
188 continue;
189 }
190 for action in &rule.then {
191 let fill = |t: &str| weirdnet_rules::template::expand(t, &local, &obs.kind, |k| compare::path(&fields, k).cloned());
192 let (key, title, status, repeat) = match action {
193 Action::Fail { key, title, repeat_secs } => {
194 (fill(key), fill(title), AlertStatus::Failing, repeat_secs.map_or(self.repeat, Duration::from_secs))
195 }
196 Action::Event { key, title, repeat_secs } => {
197 (fill(key), fill(title), AlertStatus::Event, repeat_secs.map_or(self.repeat, Duration::from_secs))
198 }
199 Action::Ok { key, title } => (fill(key), fill(title), AlertStatus::Recovered, Duration::ZERO),
200 };
201 let s = state.entry(key.clone()).or_default();
202 let send = match status {
203 AlertStatus::Failing => {
204 let due = !s.failing || s.last_sent.is_none_or(|t| now.duration_since(t) >= repeat);
205 s.failing = true;
206 due
207 }
208 AlertStatus::Event => s.last_sent.is_none_or(|t| now.duration_since(t) >= repeat),
209 AlertStatus::Recovered => std::mem::take(&mut s.failing),
210 };
211 if send {
212 s.last_sent = Some(now);
213 out.push(Alert {
214 key,
215 status,
216 host: self.host.clone(),
217 title,
218 observation: Observation { kind: obs.kind.clone(), fields: fields.clone() },
219 at: local.format("%Y-%m-%d %H:%M %Z").to_string(),
220 });
221 }
222 }
223 }
224 out
225 }
226
227 pub async fn observe(&self, obs: &Observation) -> Vec<Alert> {
230 let alerts = self.evaluate(obs, Instant::now());
231 for a in &alerts {
232 for sink in &self.sinks {
233 if let Err(e) = sink.send(&self.product, a).await {
234 tracing::warn!(sink = sink.name(), key = %a.key, "alert not sent: {e}");
235 }
236 }
237 }
238 alerts
239 }
240}
241
242#[cfg(test)]
243mod tests {
244 use serde_json::json;
245
246 use super::*;
247
248 fn alerter() -> Alerter {
249 Alerter::new("node-a", rules::default_rules(&rules::Thresholds::default()), Vec::new())
250 }
251
252 #[test]
253 fn network_degraded_alerts_once_then_recovers() {
254 let a = alerter();
255 let t0 = Instant::now();
256 let degraded = Observation::new("net.route", json!({"state": "degraded", "dev": "wlp2s0"}));
257 let ok = Observation::new("net.route", json!({"state": "ok", "dev": "eth0"}));
258 let first = a.evaluate(°raded, t0);
259 assert_eq!(first.len(), 1);
260 assert_eq!(first[0].status, AlertStatus::Failing);
261 assert_eq!(first[0].title, "DEGRADED but up: node-a default route uses Wi-Fi (wlp2s0)");
262 assert_eq!(first[0].subject("node"), "[node node-a] ALERT: DEGRADED but up: node-a default route uses Wi-Fi (wlp2s0)");
263 assert!(a.evaluate(°raded, t0 + Duration::from_secs(60)).is_empty(), "deduped within the hour");
264 assert_eq!(a.evaluate(°raded, t0 + Duration::from_secs(3601)).len(), 1, "repeats hourly");
265 assert_eq!(a.failing(), vec!["net.route".to_string()]);
266 let back = a.evaluate(&ok, t0 + Duration::from_secs(3700));
267 assert_eq!(back.len(), 1);
268 assert_eq!(back[0].status, AlertStatus::Recovered);
269 assert_eq!(back[0].title, "node-a default route back on eth0");
270 assert!(a.evaluate(&ok, t0 + Duration::from_secs(3800)).is_empty(), "one recovery notice");
271 assert!(a.failing().is_empty());
272 }
273
274 #[test]
275 fn no_route_and_engine_rules() {
276 let a = alerter();
277 let t = Instant::now();
278 let r = a.evaluate(&Observation::new("net.route", json!({"state": "noroute", "dev": "-"})), t);
279 assert_eq!(r[0].title, "node-a has no default route");
280 let r = a.evaluate(&Observation::new("engine.crash_loop", json!({"model": "qwen", "crashes": 5})), t);
281 assert_eq!(r.len(), 1);
282 assert_eq!(r[0].key, "engine.qwen");
283 assert!(r[0].title.contains("crash loop"), "{}", r[0].title);
284 let r = a.evaluate(&Observation::new("engine.ready", json!({"model": "qwen", "load_secs": 3.0})), t);
285 assert_eq!(r.len(), 1);
286 assert_eq!(r[0].status, AlertStatus::Recovered);
287 assert!(a.evaluate(&Observation::new("engine.ready", json!({"model": "other"})), t).is_empty(), "nothing to recover");
288 }
289
290 #[test]
291 fn disk_and_gpu_thresholds() {
292 let a = alerter();
293 let t = Instant::now();
294 assert!(a.evaluate(&Observation::new("disk", json!({"path": "/", "free_pct": 40.0})), t).is_empty());
295 assert_eq!(a.evaluate(&Observation::new("disk", json!({"path": "/", "free_pct": 4.5})), t).len(), 1);
296 assert_eq!(a.evaluate(&Observation::new("disk", json!({"path": "/", "free_pct": 30.0})), t)[0].status, AlertStatus::Recovered);
297 assert_eq!(a.evaluate(&Observation::new("gpu", json!({"index": 0, "temp_c": 91})), t).len(), 1);
298 assert!(a.evaluate(&Observation::new("gpu", json!({"index": 0, "temp_c": 83})), t).is_empty(), "hysteresis: not yet cool");
299 assert_eq!(a.evaluate(&Observation::new("gpu", json!({"index": 0, "temp_c": 70})), t)[0].status, AlertStatus::Recovered);
300 }
301
302 #[test]
303 fn rules_round_trip_as_toml() {
304 let rules = rules::default_rules(&rules::Thresholds::default());
305 #[derive(Serialize, Deserialize)]
306 struct Pack {
307 rule: Vec<AlertRule>,
308 }
309 let text = toml::to_string(&Pack { rule: rules.clone() }).unwrap();
310 let back: Pack = toml::from_str(&text).unwrap();
311 assert_eq!(back.rule, rules);
312 }
313
314 #[tokio::test]
315 async fn observe_sends_to_sinks() {
316 let mem = Arc::new(MemorySink::default());
317 let a = Alerter::new("node-a", rules::default_rules(&rules::Thresholds::default()), vec![mem.clone()]);
318 a.observe(&Observation::new("engine.load_failed", json!({"model": "big", "why": "out of memory"}))).await;
319 let sent = mem.sent();
320 assert_eq!(sent.len(), 1);
321 assert!(sent[0].title.contains("big") && sent[0].title.contains("out of memory"));
322 }
323}