remove `Debug = True when run Flask and add logger
[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
58         # NOTE: We use our own client here instead of this novaclient for a
59         #       workaround.  Once keystone provides v2.1 nova api endpoint
60         #       in the service catalog which is configured by OpenStack
61         #       installer, we can use this:
62         #
63         # self.nova.services.force_down(hostname, 'nova-compute', True)
64         #
65         nova_force_down.force_down(hostname)
66
67
68 app = Flask(__name__)
69 inspector = DoctorInspectorSample()
70
71
72 @app.route('/events', methods=['POST'])
73 def event_posted():
74     LOG.info('event posted at %s' % time.time())
75     LOG.info('inspector = %s' % inspector)
76     LOG.info('received data = %s' % request.data)
77     d = json.loads(request.data)
78     hostname = d['hostname']
79     event_type = d['type']
80     if event_type == 'compute.host.down':
81         inspector.disable_compute_host(hostname)
82     return "OK"
83
84
85 def get_args():
86     parser = argparse.ArgumentParser(description='Doctor Sample Inspector')
87     parser.add_argument('port', metavar='PORT', type=int, nargs='?',
88                         help='a port for inspector')
89     return parser.parse_args()
90
91
92 def main():
93     args = get_args()
94     app.run(port=args.port)
95
96
97 if __name__ == '__main__':
98     main()