2 # Copyright 2016 NEC Corporation.
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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
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'
28 class DoctorMonitorSample(object):
30 interval = 0.1 # second
31 timeout = 0.1 # second
32 event_type = "compute.host.down"
34 def __init__(self, args):
35 self.hostname = args.hostname
36 self.inspector = args.inspector
37 self.ip_addr = socket.gethostbyname(self.hostname)
40 print "start ping to host %s" % self.hostname
41 sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
43 sock.settimeout(self.timeout)
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()
51 print "ping timeout, quit monitoring..."
53 time.sleep(self.interval)
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)
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()
74 monitor = DoctorMonitorSample(args)
78 if __name__ == '__main__':