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 ##############################################################################
11 from datetime import datetime
13 import logger as doctor_log
20 from congressclient.v1 import client
21 from keystoneclient import session as ksc_session
22 from keystoneclient.auth.identity import v2
24 # NOTE: icmp message with all zero data (checksum = 0xf7ff)
25 # see https://tools.ietf.org/html/rfc792
26 ICMP_ECHO_MESSAGE = '\x08\x00\xf7\xff\x00\x00\x00\x00'
28 SUPPORTED_INSPECTOR_TYPES = ['sample', 'congress']
30 LOG = doctor_log.Logger('doctor_monitor').getLogger()
32 class DoctorMonitorSample(object):
34 interval = 0.1 # second
35 timeout = 0.1 # second
36 event_type = "compute.host.down"
38 def __init__(self, args):
39 if args.inspector_type not in SUPPORTED_INSPECTOR_TYPES:
40 raise Exception("Inspector type '%s' not supported", args.inspector_type)
42 self.hostname = args.hostname
43 self.inspector_type = args.inspector_type
44 self.ip_addr = args.ip or socket.gethostbyname(self.hostname)
46 if self.inspector_type == 'sample':
47 self.inspector_url = 'http://127.0.0.1:12345/events'
48 elif self.inspector_type == 'congress':
49 auth = v2.Password(auth_url=os.environ['OS_AUTH_URL'],
50 username=os.environ['OS_USERNAME'],
51 password=os.environ['OS_PASSWORD'],
52 tenant_name=os.environ['OS_TENANT_NAME'])
53 self.session = ksc_session.Session(auth=auth)
55 congress = client.Client(session=self.session, service_type='policy')
56 ds = congress.list_datasources()['results']
57 doctor_ds = next((item for item in ds if item['driver'] == 'doctor'),
60 congress_endpoint = congress.httpclient.get_endpoint(auth=auth)
61 self.inspector_url = ('%s/v1/data-sources/%s/tables/events/rows' %
62 (congress_endpoint, doctor_ds['id']))
65 LOG.debug("start ping to host %(h)s (ip=%(i)s)" % {'h': self.hostname,
67 sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
69 sock.settimeout(self.timeout)
72 sock.sendto(ICMP_ECHO_MESSAGE, (self.ip_addr, 0))
73 data = sock.recv(4096)
74 except socket.timeout:
75 LOG.info("doctor monitor detected at %s" % time.time())
77 LOG.info("ping timeout, quit monitoring...")
79 time.sleep(self.interval)
81 def report_error(self):
84 'id': 'monitor_sample_id1',
85 'time': datetime.now().isoformat(),
86 'type': self.event_type,
88 'hostname': self.hostname,
90 'monitor': 'monitor_sample',
91 'monitor_event_id': 'monitor_sample_event1'
95 data = json.dumps(payload)
97 if self.inspector_type == 'sample':
98 headers = {'content-type': 'application/json'}
99 requests.post(self.inspector_url, data=data, headers=headers)
100 elif self.inspector_type == 'congress':
102 'Content-Type': 'application/json',
103 'Accept': 'application/json',
104 'X-Auth-Token':self.session.get_token(),
106 requests.put(self.inspector_url, data=data, headers=headers)
110 parser = argparse.ArgumentParser(description='Doctor Sample Monitor')
111 parser.add_argument('hostname', metavar='HOSTNAME', type=str, nargs='?',
112 help='a hostname to monitor connectivity')
113 parser.add_argument('ip', metavar='IP', type=str, nargs='?',
114 help='an IP address to monitor connectivity')
115 parser.add_argument('inspector_type', metavar='INSPECTOR_TYPE', type=str, nargs='?',
116 help='inspector to report',
118 return parser.parse_args()
123 monitor = DoctorMonitorSample(args)
127 if __name__ == '__main__':