-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuptime.py
76 lines (58 loc) · 1.68 KB
/
uptime.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
import sys
import os
import json
import socket
from subprocess import Popen
from urlparse import urlparse
try:
from subprocess import DEVNULL
except ImportError:
import os
DEVNULL = open(os.devnull, 'wb')
def run_check(services, down_actions, up_actions):
for service, data in services.items():
url = data.get('url')
port = data.get('port')
is_up = ping(url, port)
actions = up_actions if is_up else down_actions
for action in actions:
action = action.replace("$SERVICE", service)
Popen([action],
shell=True,
stdin=None,
stdout=DEVNULL,
stderr=DEVNULL,
close_fds=True
)
def ping(url, port):
if not url: return False
parsed = urlparse(url)
if parsed.netloc:
url = parsed.netloc
else:
try:
socket.inet_aton(url)
except socket.error:
return False
if not port:
port = 443 if parsed.scheme == 'https' else 80
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
result = sock.connect_ex((url, port))
except Exception as e:
return False
return result == 0
if __name__ == '__main__':
config_path = os.path.join(os.path.dirname(__file__), "config.json")
if not os.path.exists(config_path):
sys.exit("You need to create a config.json file")
try:
config = json.loads(open(config_path, 'r').read())
except Exception as e:
sys.exit("config.json file is invalid")
services = config.get('services')
down_actions = config.get('down')
up_actions = config.get('up')
if not services or not (down_actions or up_actions):
sys.exit("You need to specify services, and a down or up action")
run_check(services, down_actions, up_actions)