-
Notifications
You must be signed in to change notification settings - Fork 0
/
health_check.py
78 lines (55 loc) · 2.34 KB
/
health_check.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
#!/usr/bin/env python3
import os
import psutil
import socket
import emails
CPU_THRESHOLD = 80 # percent (error if cpu usage higher than threshold)
DISC_THRESHOLD = 20 # percent (error if available disc space lower than threshold)
MEMORY_THRESHOLD = 500 # MB (error if available memory lower than threshold)
def check_cpu_usage(cpu_threshold: int) -> str:
cpu_usage = psutil.cpu_percent()
print(f"cpu usage: {cpu_usage}%")
if cpu_usage > cpu_threshold:
return 'NOK'
return 'OK'
def check_disc_usage(disc_threshold: int) -> str:
disc_available = 100 - psutil.disk_usage('/').percent
print(f"disc available: {disc_available}%")
if disc_available < disc_threshold:
return 'NOK'
return 'OK'
def check_memory_usage(memory_threshold: int) -> str:
memory_available = psutil.virtual_memory().available / 1000000
print(f"memory available: {int(memory_available)}MB")
if memory_available < memory_threshold:
return 'NOK'
return 'OK'
def check_hostname() -> str:
local_address = socket.gethostbyname('localhost')
print(f"local address: {local_address}")
if local_address != '127.0.0.1':
return 'NOK'
return 'OK'
def send_error_email(subject: str) -> None:
sender = "[email protected]"
recipient = "{}@example.com".format(os.environ["USER"])
body = "Please check your system and resolve the issue as soon as possible."
message = emails.generate_email(sender, recipient, subject, body)
try:
emails.send_email(message)
except ConnectionRefusedError as err:
print(f"Cannot send an e-mail => {err}")
def monitoring() -> None:
subject = {"cpu": "Error - CPU usage is over {}%".format(CPU_THRESHOLD),
"disc": "Error - Available disk space is less than {}%".format(DISC_THRESHOLD),
"memory": "Error - Available memory is less than {}MB".format(MEMORY_THRESHOLD),
"hostname": "Error - localhost cannot be resolved to 127.0.0.1"}
if check_cpu_usage(CPU_THRESHOLD) == 'NOK':
send_error_email(subject['cpu'])
if check_disc_usage(DISC_THRESHOLD) == 'NOK':
send_error_email(subject['disc'])
if check_memory_usage(MEMORY_THRESHOLD) == 'NOK':
send_error_email(subject['memory'])
if check_hostname() == 'NOK':
send_error_email(subject['hostname'])
monitoring()