953ef09b0a7ce7716a83f4f269b39a03251b0c81
[doctor.git] / tests / monitor.py
1 ##############################################################################
2 # Copyright (c) 2016 NEC Corporation and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 import argparse
11 import json
12 import requests
13 import socket
14 import time
15
16
17 # NOTE: icmp message with all zero data (checksum = 0xf7ff)
18 #       see https://tools.ietf.org/html/rfc792
19 ICMP_ECHO_MESSAGE = '\x08\x00\xf7\xff\x00\x00\x00\x00'
20
21
22 class DoctorMonitorSample(object):
23
24     interval = 0.1  # second
25     timeout = 0.1  # second
26     event_type = "compute.host.down"
27
28     def __init__(self, args):
29         self.hostname = args.hostname
30         self.inspector = args.inspector
31         self.ip_addr = socket.gethostbyname(self.hostname)
32
33     def start_loop(self):
34         print "start ping to host %s" % self.hostname
35         sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
36                              socket.IPPROTO_ICMP)
37         sock.settimeout(self.timeout)
38         while True:
39             try:
40                 sock.sendto(ICMP_ECHO_MESSAGE, (self.ip_addr, 0))
41                 data = sock.recv(4096)
42             except socket.timeout:
43                 print "doctor monitor detected at %s" % time.time()
44                 self.report_error()
45                 print "ping timeout, quit monitoring..."
46                 return
47             time.sleep(self.interval)
48
49     def report_error(self):
50         payload = {"type": self.event_type, "hostname": self.hostname}
51         data = json.dumps(payload)
52         headers = {'content-type': 'application/json'}
53         requests.post(self.inspector, data=data, headers=headers)
54
55
56 def get_args():
57     parser = argparse.ArgumentParser(description='Doctor Sample Monitor')
58     parser.add_argument('hostname', metavar='HOSTNAME', type=str, nargs='?',
59                         help='a hostname to monitor connectivity')
60     parser.add_argument('inspector', metavar='INSPECTOR', type=str, nargs='?',
61                         help='inspector url to report error',
62                         default='http://127.0.0.1:12345/events')
63     return parser.parse_args()
64
65
66 def main():
67     args = get_args()
68     monitor = DoctorMonitorSample(args)
69     monitor.start_loop()
70
71
72 if __name__ == '__main__':
73     main()