Documents up-to-date
[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 from flask import Flask
12 from flask import request
13 import json
14 import os
15
16 import novaclient.client as novaclient
17
18
19 class DoctorInspectorSample(object):
20
21     nova_api_version = 2.11
22
23     def __init__(self):
24         self.nova = novaclient.Client(self.nova_api_version,
25                                       os.environ['OS_USERNAME'],
26                                       os.environ['OS_PASSWORD'],
27                                       os.environ['OS_TENANT_NAME'],
28                                       os.environ['OS_AUTH_URL'],
29                                       connection_pool=True)
30         # check nova is available
31         self.nova.servers.list(detailed=False)
32
33     def disable_compute_host(self, hostname):
34         opts = {'all_tenants': True, 'host': hostname}
35         for server in self.nova.servers.list(detailed=False, search_opts=opts):
36             self.nova.servers.reset_state(server, 'error')
37         self.nova.services.force_down(hostname, 'nova-compute', True)
38
39
40 app = Flask(__name__)
41 inspector = DoctorInspectorSample()
42
43
44 @app.route('/events', methods=['POST'])
45 def event_posted():
46     app.logger.debug('event posted')
47     app.logger.debug('inspector = %s' % inspector)
48     app.logger.debug('received data = %s' % request.data)
49     d = json.loads(request.data)
50     hostname = d['hostname']
51     event_type = d['type']
52     if event_type == 'compute.host.down':
53         inspector.disable_compute_host(hostname)
54     return "OK"
55
56
57 def get_args():
58     parser = argparse.ArgumentParser(description='Doctor Sample Monitor')
59     parser.add_argument('port', metavar='PORT', type=int, nargs='?',
60                         help='a port for inspectpr')
61     return parser.parse_args()
62
63
64 def main():
65     args = get_args()
66     app.run(port=args.port, debug=True)
67
68
69 if __name__ == '__main__':
70     main()