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
use std::fs;
use std::io::{Error, ErrorKind};
use std::path::Path;
use crate::*;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct GenCheck {
#[serde(skip_serializing_if = "Option::is_none")]
pub domains: Option<Domains>,
#[serde(skip_serializing_if = "Option::is_none")]
pub pages: Option<Pages>,
#[serde(skip_serializing_if = "Option::is_none")]
pub alert_webhook: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub alert_channel: Option<String>,
}
impl Checks<GenCheck> for GenCheck {
fn load(name: &str) -> Result<GenCheck, Error> {
read_text_file(&name).and_then(|file_contents| {
serde_json::from_str(&*file_contents)
.map_err(|err| Error::new(ErrorKind::InvalidInput, err.to_string()))
})
}
fn execute(&self, execution_name: &str) -> History {
let history = History::new_from(
[
Self::check_pages(self.pages.clone()).stories(),
Self::check_domains(self.domains.clone()).stories(),
]
.concat(),
);
match (&self.alert_webhook, &self.alert_channel) {
(Some(webhook), Some(channel)) => {
let failures = history
.stories()
.iter()
.filter_map(|story| {
if let Some(error) = &story.error {
Some(format!("{}\n", error))
} else {
None
}
})
.collect::<String>();
let failures_state_file =
&format!("{}-{}", DEFAULT_FAILURES_STATE_FILE, execution_name);
debug!("Failures state file: {}", failures_state_file);
debug!("FAILURES: {:?}", failures);
if failures.is_empty() {
if Path::new(failures_state_file).exists() {
debug!(
"No more failures! Removing failures log file and notifying that failures are gone"
);
fs::remove_file(failures_state_file).unwrap_or_default();
notify_success(
webhook,
channel,
&format!("All services are UP again ({}).\n", &execution_name),
);
} else {
debug!("All services are OK! No notification sent");
}
} else {
let file_entries = read_text_file(failures_state_file).unwrap_or_default();
let send_notification = failures.split('\n').find(|fail| {
if !file_entries.contains(fail) {
write_append(failures_state_file, &fail.to_string());
true
} else {
false
}
});
let failures_to_notify = failures
.split('\n')
.filter(|fail| !file_entries.contains(fail))
.map(|fail| format!("{}\n", fail))
.collect::<String>();
if send_notification.is_some() {
notify_failure(webhook, channel, &failures_to_notify);
}
}
}
(..) => {
info!("Notifications not configured hence skipped…");
}
};
history
}
}