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 doctor_tests.common.constants import Inspector
17 from doctor_tests.identity_auth import get_session
18 from doctor_tests.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()
29 def start(self, host):
30 self.log.info('sample monitor start......')
31 self.pinger = Pinger(host.name, host.ip, self, self.log)
35 self.log.info('sample monitor stop......')
36 if self.pinger is not None:
40 def report_error(self, hostname):
41 self.log.info('sample monitor report error......')
43 'time': datetime.now().isoformat(),
44 'type': self.event_type,
48 'monitor': 'monitor_sample',
49 'monitor_event_id': 'monitor_sample_event1'
53 auth_token = self.session.get_token() if \
54 self.conf.inspector.type != 'sample' else None
56 'Content-Type': 'application/json',
57 'Accept': 'application/json',
58 'X-Auth-Token': auth_token,
60 if self.conf.inspector.type != Inspector.VITRAGE:
61 requests.put(self.inspector_url,
62 data=json.dumps([data]),
65 requests.post(self.inspector_url,
66 data=json.dumps(data),
71 interval = 0.1 # second
72 timeout = 0.1 # second
73 ICMP_ECHO_MESSAGE = bytes([0x08, 0x00, 0xf7, 0xff, 0x00, 0x00, 0x00, 0x00])
75 def __init__(self, host_name, host_ip, monitor, log):
77 self.monitor = monitor
78 self.hostname = host_name
79 self.ip_addr = host_ip or socket.gethostbyname(self.hostname)
84 self.log.info("Starting Pinger host_name(%s), host_ip(%s)"
85 % (self.hostname, self.ip_addr))
87 sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
89 sock.settimeout(self.timeout)
94 sock.sendto(self.ICMP_ECHO_MESSAGE, (self.ip_addr, 0))
96 except socket.timeout:
97 detected_time = time.time()
98 self.log.info("doctor monitor detected at %s" % detected_time)
99 self.monitor.detected_time = detected_time
100 self.monitor.report_error(self.hostname)
101 self.log.info("ping timeout, quit monitoring...")
104 time.sleep(self.interval)
107 self.log.info("Stopping Pinger host_name(%s), host_ip(%s)"
108 % (self.hostname, self.ip_addr))