Merge "Support recovering VM on the same host"
[doctor.git] / tests / inspector.py
1 #
2 # Copyright 2016 NEC Corporation.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 #      http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import argparse
17 from flask import Flask
18 from flask import request
19 import json
20 import os
21
22 import novaclient.client as novaclient
23
24
25 class DoctorInspectorSample(object):
26
27     nova_api_version = 2.11
28
29     def __init__(self):
30         self.nova = novaclient.Client(self.nova_api_version,
31                                       os.environ['OS_USERNAME'],
32                                       os.environ['OS_PASSWORD'],
33                                       os.environ['OS_TENANT_NAME'],
34                                       os.environ['OS_AUTH_URL'],
35                                       connection_pool=True)
36         # check nova is available
37         self.nova.servers.list(detailed=False)
38
39     def disable_compute_host(self, hostname):
40         opts = {'all_tenants': True, 'host': hostname}
41         for server in self.nova.servers.list(detailed=False, search_opts=opts):
42             self.nova.servers.reset_state(server, 'error')
43         self.nova.services.force_down(hostname, 'nova-compute', True)
44
45
46 app = Flask(__name__)
47 inspector = DoctorInspectorSample()
48
49
50 @app.route('/events', methods=['POST'])
51 def event_posted():
52     app.logger.debug('event posted')
53     app.logger.debug('inspector = %s' % inspector)
54     app.logger.debug('received data = %s' % request.data)
55     d = json.loads(request.data)
56     hostname = d['hostname']
57     event_type = d['type']
58     if event_type == 'compute.host.down':
59         inspector.disable_compute_host(hostname)
60     return "OK"
61
62
63 def get_args():
64     parser = argparse.ArgumentParser(description='Doctor Sample Monitor')
65     parser.add_argument('port', metavar='PORT', type=int, nargs='?',
66                         help='a port for inspectpr')
67     return parser.parse_args()
68
69
70 def main():
71     args = get_args()
72     app.run(port=args.port, debug=True)
73
74
75 if __name__ == '__main__':
76     main()