forked from fqrouter/qiang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatchdog
executable file
·77 lines (65 loc) · 2.34 KB
/
watchdog
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 python
import sys
import subprocess
import time
import os
import csv
import datetime
from qiang import config
checkers = {}
def start_checker(destination):
checkers[destination]['process'] = subprocess.Popen(
'./find-router %s' % destination, shell=True,
stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
checkers[destination]['started_at'] = time.time()
def log_error(error):
sys.stderr.write(error)
sys.stderr.write('\n')
sys.stderr.flush()
def log_message(message):
sys.stdout.write(message)
sys.stdout.write('\n')
sys.stdout.flush()
sys.stderr.write(message)
sys.stderr.write('\n')
sys.stderr.flush()
def record_event(event, destination):
log_message('%s: %s' % (event, destination))
with open(os.path.join(config.output_dir, 'watchdog.csv'), 'a') as f:
csv_writer = csv.writer(f)
csv_writer.writerow([datetime.datetime.now().isoformat(), event, destination])
for destination in sys.argv[1:]:
checkers[destination] = {
'was_blocked': None # unknown yet
}
start_checker(destination)
while True:
for destination, checker in checkers.items():
result = checker['process'].poll()
if result is None:
# not finished yet
if time.time() - checker['started_at'] > 60 * 5:
# timeout
log_message('TIMEOUT: %s' % destination)
log_error(checker['process'].stdout.read())
checker['process'].kill()
start_checker(destination)
elif 0 == result:
if checker['was_blocked'] is None:
record_event('INITIALLY NOT BLOCKED', destination)
elif checker['was_blocked']:
record_event('UNBLOCKED', destination)
start_checker(destination)
checker['was_blocked'] = False
elif 42 == result:
if checker['was_blocked'] is None:
record_event('INITIALLY BLOCKED', destination)
elif not checker['was_blocked']:
record_event('BLOCKED', destination)
start_checker(destination)
checker['was_blocked'] = True
else:
log_message('ERROR [%s]: %s' % (result, destination))
log_error(checker['process'].stdout.read())
start_checker(destination)
time.sleep(1)