1 ##############################################################################
2 # Copyright (c) 2017 ZTE 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 ##############################################################################
9 from datetime import datetime
13 from threading import Thread
16 from identity_auth import get_session
17 from os_clients import nova_client
18 from monitor.base import BaseMonitor
21 class SampleMonitor(BaseMonitor):
22 event_type = "compute.host.down"
24 def __init__(self, conf, inspector_url, log):
25 super(SampleMonitor, self).__init__(conf, inspector_url, log)
26 self.session = get_session()
27 self.nova = nova_client(conf.nova_version, self.session)
28 self.hosts = self.nova.hypervisors.list(detailed=True)
32 self.log.info('sample monitor start......')
33 for host in self.hosts:
34 host_dict = host.__dict__
35 host_name = host_dict['hypervisor_hostname']
36 host_ip = host_dict['host_ip']
37 pinger = Pinger(host_name, host_ip, self, self.log)
39 self.pingers.append(pinger)
42 self.log.info('sample monitor stop......')
43 for pinger in self.pingers:
48 def report_error(self, hostname):
49 self.log.info('sample monitor report error......')
52 'id': 'monitor_sample_id1',
53 'time': datetime.now().isoformat(),
54 'type': self.event_type,
58 'monitor': 'monitor_sample',
59 'monitor_event_id': 'monitor_sample_event1'
64 auth_token = self.session.get_token() if \
65 self.conf.inspector.type != 'sample' else None
67 'Content-Type': 'application/json',
68 'Accept': 'application/json',
69 'X-Auth-Token': auth_token,
72 url = '%s%s' % (self.inspector_url, 'events') \
73 if self.inspector_url.endswith('/') else \
74 '%s%s' % (self.inspector_url, '/events')
75 requests.put(url, data=json.dumps(data), headers=headers)
79 interval = 0.1 # second
80 timeout = 0.1 # second
81 ICMP_ECHO_MESSAGE = '\x08\x00\xf7\xff\x00\x00\x00\x00'
83 def __init__(self, host_name, host_ip, monitor, log):
85 self.monitor = monitor
86 self.hostname = host_name
87 self.ip_addr = host_ip or socket.gethostbyname(self.hostname)
96 time.sleep(self.interval)
99 self.log.info("Stopping Pinger host_name(%s), host_ip(%s)"
100 % (self.hostname, self.ip_addr))
104 self.log.info("Starting Pinger host_name(%s), host_ip(%s)"
105 % (self.hostname, self.ip_addr))
107 sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
109 sock.settimeout(self.timeout)
112 sock.sendto(self.ICMP_ECHO_MESSAGE.encode(), (self.ip_addr, 0))
114 except socket.timeout:
115 self.log.info("doctor monitor detected at %s" % time.time())
116 self.monitor.report_error(self.hostname)
117 self.log.info("ping timeout, quit monitoring...")