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
|
#!/usr/bin/env python3
import argparse
import configparser
import subprocess
import sys
from dataclasses import dataclass
from datetime import datetime
from enum import Enum, auto
from pathlib import Path
class State(Enum):
UP = 1
DOWN = 2
UNSTABLE = 3
UNKNOWN = auto()
@staticmethod
def from_rc(rc: int) -> "State":
if rc == 0:
return State.UP
else:
return State.DOWN
def to_colour(self) -> str:
return {
State.UP: "green",
State.DOWN: "red",
State.UNSTABLE: "orange",
State.UNKNOWN: "gray"
}[self]
class StateChange(Enum):
NONE = 0
FAIL = 1
RECOVER = 2
@dataclass
class Service:
name: str
cmd: str
url: str
on_fail: str | None = None
on_recover: str | None = None
def get_services_from_config(config_path: Path) -> list[Service]:
config = configparser.ConfigParser()
config.read(config_path)
services = []
for section in config.sections():
if not section.startswith("service:"):
continue
name = section.split("service:")[1]
cmd = config[section].get("cmd")
url = config[section].get("url") or "#"
on_fail = config[section].get("on_fail")
on_recover = config[section].get("on_recover")
if cmd is None:
raise ValueError(f"Section service:{name} missing 'cmd'.")
services.append(Service(name=name, url=url, cmd=cmd, on_fail=on_fail, on_recover=on_recover))
return services
def do_check(service: Service) -> int:
print(f"Checking {service.name}...", file=sys.stderr, end="")
rc = subprocess.run(
service.cmd,
shell=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
).returncode
print(f" {State.from_rc(rc).name}", file=sys.stderr)
return rc
def run_on_fail(service: Service):
if service.on_fail:
subprocess.run(service.on_fail, shell=True)
def run_on_recover(service: Service):
if service.on_recover:
subprocess.run(service.on_recover, shell=True)
def write_status(rc: int, status_file: Path):
now = datetime.now().isoformat(timespec="seconds")
with open(status_file, "a") as f:
f.write(f"{now} {rc}\n")
def check_for_state_change(status_file: Path) -> StateChange:
with open(status_file, "r") as f:
lines = f.readlines()[-2:]
try:
prev_rc = int(lines[0].split()[1])
cur_rc = int(lines[1].split()[1])
except IndexError:
return StateChange.NONE
if prev_rc == 0 and cur_rc != 0:
return StateChange.FAIL
elif prev_rc != 0 and cur_rc == 0:
return StateChange.RECOVER
else:
return StateChange.NONE
def check_service(service: Service, workdir: Path):
status_dir = workdir / service.name
if not status_dir.exists():
status_dir.mkdir(parents=True)
today = datetime.today().strftime("%Y-%m-%d")
status_file = status_dir / today
rc = do_check(service)
write_status(rc, status_file)
state_change = check_for_state_change(status_file)
if state_change == StateChange.FAIL:
run_on_fail(service)
elif state_change == StateChange.RECOVER:
run_on_recover(service)
def write_report_header(f):
f.write("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Service Status</title>
<style>
body { font-family: system-ui; max-width: 600px; margin: 2rem auto; padding: 0 1rem; }
h1 { margin-bottom: 1rem; }
table { border-collapse: collapse; width: 100%; }
th, td { padding: .5rem .75rem; border-bottom: 1px solid #ddd; }
th { text-align: left; background: #f6f6f6; position: sticky; top: 0; }
td:last-child { font-size: 0; white-space: nowrap; }
td:last-child span { display: inline-block; font-size: 1rem; width: 6px; height: 1.4em; margin-right: 2px; border-radius: 2px; line-height: 1; background-color: currentColor; }
.badge { display: inline-block; font-size: .75rem; font-weight: bold; padding: .15em .5em; border-radius: 999px; color: #fff; }
.badge-green { background: green; }
.badge-red { background: red; }
.badge-orange { background: orange; color: #000; }
.badge-gray { background: gray; }
footer { margin-top: 1rem; font-size: .8rem; color: #999; }
</style>
</head>
<body>
<h1>Service Status</h1>
<table>
<tr>
<th>Service</th>
<th>Status</th>
<th>Last 30 days</th>
</tr>
""")
def write_service_row(f, service: Service, days: list[tuple[str, State, State]]):
latest_state = days[-1][2]
badge = f'<span class="badge badge-{latest_state.to_colour()}">{latest_state.name}</span>'
f.write(f' <tr>\n <td><a href="{service.url}">{service.name}</a></td><td>{badge}</td>\n <td>\n')
for day, overall_state, _ in days:
f.write(f' <span title="{day}: {overall_state.name}" style="color: {overall_state.to_colour()};"></span>\n')
f.write(" </td>\n </tr>\n")
def write_report_footer(f):
now = datetime.now().strftime("%Y-%m-%d %H:%M")
f.write(f"""
</table>
<footer>Updated: {now}</footer>
</body>
</html>
""")
def generate_report(services: list[Service], workdir: Path, output: Path):
if not output.exists():
output.mkdir(parents=True)
report_file = output / "status.html"
with open(report_file, "w") as report_f:
write_report_header(report_f)
for service in services:
status_dir = workdir / service.name
# Last 30 days
status_files = sorted(status_dir.glob("*"))[-30:]
days: list[tuple[str, State, State]] = [] # (date, overall_state, latest_state)
for status_file in status_files:
with open(status_file, "r") as status_f:
overall_state = State.UNKNOWN
for line in status_f:
when, raw_rc = line.strip().split()
rc = int(raw_rc)
latest_state = State.from_rc(rc)
if overall_state == State.UNKNOWN:
overall_state = latest_state
else:
if latest_state != overall_state:
overall_state = State.UNSTABLE
days.append((status_file.name, overall_state, latest_state))
write_service_row(report_f, service, days)
write_report_footer(report_f)
def run(args: argparse.Namespace) -> int:
services = get_services_from_config(args.config)
for service in services:
check_service(service, args.workdir)
generate_report(services, args.workdir, args.output)
return 0
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Monitor the uptime of your services.")
parser.add_argument(
"-c", "--config", type=Path, required=True, help="Path to the configuration file."
)
parser.add_argument(
# TODO: Should probably be database
"-w", "--workdir", type=Path, default=Path.cwd(), help="Working directory."
)
parser.add_argument(
"-o", "--output", type=Path, default=Path.cwd() / "html", help="Output directory."
)
return parser.parse_args()
def main() -> int:
args = parse_args()
return run(args)
if __name__ == "__main__":
sys.exit(main())
|