1 ##############################################################################
2 # Copyright (c) 2016 NEC Corporation and others.
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 ##############################################################################
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'
22 class DoctorMonitorSample(object):
24 interval = 0.1 # second
25 timeout = 0.1 # second
26 event_type = "compute.host.down"
28 def __init__(self, args):
29 self.hostname = args.hostname
30 self.inspector = args.inspector
31 self.ip_addr = args.ip or socket.gethostbyname(self.hostname)
34 print "start ping to host %(h)s (ip=$(i)s)" % {'h': self.hostname,
36 sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
38 sock.settimeout(self.timeout)
41 sock.sendto(ICMP_ECHO_MESSAGE, (self.ip_addr, 0))
42 data = sock.recv(4096)
43 except socket.timeout:
44 print "doctor monitor detected at %s" % time.time()
46 print "ping timeout, quit monitoring..."
48 time.sleep(self.interval)
50 def report_error(self):
51 payload = {"type": self.event_type, "hostname": self.hostname}
52 data = json.dumps(payload)
53 headers = {'content-type': 'application/json'}
54 requests.post(self.inspector, data=data, headers=headers)
58 parser = argparse.ArgumentParser(description='Doctor Sample Monitor')
59 parser.add_argument('hostname', metavar='HOSTNAME', type=str, nargs='?',
60 help='a hostname to monitor connectivity')
61 parser.add_argument('ip', metavar='IP', type=str, nargs='?',
62 help='an IP address to monitor connectivity')
63 parser.add_argument('inspector', metavar='INSPECTOR', type=str, nargs='?',
64 help='inspector url to report error',
65 default='http://127.0.0.1:12345/events')
66 return parser.parse_args()
71 monitor = DoctorMonitorSample(args)
75 if __name__ == '__main__':