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 monitor.base import BaseMonitor
20 class SampleMonitor(BaseMonitor):
21 event_type = "compute.host.down"
23 def __init__(self, conf, inspector_url, log):
24 super(SampleMonitor, self).__init__(conf, inspector_url, log)
25 self.session = get_session()
28 def start(self, host):
29 self.log.info('sample monitor start......')
30 self.pinger = Pinger(host.name, host.ip, self, self.log)
34 self.log.info('sample monitor stop......')
35 if self.pinger is not None:
39 def report_error(self, hostname):
40 self.log.info('sample monitor report error......')
43 'id': 'monitor_sample_id1',
44 'time': datetime.now().isoformat(),
45 'type': self.event_type,
49 'monitor': 'monitor_sample',
50 'monitor_event_id': 'monitor_sample_event1'
55 auth_token = self.session.get_token() if \
56 self.conf.inspector.type != 'sample' else None
58 'Content-Type': 'application/json',
59 'Accept': 'application/json',
60 'X-Auth-Token': auth_token,
63 url = '%s%s' % (self.inspector_url, 'events') \
64 if self.inspector_url.endswith('/') else \
65 '%s%s' % (self.inspector_url, '/events')
66 requests.put(url, data=json.dumps(data), headers=headers)
70 interval = 0.1 # second
71 timeout = 0.1 # second
72 ICMP_ECHO_MESSAGE = bytes([0x08, 0x00, 0xf7, 0xff, 0x00, 0x00, 0x00, 0x00])
74 def __init__(self, host_name, host_ip, monitor, log):
76 self.monitor = monitor
77 self.hostname = host_name
78 self.ip_addr = host_ip or socket.gethostbyname(self.hostname)
83 self.log.info("Starting Pinger host_name(%s), host_ip(%s)"
84 % (self.hostname, self.ip_addr))
86 sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
88 sock.settimeout(self.timeout)
93 sock.sendto(self.ICMP_ECHO_MESSAGE, (self.ip_addr, 0))
95 except socket.timeout:
96 self.log.info("doctor monitor detected at %s" % time.time())
97 self.monitor.report_error(self.hostname)
98 self.log.info("ping timeout, quit monitoring...")
101 time.sleep(self.interval)
104 self.log.info("Stopping Pinger host_name(%s), host_ip(%s)"
105 % (self.hostname, self.ip_addr))