Add more timestamps and export them for profiler
[doctor.git] / tests / inspector.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 import collections
12 from flask import Flask
13 from flask import request
14 import json
15 import logger as doctor_log
16 import os
17 import time
18
19 import novaclient.client as novaclient
20
21 import nova_force_down
22
23 LOG = doctor_log.Logger('doctor_inspector').getLogger()
24
25
26 class DoctorInspectorSample(object):
27
28     nova_api_version = '2.11'
29
30     def __init__(self):
31         self.servers = collections.defaultdict(list)
32         self.nova = novaclient.Client(self.nova_api_version,
33                                       os.environ['OS_USERNAME'],
34                                       os.environ['OS_PASSWORD'],
35                                       os.environ['OS_TENANT_NAME'],
36                                       os.environ['OS_AUTH_URL'],
37                                       connection_pool=True)
38         # check nova is available
39         self.nova.servers.list(detailed=False)
40         self.init_servers_list()
41
42     def init_servers_list(self):
43         opts = {'all_tenants': True}
44         servers=self.nova.servers.list(search_opts=opts)
45         self.servers.clear()
46         for server in servers:
47             try:
48                 host=server.__dict__.get('OS-EXT-SRV-ATTR:host')
49                 self.servers[host].append(server)
50                 LOG.debug('get hostname=%s from server=%s' % (host, server))
51             except Exception as e:
52                 LOG.error('can not get hostname from server=%s' % server)
53
54     def disable_compute_host(self, hostname):
55         for server in self.servers[hostname]:
56             self.nova.servers.reset_state(server, 'error')
57             LOG.info('doctor mark vm(%s) error at %s' % (server, time.time()))
58
59         # NOTE: We use our own client here instead of this novaclient for a
60         #       workaround.  Once keystone provides v2.1 nova api endpoint
61         #       in the service catalog which is configured by OpenStack
62         #       installer, we can use this:
63         #
64         # self.nova.services.force_down(hostname, 'nova-compute', True)
65         #
66         nova_force_down.force_down(hostname)
67         LOG.info('doctor mark host(%s) down at %s' % (hostname, time.time()))
68
69
70 app = Flask(__name__)
71 inspector = DoctorInspectorSample()
72
73
74 @app.route('/events', methods=['POST'])
75 def event_posted():
76     LOG.info('event posted at %s' % time.time())
77     LOG.info('inspector = %s' % inspector)
78     LOG.info('received data = %s' % request.data)
79     d = json.loads(request.data)
80     for event in d:
81         hostname = event['details']['hostname']
82         event_type = event['type']
83         if event_type == 'compute.host.down':
84             inspector.disable_compute_host(hostname)
85     return "OK"
86
87
88 def get_args():
89     parser = argparse.ArgumentParser(description='Doctor Sample Inspector')
90     parser.add_argument('port', metavar='PORT', type=int, nargs='?',
91                         help='a port for inspector')
92     return parser.parse_args()
93
94
95 def main():
96     args = get_args()
97     app.run(port=args.port)
98
99
100 if __name__ == '__main__':
101     main()