use std::path::PathBuf;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use crate::rules::Thresholds;
use crate::sinks::{LogSink, Sink, SmtpSink, WebhookSink};
use crate::{AlertRule, Alerter};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AlertsConfig {
#[serde(default = "yes")]
pub enabled: bool,
#[serde(default)]
pub dry_run: bool,
#[serde(default = "hour")]
pub repeat_secs: u64,
#[serde(default = "every")]
pub probe_secs: u64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub disks: Vec<PathBuf>,
#[serde(default, flatten)]
pub thresholds: Thresholds,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub smtp: Option<SmtpConfig>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub webhook: Vec<WebhookConfig>,
#[serde(default)]
pub push: PushConfig,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rule: Vec<AlertRule>,
}
fn yes() -> bool {
true
}
fn hour() -> u64 {
3600
}
fn every() -> u64 {
30
}
impl Default for AlertsConfig {
fn default() -> Self {
Self {
enabled: true,
dry_run: false,
repeat_secs: hour(),
probe_secs: every(),
disks: Vec::new(),
thresholds: Thresholds::default(),
smtp: None,
webhook: Vec::new(),
push: PushConfig::default(),
rule: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SmtpConfig {
pub server: String,
#[serde(default = "smtp_port")]
pub port: u16,
#[serde(default = "starttls")]
pub security: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub user: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub password: Option<String>,
pub from: String,
pub to: Vec<String>,
}
fn smtp_port() -> u16 {
587
}
fn starttls() -> String {
"starttls".into()
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WebhookConfig {
pub url: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct PushConfig {
#[serde(default)]
pub enabled: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub cards: Vec<PushCard>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PushCard {
pub service: String,
pub handle: String,
pub key: String,
}
impl PushConfig {
#[cfg(feature = "push")]
fn sink(&self, dry_run: bool) -> Result<Arc<dyn Sink>, String> {
let cards = self
.cards
.iter()
.map(|c| {
let handle = weirdnet_push::WakeHandle::parse(&c.handle).map_err(|e| format!("push card: {e}"))?;
Ok(weirdnet_push::WakeCard { service: c.service.clone(), handle, key: c.key.clone() })
})
.collect::<Result<Vec<_>, String>>()?;
Ok(Arc::new(crate::sinks::PushSink::new(cards, dry_run)?))
}
#[cfg(not(feature = "push"))]
fn sink(&self, _dry_run: bool) -> Result<Arc<dyn Sink>, String> {
Err("push alerts need weirdnet-alerts built with the `push` feature".into())
}
}
pub fn resolve_secret(source: &str) -> Result<String, String> {
if let Some(name) = source.strip_prefix("env:") {
return std::env::var(name).map_err(|_| format!("environment variable {name} is not set"));
}
if let Some(path) = source.strip_prefix("file:") {
return std::fs::read_to_string(path).map(|s| s.trim_end_matches(['\n', '\r']).to_string()).map_err(|e| format!("reading {path}: {e}"));
}
if source.starts_with("keyring:") {
return Err("keyring: secrets are not supported yet; use env:NAME or file:/path".into());
}
Err("a secret must be a reference (env:NAME or file:/path), not the secret itself".into())
}
impl AlertsConfig {
pub fn sinks(&self) -> Result<Vec<Arc<dyn Sink>>, String> {
let mut out: Vec<Arc<dyn Sink>> = vec![Arc::new(LogSink)];
if let Some(s) = &self.smtp {
out.push(Arc::new(SmtpSink::new(s, self.dry_run)?));
}
for w in &self.webhook {
out.push(Arc::new(WebhookSink::new(w, self.dry_run)?));
}
if self.push.enabled {
out.push(self.push.sink(self.dry_run)?);
}
Ok(out)
}
pub fn alerter(&self, host: &str) -> Result<Alerter, String> {
let mut rules = crate::rules::default_rules(&self.thresholds);
rules.extend(self.rule.iter().cloned());
Ok(Alerter::new(host, rules, self.sinks()?).with_repeat(std::time::Duration::from_secs(self.repeat_secs.max(1))))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_and_refuses_inline_secrets() {
let cfg: AlertsConfig = toml::from_str(
r#"
dry_run = true
disk_min_free_pct = 5
[smtp]
server = "smtp.example.com"
user = "alerts@example.com"
password = "env:WEIRDNET_TEST_SMTP_PASSWORD_UNSET"
from = "alerts@example.com"
to = ["owner@example.com"]
[[webhook]]
url = "https://hooks.example.com/alerts"
[[rule]]
on = ["engine.unloaded"]
then = [{ do = "event", key = "u.{model}", title = "{model} unloaded" }]
"#,
)
.unwrap();
assert_eq!(cfg.thresholds.disk_min_free_pct, 5.0);
assert_eq!(cfg.smtp.as_ref().unwrap().port, 587);
assert_eq!(cfg.rule.len(), 1);
assert!(resolve_secret("hunter2").is_err());
assert!(resolve_secret("keyring:alerts/smtp").is_err());
assert!(resolve_secret("env:WEIRDNET_TEST_SMTP_PASSWORD_UNSET").is_err());
let dir = tempfile::tempdir().unwrap();
let f = dir.path().join("pw");
std::fs::write(&f, "s3cret\n").unwrap();
assert_eq!(resolve_secret(&format!("file:{}", f.display())).unwrap(), "s3cret");
assert_eq!(cfg.sinks().unwrap().len(), 3);
}
#[test]
fn push_needs_cards_and_the_feature() {
let mut cfg = AlertsConfig { dry_run: true, ..Default::default() };
cfg.push.enabled = true;
assert!(cfg.sinks().is_err(), "no cards (or no feature)");
cfg.push.cards.push(PushCard { service: "https://push.example.com".into(), handle: "not a handle".into(), key: "11".repeat(32) });
assert!(cfg.sinks().is_err());
}
}