remove `Debug = True when run Flask and add logger
[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 from keystoneclient import session as ksc_session
22 from keystoneclient.auth.identity import v2
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 class DoctorMonitorSample(object):
33
34     interval = 0.1  # second
35     timeout = 0.1  # second
36     event_type = "compute.host.down"
37
38     def __init__(self, args):
39         if args.inspector_type not in SUPPORTED_INSPECTOR_TYPES:
40             raise Exception("Inspector type '%s' not supported", args.inspector_type)
41
42         self.hostname = args.hostname
43         self.inspector_url = args.inspector_url
44         self.inspector_type = args.inspector_type
45         self.ip_addr = args.ip or socket.gethostbyname(self.hostname)
46
47         if self.inspector_type == 'congress':
48             auth = v2.Password(auth_url=os.environ['OS_AUTH_URL'],
49                                username=os.environ['OS_USERNAME'],
50                                password=os.environ['OS_PASSWORD'],
51                                tenant_name=os.environ['OS_TENANT_NAME'])
52             self.session = ksc_session.Session(auth=auth)
53
54             congress = client.Client(session=self.session, service_type='policy')
55             ds = congress.list_datasources()['results']
56             doctor_ds = next((item for item in ds if item['driver'] == 'doctor'),
57                              None)
58
59             congress_endpoint = congress.httpclient.get_endpoint(auth=auth)
60             self.inspector_url = ('%s/v1/data-sources/%s/tables/events/rows' %
61                                   (congress_endpoint, doctor_ds['id']))
62
63     def start_loop(self):
64         LOG.debug("start ping to host %(h)s (ip=%(i)s)" % {'h': self.hostname,
65                                                        'i': self.ip_addr})
66         sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
67                              socket.IPPROTO_ICMP)
68         sock.settimeout(self.timeout)
69         while True:
70             try:
71                 sock.sendto(ICMP_ECHO_MESSAGE, (self.ip_addr, 0))
72                 data = sock.recv(4096)
73             except socket.timeout:
74                 LOG.info("doctor monitor detected at %s" % time.time())
75                 self.report_error()
76                 LOG.info("ping timeout, quit monitoring...")
77                 return
78             time.sleep(self.interval)
79
80     def report_error(self):
81         if self.inspector_type == 'sample':
82             payload = {"type": self.event_type, "hostname": self.hostname}
83             data = json.dumps(payload)
84             headers = {'content-type': 'application/json'}
85             requests.post(self.inspector_url, data=data, headers=headers)
86         elif self.inspector_type == 'congress':
87             data = [
88                 {
89                     'id': 'monitor_sample_id1',
90                     'time': datetime.now().isoformat(),
91                     'type': self.event_type,
92                     'details': {
93                         'hostname': self.hostname,
94                         'status': 'down',
95                         'monitor': 'monitor_sample',
96                         'monitor_event_id': 'monitor_sample_event1'
97                     },
98                 },
99             ]
100
101             headers = {
102                 'Content-Type': 'application/json',
103                 'Accept': 'application/json',
104                 'X-Auth-Token':self.session.get_token(),
105             }
106
107             requests.put(self.inspector_url, data=json.dumps(data), headers=headers)
108
109
110 def get_args():
111     parser = argparse.ArgumentParser(description='Doctor Sample Monitor')
112     parser.add_argument('hostname', metavar='HOSTNAME', type=str, nargs='?',
113                         help='a hostname to monitor connectivity')
114     parser.add_argument('ip', metavar='IP', type=str, nargs='?',
115                         help='an IP address to monitor connectivity')
116     parser.add_argument('inspector_type', metavar='INSPECTOR_TYPE', type=str, nargs='?',
117                         help='inspector to report',
118                         default='sample')
119     parser.add_argument('inspector_url', metavar='INSPECTOR_URL', type=str, nargs='?',
120                         help='inspector url to report error',
121                         default='http://127.0.0.1:12345/events')
122     return parser.parse_args()
123
124
125 def main():
126     args = get_args()
127     monitor = DoctorMonitorSample(args)
128     monitor.start_loop()
129
130
131 if __name__ == '__main__':
132     main()