-
Notifications
You must be signed in to change notification settings - Fork 1
/
mownitoring.py
executable file
·348 lines (296 loc) · 11.7 KB
/
mownitoring.py
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#!/usr/bin/env python3
# Copyright (c) 2018 Daniel Jakots
#
# Licensed under the MIT license. See the LICENSE file.
import smtplib
import email.mime.text
from http import HTTPStatus
import concurrent.futures
import datetime
import os
import sqlite3
import subprocess
import sys
import syslog
import requests
import toml
def notify_pushover(machine, check, message, time_check):
"""Notify through Pushover."""
alert = f"{time_check}: {machine}!{check} {message}"
payload = {
"token": api_cfg["pushover_token"],
"user": api_cfg["pushover_user"],
"message": alert,
"priority": "1",
"expire": "3600",
"retry": "90",
"title": f"Alert from mownitoring: {machine}!{check}"
}
p = requests.post(api_cfg["pushover_api_url"], params=payload)
if p.status_code == HTTPStatus.OK:
syslog.syslog("Alert sent through pushover")
else:
syslog.syslog(syslog.LOG_ERR, "Sending through pushover didn't work")
def notify_syslog(machine, check, message, time_check):
"""Notify through syslog."""
alert = f"{time_check}: {machine}!{check} {message}"
syslog.syslog(syslog.LOG_WARNING, alert)
def notify_mail(machine, check, message, time_check):
"""Notify through email."""
body = ("Hi,\n"
f"On {time_check}, we detected a change on "
f"{machine} for the check {check}:\n\n{message}\n\n"
"Yours truly,\n-- \n"
"Mownitoring")
msg = email.mime.text.MIMEText(str(body))
msg['Subject'] = f"Alert from mownitoring: {machine}!{check}"
msg['From'] = api_cfg["mail_from"]
msg['To'] = api_cfg["mail_to"]
s = smtplib.SMTP(api_cfg["mail_server"])
s.send_message(msg)
s.quit()
syslog.syslog("Alert sent through email")
def craft_sms(machine, check, message, time_check):
"""Create a valuable alert with less text."""
# keep just the hour, i.e. strip year/month/day
time_check = time_check[-5:]
# remove the domain
machine = machine.split('.')[0]
alert = f'{time_check} {machine}!{check} {message}'
return alert[0:156]
def notify_twilio(machine, check, message, time_check):
"""Send a text with twilio."""
alert = craft_sms(machine, check, message, time_check)
payload = {
'From': api_cfg["twilio_sender"],
'To': "+" + api_cfg["twilio_dest"],
'Body': alert
}
# send the text with twilio's api
p = requests.post(
api_cfg["twilio_api_url"],
data=payload,
auth=(api_cfg["twilio_account_sid"], api_cfg["twilio_auth_token"]))
if p.status_code != HTTPStatus.CREATED:
syslog.syslog(syslog.LOG_ERR, 'Problem while sending twilio')
syslog.syslog(f'SMS sent with twilio to {api_cfg["twilio_dest"]}')
def check_nrpe(check, host, port):
"""Run a given check for a specified host."""
nrpe = subprocess.run(
[NAGIOS_CHECK_PATH + "/check_nrpe",
"-t", f'{CHECK_NRPE_TIMEOUT}',
"-H", host, "-c", "check_" + check, "-p", port],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
encoding="utf-8")
return nrpe.returncode, nrpe.stdout
def check_ping(host):
"""Run check_ping for a specified host."""
nrpe = subprocess.run(
[NAGIOS_CHECK_PATH + "/check_ping",
"-t", f'{CHECK_NRPE_TIMEOUT}', "-H", host,
"-w", f"{CHECK_PING_LATENCY_WARN},{CHECK_PING_LOSS_WARN}%",
"-c", f"{CHECK_PING_LATENCY_CRIT},{CHECK_PING_LOSS_CRIT}%",
"-p", "5"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
encoding="utf-8")
return nrpe.returncode, nrpe.stdout
def check_notifier(notifiers):
"""Check if the configured notifier really exists."""
notifiers_available = {
"syslog": notify_syslog,
"pushover": notify_pushover,
"mail": notify_mail,
"twilio": notify_twilio
}
notifiers_valid = []
for notifier in notifiers:
try:
notifiers_valid.append(notifiers_available[notifier])
except KeyError:
syslog.syslog(syslog.LOG_ERR,
f"Unknown notifier {notifier} configured")
return notifiers_valid
def notify(check, message, machine, notifiers, timestamp):
"""Send an alert to notification system(s)."""
notifiers_valid = check_notifier(notifiers)
if notifiers_valid:
for notifier in notifiers_valid:
time_check = timestamp.strftime('%Y/%m/%d %H:%M')
notifier(machine, check, message, time_check)
else:
syslog.syslog(syslog.LOG_ERR, "No valid notify system")
def run_check(host, port="5666", check="ping"):
"""Run the right check."""
timestamp = datetime.datetime.now()
if check == "ping":
status, message = check_ping(host)
else:
status, message = check_nrpe(check, host, port)
if status == 255:
message = "Connection refused"
return timestamp, status, message
def register_and_alert(check, host, port, machine, notifiers, conn,
timestamp, status, message):
"""Check if the state has changed and if so, notify and save the new state
in the DB.
"""
c = conn.cursor()
param = (machine, check)
try:
c.execute('SELECT status FROM mownitoring ' +
'WHERE machine=? AND check_name=?', param)
logged_status = c.fetchone()
except sqlite3.OperationalError:
logged_status = None
if logged_status is not None:
if logged_status[0] != status:
notify(check, message, machine, notifiers, timestamp)
if status != 0:
param = (status, machine, check)
c.execute('UPDATE mownitoring SET status = ? WHERE ' +
'machine=? AND check_name=?', param)
else:
param = (machine, check)
c.execute('DELETE FROM mownitoring ' +
'WHERE machine=? AND check_name=?', param)
else:
alert = ("Already known state but still a problem for " +
f"{machine}!{check}")
syslog.syslog(alert)
else:
if status != 0:
param = (machine, check, status, timestamp.strftime('%s'))
c.execute("INSERT INTO mownitoring VALUES (?, ?, ?, ?)", param)
notify(check, message, machine, notifiers, timestamp)
conn.commit()
def read_conf(config_file):
"""Parse the configuration file.
:param config_file: the path to the config writen in a toml format
:returns: machines (dict), max_workers (int), sqlite_file (path to DB)
It uses some global vars: api_cfg (dict) API keys and some path/parameters
for the check_nrpe.
"""
# No need to try catch FileNotFoundError, error message is clear enough
with open(config_file, 'r') as tomlfile:
toml_cfg = toml.load(tomlfile)
global api_cfg
api_cfg = {}
configured_notifier = []
try:
pushover = {
"pushover_token":
toml_cfg["Alerting_credentials"]["Pushover"]["token"],
"pushover_user":
toml_cfg["Alerting_credentials"]["Pushover"]["user"],
"pushover_api_url":
toml_cfg["Alerting_credentials"]["Pushover"]["api_url"]
}
api_cfg.update(pushover)
configured_notifier.append("pushover")
except KeyError:
syslog.syslog(syslog.LOG_ERR, "Pushover config is wrong or missing")
try:
mail = {
"mail_from": toml_cfg["Alerting_credentials"]["Mail"]["from"],
"mail_to": toml_cfg["Alerting_credentials"]["Mail"]["to"],
"mail_server": toml_cfg["Alerting_credentials"]["Mail"]["server"]
}
api_cfg.update(mail)
configured_notifier.append("mail")
except KeyError:
syslog.syslog(syslog.LOG_ERR, "Mail config is wrong or missing")
try:
twilio = {
"twilio_account_sid":
toml_cfg["Alerting_credentials"]["Twilio"]["account_sid"],
"twilio_auth_token":
toml_cfg["Alerting_credentials"]["Twilio"]["auth_token"],
"twilio_sender":
toml_cfg["Alerting_credentials"]["Twilio"]["sender"],
"twilio_dest":
toml_cfg["Alerting_credentials"]["Twilio"]["dest"],
"twilio_api_url":
toml_cfg["Alerting_credentials"]["Twilio"]["api_url"]
}
api_cfg.update(twilio)
configured_notifier.append("twilio")
except KeyError:
syslog.syslog(syslog.LOG_ERR, "Twilio config is wrong or missing")
if not configured_notifier:
syslog.syslog(syslog.LOG_ERR, "No alerting system configured!")
global NAGIOS_CHECK_PATH
NAGIOS_CHECK_PATH = toml_cfg["Parameters"]["nagios_check_path"]
global CHECK_NRPE_TIMEOUT
CHECK_NRPE_TIMEOUT = int(toml_cfg["Parameters"]["check_nrpe_timeout"])
global CHECK_PING_LATENCY_WARN
CHECK_PING_LATENCY_WARN = int(
toml_cfg["Parameters"]["check_ping_latency_warn"]
)
global CHECK_PING_LOSS_WARN
CHECK_PING_LOSS_WARN = int(
toml_cfg["Parameters"]["check_ping_loss_warn"]
)
global CHECK_PING_LATENCY_CRIT
CHECK_PING_LATENCY_CRIT = int(
toml_cfg["Parameters"]["check_ping_latency_crit"]
)
global CHECK_PING_LOSS_CRIT
CHECK_PING_LOSS_CRIT = int(
toml_cfg["Parameters"]["check_ping_loss_crit"]
)
max_workers = toml_cfg["Parameters"]["workers"]
sqlite_file = toml_cfg["Parameters"]["sqlite_file"]
# monitored machines
machines = toml_cfg.copy()
del machines["Alerting_credentials"]
del machines["Parameters"]
return machines, max_workers, sqlite_file
def sqlite_init(sqlite_file):
"""Initialize database."""
conn = sqlite3.connect(sqlite_file)
with conn:
conn.execute('CREATE TABLE IF NOT EXISTS mownitoring (machine TEXT, ' +
'check_name TEXT, status INTEGER, mtime INTEGER);')
conn.close()
def check_machine(machines, machine, sqlite_file):
try:
host = machines[machine][2]["connection"]["ip"]
port = machines[machine][2]["connection"]["port"]
except IndexError:
host = machine
port = "5666"
timestamp, status, message = run_check(host, "ping")
conn = sqlite3.connect(sqlite_file)
register_and_alert("ping", host, "5666", machine,
machines[machine][1]["alert"], conn, timestamp, status,
message)
if status == 0:
for check in machines[machine][0]["checks"]:
timestamp, status, message = run_check(host, port, check)
register_and_alert(check, host, port, machine,
machines[machine][1]["alert"], conn, timestamp,
status, message)
conn.close()
if __name__ == "__main__":
if not sys.version_info >= (3, 6):
print("You need python 3.6 or later")
sys.exit(1)
config_file = "/etc/mownitoring.toml"
if len(sys.argv) > 1:
config_file = sys.argv[1]
syslog.syslog("mownitoring starts")
machines, max_workers, sqlite_file = read_conf(config_file)
if not os.path.isfile(NAGIOS_CHECK_PATH + "/check_nrpe"):
raise FileNotFoundError("No such file or directory: "
f"{NAGIOS_CHECK_PATH}/check_nrpe")
if not os.path.isfile(NAGIOS_CHECK_PATH + "/check_ping"):
raise FileNotFoundError("No such file or directory: "
f"{NAGIOS_CHECK_PATH}/check_ping")
sqlite_init(sqlite_file)
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) \
as executor:
{executor.submit(check_machine, machines, machine, sqlite_file):
machine for machine in machines["machines"]}
syslog.syslog("mownitoring ends")