urgent bug fixes for danube (2)
[doctor.git] / tests / monitor.py
1 ##############################################################################
2 # Copyright (c) 2016 NEC 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
10 import argparse
11 from datetime import datetime
12 import json
13 import logger as doctor_log
14 import os
15 import requests
16 import socket
17 import sys
18 import time
19
20 from congressclient.v1 import client
21
22 import identity_auth
23
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'
27
28 SUPPORTED_INSPECTOR_TYPES = ['sample', 'congress']
29
30 LOG = doctor_log.Logger('doctor_monitor').getLogger()
31
32
33 class DoctorMonitorSample(object):
34
35     interval = 0.1  # second
36     timeout = 0.1  # second
37     event_type = "compute.host.down"
38
39     def __init__(self, args):
40         if args.inspector_type not in SUPPORTED_INSPECTOR_TYPES:
41             raise Exception("Inspector type '%s' not supported", args.inspector_type)
42
43         self.hostname = args.hostname
44         self.inspector_type = args.inspector_type
45         self.ip_addr = args.ip or socket.gethostbyname(self.hostname)
46
47         if self.inspector_type == 'sample':
48             self.inspector_url = 'http://127.0.0.1:12345/events'
49         elif self.inspector_type == 'congress':
50             auth=identity_auth.get_identity_auth()
51             sess=session.Session(auth=auth)
52             congress = client.Client(session=sess, service_type='policy')
53             ds = congress.list_datasources()['results']
54             doctor_ds = next((item for item in ds if item['driver'] == 'doctor'),
55                              None)
56
57             congress_endpoint = congress.httpclient.get_endpoint(auth=auth)
58             self.inspector_url = ('%s/v1/data-sources/%s/tables/events/rows' %
59                                   (congress_endpoint, doctor_ds['id']))
60
61     def start_loop(self):
62         LOG.debug("start ping to host %(h)s (ip=%(i)s)" % {'h': self.hostname,
63                                                        'i': self.ip_addr})
64         sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
65                              socket.IPPROTO_ICMP)
66         sock.settimeout(self.timeout)
67         while True:
68             try:
69                 sock.sendto(ICMP_ECHO_MESSAGE, (self.ip_addr, 0))
70                 data = sock.recv(4096)
71             except socket.timeout:
72                 LOG.info("doctor monitor detected at %s" % time.time())
73                 self.report_error()
74                 LOG.info("ping timeout, quit monitoring...")
75                 return
76             time.sleep(self.interval)
77
78     def report_error(self):
79         payload = [
80             {
81                 'id': 'monitor_sample_id1',
82                 'time': datetime.now().isoformat(),
83                 'type': self.event_type,
84                 'details': {
85                     'hostname': self.hostname,
86                     'status': 'down',
87                     'monitor': 'monitor_sample',
88                     'monitor_event_id': 'monitor_sample_event1'
89                 },
90             },
91         ]
92         data = json.dumps(payload)
93
94         if self.inspector_type == 'sample':
95             headers = {'content-type': 'application/json'}
96             requests.post(self.inspector_url, data=data, headers=headers)
97         elif self.inspector_type == 'congress':
98             headers = {
99                 'Content-Type': 'application/json',
100                 'Accept': 'application/json',
101                 'X-Auth-Token':self.session.get_token(),
102             }
103             requests.put(self.inspector_url, data=data, headers=headers)
104
105
106 def get_args():
107     parser = argparse.ArgumentParser(description='Doctor Sample Monitor')
108     parser.add_argument('hostname', metavar='HOSTNAME', type=str, nargs='?',
109                         help='a hostname to monitor connectivity')
110     parser.add_argument('ip', metavar='IP', type=str, nargs='?',
111                         help='an IP address to monitor connectivity')
112     parser.add_argument('inspector_type', metavar='INSPECTOR_TYPE', type=str, nargs='?',
113                         help='inspector to report',
114                         default='sample')
115     return parser.parse_args()
116
117
118 def main():
119     args = get_args()
120     monitor = DoctorMonitorSample(args)
121     monitor.start_loop()
122
123
124 if __name__ == '__main__':
125     main()