/
hosts.py
292 lines (265 loc) · 12.2 KB
/
hosts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""The hosts admin extension."""
from oslo_log import log as logging
import webob.exc
from nova.api.openstack import common
from nova.api.openstack.compute.schemas import hosts
from nova.api.openstack import wsgi
from nova.api import validation
from nova.compute import api as compute
from nova import context as nova_context
from nova import exception
from nova import objects
from nova.policies import hosts as hosts_policies
LOG = logging.getLogger(__name__)
class HostController(wsgi.Controller):
"""The Hosts API controller for the OpenStack API."""
def __init__(self):
super(HostController, self).__init__()
self.api = compute.HostAPI()
@wsgi.Controller.api_version("2.1", "2.42")
@validation.query_schema(hosts.index_query)
@wsgi.expected_errors(())
def index(self, req):
"""Returns a dict in the format
| {'hosts': [{'host_name': 'some.host.name',
| 'service': 'cells',
| 'zone': 'internal'},
| {'host_name': 'some.other.host.name',
| 'service': 'cells',
| 'zone': 'internal'},
| {'host_name': 'some.celly.host.name',
| 'service': 'cells',
| 'zone': 'internal'},
| {'host_name': 'compute1.host.com',
| 'service': 'compute',
| 'zone': 'nova'},
| {'host_name': 'compute2.host.com',
| 'service': 'compute',
| 'zone': 'nova'},
| {'host_name': 'sched1.host.com',
| 'service': 'scheduler',
| 'zone': 'internal'},
| {'host_name': 'sched2.host.com',
| 'service': 'scheduler',
| 'zone': 'internal'},
| {'host_name': 'vol1.host.com',
| 'service': 'volume',
| 'zone': 'internal'}]}
"""
context = req.environ['nova.context']
context.can(hosts_policies.POLICY_NAME % 'list',
target={})
filters = {'disabled': False}
zone = req.GET.get('zone', None)
if zone:
filters['availability_zone'] = zone
services = self.api.service_get_all(context, filters=filters,
set_zones=True, all_cells=True)
hosts = []
api_services = ('nova-osapi_compute', 'nova-metadata')
for service in services:
if service.binary not in api_services:
hosts.append({'host_name': service['host'],
'service': service['topic'],
'zone': service['availability_zone']})
return {'hosts': hosts}
@wsgi.Controller.api_version("2.1", "2.42")
@wsgi.expected_errors((400, 404, 501))
@validation.schema(hosts.update)
def update(self, req, id, body):
"""Return booleanized version of body dict.
:param Request req: The request object (containing 'nova-context'
env var).
:param str id: The host name.
:param dict body: example format {'host': {'status': 'enable',
'maintenance_mode': 'enable'}}
:return: Same dict as body but 'enable' strings for 'status' and
'maintenance_mode' are converted into True, else False.
:rtype: dict
"""
def read_enabled(orig_val):
# Convert enable/disable str to a bool.
val = orig_val.strip().lower()
return val == "enable"
context = req.environ['nova.context']
context.can(hosts_policies.POLICY_NAME % 'update',
target={})
# See what the user wants to 'update'
status = body.get('status')
maint_mode = body.get('maintenance_mode')
if status is not None:
status = read_enabled(status)
if maint_mode is not None:
maint_mode = read_enabled(maint_mode)
# Make the calls and merge the results
result = {'host': id}
if status is not None:
result['status'] = self._set_enabled_status(context, id, status)
if maint_mode is not None:
result['maintenance_mode'] = self._set_host_maintenance(context,
id,
maint_mode)
return result
def _set_host_maintenance(self, context, host_name, mode=True):
"""Start/Stop host maintenance window. On start, it triggers
guest VMs evacuation.
"""
LOG.info("Putting host %(host_name)s in maintenance mode %(mode)s.",
{'host_name': host_name, 'mode': mode})
try:
result = self.api.set_host_maintenance(context, host_name, mode)
except NotImplementedError:
common.raise_feature_not_supported()
except (exception.HostNotFound, exception.HostMappingNotFound) as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
except exception.ComputeServiceUnavailable as e:
raise webob.exc.HTTPBadRequest(explanation=e.format_message())
if result not in ("on_maintenance", "off_maintenance"):
raise webob.exc.HTTPBadRequest(explanation=result)
return result
def _set_enabled_status(self, context, host_name, enabled):
"""Sets the specified host's ability to accept new instances.
:param enabled: a boolean - if False no new VMs will be able to start
on the host.
"""
if enabled:
LOG.info("Enabling host %s.", host_name)
else:
LOG.info("Disabling host %s.", host_name)
try:
result = self.api.set_host_enabled(context, host_name, enabled)
except NotImplementedError:
common.raise_feature_not_supported()
except (exception.HostNotFound, exception.HostMappingNotFound) as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
except exception.ComputeServiceUnavailable as e:
raise webob.exc.HTTPBadRequest(explanation=e.format_message())
if result not in ("enabled", "disabled"):
raise webob.exc.HTTPBadRequest(explanation=result)
return result
def _host_power_action(self, req, host_name, action):
"""Reboots, shuts down or powers up the host."""
context = req.environ['nova.context']
try:
result = self.api.host_power_action(context, host_name, action)
except NotImplementedError:
common.raise_feature_not_supported()
except (exception.HostNotFound, exception.HostMappingNotFound) as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
except exception.ComputeServiceUnavailable as e:
raise webob.exc.HTTPBadRequest(explanation=e.format_message())
return {"host": host_name, "power_action": result}
@wsgi.Controller.api_version("2.1", "2.42")
@wsgi.expected_errors((400, 404, 501))
def startup(self, req, id):
context = req.environ['nova.context']
context.can(hosts_policies.POLICY_NAME % 'start',
target={})
return self._host_power_action(req, host_name=id, action="startup")
@wsgi.Controller.api_version("2.1", "2.42")
@wsgi.expected_errors((400, 404, 501))
def shutdown(self, req, id):
context = req.environ['nova.context']
context.can(hosts_policies.POLICY_NAME % 'shutdown',
target={})
return self._host_power_action(req, host_name=id, action="shutdown")
@wsgi.Controller.api_version("2.1", "2.42")
@wsgi.expected_errors((400, 404, 501))
def reboot(self, req, id):
context = req.environ['nova.context']
context.can(hosts_policies.POLICY_NAME % 'reboot',
target={})
return self._host_power_action(req, host_name=id, action="reboot")
@staticmethod
def _get_total_resources(host_name, compute_node):
return {'resource': {'host': host_name,
'project': '(total)',
'cpu': compute_node.vcpus,
'memory_mb': compute_node.memory_mb,
'disk_gb': compute_node.local_gb}}
@staticmethod
def _get_used_now_resources(host_name, compute_node):
return {'resource': {'host': host_name,
'project': '(used_now)',
'cpu': compute_node.vcpus_used,
'memory_mb': compute_node.memory_mb_used,
'disk_gb': compute_node.local_gb_used}}
@staticmethod
def _get_resource_totals_from_instances(host_name, instances):
cpu_sum = 0
mem_sum = 0
hdd_sum = 0
for instance in instances:
cpu_sum += instance['vcpus']
mem_sum += instance['memory_mb']
hdd_sum += instance['root_gb'] + instance['ephemeral_gb']
return {'resource': {'host': host_name,
'project': '(used_max)',
'cpu': cpu_sum,
'memory_mb': mem_sum,
'disk_gb': hdd_sum}}
@staticmethod
def _get_resources_by_project(host_name, instances):
# Getting usage resource per project
project_map = {}
for instance in instances:
resource = project_map.setdefault(instance['project_id'],
{'host': host_name,
'project': instance['project_id'],
'cpu': 0,
'memory_mb': 0,
'disk_gb': 0})
resource['cpu'] += instance['vcpus']
resource['memory_mb'] += instance['memory_mb']
resource['disk_gb'] += (instance['root_gb'] +
instance['ephemeral_gb'])
return project_map
@wsgi.Controller.api_version("2.1", "2.42")
@wsgi.expected_errors(404)
def show(self, req, id):
"""Shows the physical/usage resource given by hosts.
:param id: hostname
:returns: expected to use HostShowTemplate.
ex.::
{'host': {'resource':D},..}
D: {'host': 'hostname','project': 'admin',
'cpu': 1, 'memory_mb': 2048, 'disk_gb': 30}
"""
context = req.environ['nova.context']
context.can(hosts_policies.POLICY_NAME % 'show',
target={})
host_name = id
try:
mapping = objects.HostMapping.get_by_host(context, host_name)
nova_context.set_target_cell(context, mapping.cell_mapping)
compute_node = (
objects.ComputeNode.get_first_node_by_host_for_old_compat(
context, host_name))
instances = self.api.instance_get_all_by_host(context, host_name)
except (exception.ComputeHostNotFound,
exception.HostMappingNotFound) as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
resources = [self._get_total_resources(host_name, compute_node)]
resources.append(self._get_used_now_resources(host_name,
compute_node))
resources.append(self._get_resource_totals_from_instances(host_name,
instances))
by_proj_resources = self._get_resources_by_project(host_name,
instances)
for resource in by_proj_resources.values():
resources.append({'resource': resource})
return {'host': resources}