refactor failure inject
[doctor.git] / tests / monitor / sample.py
1 ##############################################################################
2 # Copyright (c) 2017 ZTE Corporation and others.
3 #
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
10 import json
11 import requests
12 import socket
13 from threading import Thread
14 import time
15
16 from identity_auth import get_session
17 from monitor.base import BaseMonitor
18
19
20 class SampleMonitor(BaseMonitor):
21     event_type = "compute.host.down"
22
23     def __init__(self, conf, inspector_url, log):
24         super(SampleMonitor, self).__init__(conf, inspector_url, log)
25         self.session = get_session()
26         self.pinger = None
27
28     def start(self, host):
29         self.log.info('sample monitor start......')
30         self.pinger = Pinger(host.name, host.ip, self, self.log)
31         self.pinger.start()
32
33     def stop(self):
34         self.log.info('sample monitor stop......')
35         if self.pinger is not None:
36             self.pinger.stop()
37             self.pinger.join()
38
39     def report_error(self, hostname):
40         self.log.info('sample monitor report error......')
41         data = [
42             {
43                 'id': 'monitor_sample_id1',
44                 'time': datetime.now().isoformat(),
45                 'type': self.event_type,
46                 'details': {
47                     'hostname': hostname,
48                     'status': 'down',
49                     'monitor': 'monitor_sample',
50                     'monitor_event_id': 'monitor_sample_event1'
51                 },
52             },
53         ]
54
55         auth_token = self.session.get_token() if \
56                      self.conf.inspector.type != 'sample' else None
57         headers = {
58             'Content-Type': 'application/json',
59             'Accept': 'application/json',
60             'X-Auth-Token': auth_token,
61         }
62
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)
67
68
69 class Pinger(Thread):
70     interval = 0.1  # second
71     timeout = 0.1   # second
72     ICMP_ECHO_MESSAGE = bytes([0x08, 0x00, 0xf7, 0xff, 0x00, 0x00, 0x00, 0x00])
73
74     def __init__(self, host_name, host_ip, monitor, log):
75         Thread.__init__(self)
76         self.monitor = monitor
77         self.hostname = host_name
78         self.ip_addr = host_ip or socket.gethostbyname(self.hostname)
79         self.log = log
80         self._stopped = False
81
82     def run(self):
83         self.log.info("Starting Pinger host_name(%s), host_ip(%s)"
84                       % (self.hostname, self.ip_addr))
85
86         sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
87                              socket.IPPROTO_ICMP)
88         sock.settimeout(self.timeout)
89         while True:
90             if self._stopped:
91                 return
92             try:
93                 sock.sendto(self.ICMP_ECHO_MESSAGE, (self.ip_addr, 0))
94                 sock.recv(4096)
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...")
99                 self._stopped = True
100                 return
101             time.sleep(self.interval)
102
103     def stop(self):
104         self.log.info("Stopping Pinger host_name(%s), host_ip(%s)"
105                       % (self.hostname, self.ip_addr))
106         self._stopped = True