add test scenario and sample components
[doctor.git] / tests / monitor.py
1 #
2 # Copyright 2016 NEC Corporation.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 #      http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import argparse
17 import json
18 import requests
19 import socket
20 import time
21
22
23 # NOTE: icmp message with all zero data (checksum = 0xf7ff)
24 #       see https://tools.ietf.org/html/rfc792
25 ICMP_ECHO_MESSAGE = '\x08\x00\xf7\xff\x00\x00\x00\x00'
26
27
28 class DoctorMonitorSample(object):
29
30     interval = 0.1  # second
31     timeout = 0.1  # second
32     event_type = "compute.host.down"
33
34     def __init__(self, args):
35         self.hostname = args.hostname
36         self.inspector = args.inspector
37         self.ip_addr = socket.gethostbyname(self.hostname)
38
39     def start_loop(self):
40         print "start ping to host %s" % self.hostname
41         sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
42                              socket.IPPROTO_ICMP)
43         sock.settimeout(self.timeout)
44         while True:
45             try:
46                 sock.sendto(ICMP_ECHO_MESSAGE, (self.ip_addr, 0))
47                 data = sock.recv(4096)
48             except socket.timeout:
49                 print "doctor monitor detected at %s" % time.time()
50                 self.report_error()
51                 print "ping timeout, quit monitoring..."
52                 return
53             time.sleep(self.interval)
54
55     def report_error(self):
56         payload = {"type": self.event_type, "hostname": self.hostname}
57         data = json.dumps(payload)
58         headers = {'content-type': 'application/json'}
59         requests.post(self.inspector, data=data, headers=headers)
60
61
62 def get_args():
63     parser = argparse.ArgumentParser(description='Doctor Sample Monitor')
64     parser.add_argument('hostname', metavar='HOSTNAME', type=str, nargs='?',
65                         help='a hostname to monitor connectivity')
66     parser.add_argument('inspector', metavar='INSPECTOR', type=str, nargs='?',
67                         help='inspector url to report error',
68                         default='http://127.0.0.1:12345/events')
69     return parser.parse_args()
70
71
72 def main():
73     args = get_args()
74     monitor = DoctorMonitorSample(args)
75     monitor.start_loop()
76
77
78 if __name__ == '__main__':
79     main()