Use common get_instance call in API plugins

Cleanup API to use common get_instance call which
automatically does exception handling. Not all cases
are handled in this patch as some require more
significant testcase rework and are done in future
patches to make it easier to review.

Change-Id: Id27350e6562636f81347b490db649744b6b41186
This commit is contained in:
Chris Yeoh
2014-10-28 11:23:14 +10:30
parent 43094a98e0
commit 90d5308a94
17 changed files with 67 additions and 109 deletions

View File

@@ -18,6 +18,7 @@ import re
import webob
from nova.api.openstack import common
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova import compute
@@ -39,13 +40,8 @@ class ConsoleOutputController(wsgi.Controller):
context = req.environ['nova.context']
authorize(context)
try:
instance = self.compute_api.get(context, id,
want_objects=True)
except exception.NotFound:
msg = _('Instance not found')
raise webob.exc.HTTPNotFound(explanation=msg)
instance = common.get_instance(self.compute_api, context, id,
want_objects=True)
try:
length = body['os-getConsoleOutput'].get('length')
except (TypeError, KeyError):

View File

@@ -115,8 +115,9 @@ class ConsolesController(wsgi.Controller):
# If type is not supplied or unknown get_serial_console below will cope
console_type = body['os-getSerialConsole'].get('type')
instance = common.get_instance(self.compute_api, context, id,
want_objects=True)
try:
instance = self.compute_api.get(context, id, want_objects=True)
output = self.compute_api.get_serial_console(context,
instance,
console_type)

View File

@@ -80,8 +80,9 @@ class Controller(wsgi.Controller):
msg = _("Compute host %s not found.") % host
raise exc.HTTPNotFound(explanation=msg)
instance = common.get_instance(self.compute_api, context, id,
want_objects=True)
try:
instance = self.compute_api.get(context, id, want_objects=True)
if instance.host == host:
msg = _("The target host can't be the same one.")
raise exc.HTTPBadRequest(explanation=msg)

View File

@@ -86,7 +86,7 @@ def get_instance_by_floating_ip_addr(self, context, address):
snagiibfa = self.network_api.get_instance_id_by_floating_address
instance_id = snagiibfa(context, address)
if instance_id:
return self.compute_api.get(context, instance_id)
return common.get_instance(self.compute_api, context, instance_id)
def disassociate_floating_ip(self, context, instance, address):

View File

@@ -123,23 +123,25 @@ class FpingController(object):
return {"servers": res}
def show(self, req, id):
context = req.environ["nova.context"]
authorize(context)
self.check_fping()
instance = common.get_instance(self.compute_api, context, id)
try:
context = req.environ["nova.context"]
authorize(context)
self.check_fping()
instance = self.compute_api.get(context, id)
ips = [str(ip) for ip in self._get_instance_ips(context, instance)]
alive_ips = self.fping(ips)
return {
"server": {
"id": instance["uuid"],
"project_id": instance["project_id"],
"alive": bool(set(ips) & alive_ips),
}
}
except exception.NotFound:
raise exc.HTTPNotFound()
alive_ips = self.fping(ips)
return {
"server": {
"id": instance["uuid"],
"project_id": instance["project_id"],
"alive": bool(set(ips) & alive_ips),
}
}
class Fping(extensions.ExtensionDescriptor):
"""Fping Management Extension."""

View File

@@ -18,6 +18,7 @@
import webob
from webob import exc
from nova.api.openstack import common
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova import compute
@@ -36,14 +37,6 @@ class MultinicController(wsgi.Controller):
super(MultinicController, self).__init__(*args, **kwargs)
self.compute_api = compute.API()
def _get_instance(self, context, instance_id, want_objects=False):
try:
return self.compute_api.get(context, instance_id,
want_objects=want_objects)
except exception.InstanceNotFound:
msg = _("Server not found")
raise exc.HTTPNotFound(explanation=msg)
@wsgi.action('addFixedIp')
def _add_fixed_ip(self, req, id, body):
"""Adds an IP on a given network to an instance."""
@@ -55,7 +48,8 @@ class MultinicController(wsgi.Controller):
msg = _("Missing 'networkId' argument for addFixedIp")
raise exc.HTTPBadRequest(explanation=msg)
instance = self._get_instance(context, id, want_objects=True)
instance = common.get_instance(self.compute_api, context, id,
want_objects=True)
network_id = body['addFixedIp']['networkId']
try:
self.compute_api.add_fixed_ip(context, instance, network_id)
@@ -75,8 +69,8 @@ class MultinicController(wsgi.Controller):
msg = _("Missing 'address' argument for removeFixedIp")
raise exc.HTTPBadRequest(explanation=msg)
instance = self._get_instance(context, id,
want_objects=True)
instance = common.get_instance(self.compute_api, context, id,
want_objects=True)
address = body['removeFixedIp']['address']
try:

View File

@@ -23,7 +23,6 @@ from nova.api.openstack import extensions as exts
from nova.api.openstack import wsgi
from nova import compute
from nova import exception
from nova.i18n import _
from nova import utils
@@ -37,14 +36,6 @@ class RescueController(wsgi.Controller):
self.compute_api = compute.API()
self.ext_mgr = ext_mgr
def _get_instance(self, context, instance_id, want_objects=False):
try:
return self.compute_api.get(context, instance_id,
want_objects=want_objects)
except exception.InstanceNotFound:
msg = _("Server not found")
raise exc.HTTPNotFound(explanation=msg)
@wsgi.action('rescue')
def _rescue(self, req, id, body):
"""Rescue an instance."""
@@ -56,7 +47,8 @@ class RescueController(wsgi.Controller):
else:
password = utils.generate_password()
instance = self._get_instance(context, id, want_objects=True)
instance = common.get_instance(self.compute_api, context, id,
want_objects=True)
try:
rescue_image_ref = None
if self.ext_mgr.is_loaded("os-extended-rescue-with-image"):
@@ -82,7 +74,8 @@ class RescueController(wsgi.Controller):
"""Unrescue an instance."""
context = req.environ["nova.context"]
authorize(context)
instance = self._get_instance(context, id, want_objects=True)
instance = common.get_instance(self.compute_api, context, id,
want_objects=True)
try:
self.compute_api.unrescue(context, instance)
except exception.InstanceIsLocked as e:

View File

@@ -45,11 +45,9 @@ class ServerDiagnosticsController(object):
def index(self, req, server_id):
context = req.environ["nova.context"]
authorize(context)
try:
instance = self.compute_api.get(context, server_id,
want_objects=True)
except exception.InstanceNotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
instance = common.get_instance(self.compute_api, context, server_id,
want_objects=True)
try:
return self.compute_api.get_diagnostics(context, instance)

View File

@@ -15,14 +15,12 @@
"""The server password extension."""
import webob
from nova.api.metadata import password
from nova.api.openstack import common
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova import compute
from nova import exception
authorize = extensions.extension_authorizer('compute', 'server_password')
@@ -40,17 +38,12 @@ class ServerPasswordController(object):
def __init__(self):
self.compute_api = compute.API()
def _get_instance(self, context, server_id):
try:
return self.compute_api.get(context, server_id, want_objects=True)
except exception.InstanceNotFound as exp:
raise webob.exc.HTTPNotFound(explanation=exp.format_message())
@wsgi.serializers(xml=ServerPasswordTemplate)
def index(self, req, server_id):
context = req.environ['nova.context']
authorize(context)
instance = self._get_instance(context, server_id)
instance = common.get_instance(self.compute_api, context, server_id,
want_objects=True)
passw = password.extract_password(instance)
return {'password': passw or ''}
@@ -59,7 +52,8 @@ class ServerPasswordController(object):
def delete(self, req, server_id):
context = req.environ['nova.context']
authorize(context)
instance = self._get_instance(context, server_id)
instance = common.get_instance(self.compute_api, context, server_id,
want_objects=True)
meta = password.convert_password(context, None)
instance.system_metadata.update(meta)
instance.save()

View File

@@ -22,7 +22,6 @@ from nova.api.openstack import extensions as exts
from nova.api.openstack import wsgi
from nova import compute
from nova import exception
from nova.i18n import _
auth_shelve = exts.extension_authorizer('compute', 'shelve')
@@ -35,21 +34,14 @@ class ShelveController(wsgi.Controller):
super(ShelveController, self).__init__(*args, **kwargs)
self.compute_api = compute.API()
def _get_instance(self, context, instance_id):
try:
return self.compute_api.get(context, instance_id,
want_objects=True)
except exception.InstanceNotFound:
msg = _("Server not found")
raise exc.HTTPNotFound(explanation=msg)
@wsgi.action('shelve')
def _shelve(self, req, id, body):
"""Move an instance into shelved mode."""
context = req.environ["nova.context"]
auth_shelve(context)
instance = self._get_instance(context, id)
instance = common.get_instance(self.compute_api, context, id,
want_objects=True)
try:
self.compute_api.shelve(context, instance)
except exception.InstanceIsLocked as e:
@@ -66,7 +58,8 @@ class ShelveController(wsgi.Controller):
context = req.environ["nova.context"]
auth_shelve_offload(context)
instance = self._get_instance(context, id)
instance = common.get_instance(self.compute_api, context, id,
want_objects=True)
try:
self.compute_api.shelve_offload(context, instance)
except exception.InstanceIsLocked as e:
@@ -83,7 +76,8 @@ class ShelveController(wsgi.Controller):
"""Restore an instance from shelved mode."""
context = req.environ["nova.context"]
auth_unshelve(context)
instance = self._get_instance(context, id)
instance = common.get_instance(self.compute_api, context, id,
want_objects=True)
try:
self.compute_api.unshelve(context, instance)
except exception.InstanceIsLocked as e:

View File

@@ -351,11 +351,7 @@ class VolumeAttachmentController(wsgi.Controller):
authorize_attach(context, action='show')
volume_id = id
try:
instance = self.compute_api.get(context, server_id)
except exception.NotFound as e:
raise exc.HTTPNotFound(explanation=e.format_message())
instance = common.get_instance(self.compute_api, context, server_id)
bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
context, instance['uuid'])
@@ -411,9 +407,9 @@ class VolumeAttachmentController(wsgi.Controller):
'server_id': server_id},
context=context)
instance = common.get_instance(self.compute_api, context, server_id,
want_objects=True)
try:
instance = self.compute_api.get(context, server_id,
want_objects=True)
device = self.compute_api.attach_volume(context, instance,
volume_id, device)
except exception.NotFound as e:
@@ -465,11 +461,8 @@ class VolumeAttachmentController(wsgi.Controller):
self._validate_volume_id(new_volume_id)
new_volume = self.volume_api.get(context, new_volume_id)
try:
instance = self.compute_api.get(context, server_id,
want_objects=True)
except exception.NotFound as e:
raise exc.HTTPNotFound(explanation=e.format_message())
instance = common.get_instance(self.compute_api, context, server_id,
want_objects=True)
bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
context, instance.uuid)
@@ -508,11 +501,8 @@ class VolumeAttachmentController(wsgi.Controller):
volume_id = id
LOG.audit(_("Detach volume %s"), volume_id, context=context)
try:
instance = self.compute_api.get(context, server_id,
want_objects=True)
except exception.NotFound as e:
raise exc.HTTPNotFound(explanation=e.format_message())
instance = common.get_instance(self.compute_api, context, server_id,
want_objects=True)
volume = self.volume_api.get(context, volume_id)
@@ -555,10 +545,7 @@ class VolumeAttachmentController(wsgi.Controller):
context = req.environ['nova.context']
authorize(context)
try:
instance = self.compute_api.get(context, server_id)
except exception.NotFound as e:
raise exc.HTTPNotFound(explanation=e.format_message())
instance = common.get_instance(self.compute_api, context, server_id)
bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
context, instance['uuid'])

View File

@@ -60,25 +60,17 @@ class Controller(wsgi.Controller):
super(Controller, self).__init__(**kwargs)
self._compute_api = nova.compute.API()
def _get_instance(self, context, server_id):
try:
instance = self._compute_api.get(context, server_id)
except nova.exception.NotFound:
msg = _("Instance does not exist")
raise exc.HTTPNotFound(explanation=msg)
return instance
@wsgi.serializers(xml=AddressesTemplate)
def index(self, req, server_id):
context = req.environ["nova.context"]
instance = self._get_instance(context, server_id)
instance = common.get_instance(self._compute_api, context, server_id)
networks = common.get_networks_for_instance(context, instance)
return self._view_builder.index(networks)
@wsgi.serializers(xml=NetworkTemplate)
def show(self, req, server_id, id):
context = req.environ["nova.context"]
instance = self._get_instance(context, server_id)
instance = common.get_instance(self._compute_api, context, server_id)
networks = common.get_networks_for_instance(context, instance)
if id not in networks:
msg = _("Instance is not a member of specified network")

View File

@@ -177,9 +177,9 @@ class Controller(object):
msg = _("Metadata item was not found")
raise exc.HTTPNotFound(explanation=msg)
server = common.get_instance(self.compute_api, context, server_id,
want_objects=True)
try:
server = self.compute_api.get(context, server_id,
want_objects=True)
self.compute_api.delete_instance_metadata(context, server, id)
except exception.InstanceNotFound:

View File

@@ -15,6 +15,7 @@
import mock
from oslo.config import cfg
from nova.api.openstack import common
from nova.api.openstack.compute.contrib import rescue
from nova.api.openstack import extensions
from nova import compute
@@ -37,8 +38,11 @@ class ExtendedRescueWithImageTest(test.NoDBTestCase):
ext_mgr.extensions = {'os-extended-rescue-with-image': 'fake'}
self.controller = rescue.RescueController(ext_mgr)
@mock.patch.object(common, 'get_instance',
return_value="instance")
@mock.patch.object(compute.api.API, "rescue")
def _make_rescue_request_with_image_ref(self, body, mock_rescue):
def _make_rescue_request_with_image_ref(self, body, mock_rescue,
mock_get_instance):
instance = "instance"
self.controller._get_instance = mock.Mock(return_value=instance)
fake_context = context.RequestContext('fake', 'fake')

View File

@@ -32,7 +32,8 @@ def fake_get_diagnostics(self, _context, instance_uuid):
return {'data': 'Some diagnostic info'}
def fake_instance_get(self, _context, instance_uuid, want_objects=False):
def fake_instance_get(self, _context, instance_uuid, want_objects=False,
expected_attrs=None):
if instance_uuid != UUID:
raise Exception("Invalid UUID")
return {'uuid': instance_uuid}

View File

@@ -53,7 +53,8 @@ FAKE_UUID_D = 'dddddddd-dddd-dddd-dddd-dddddddddddd'
IMAGE_UUID = 'c905cedb-7281-47e4-8a62-f26bc5fc4c77'
def fake_get_instance(self, context, instance_id, want_objects=False):
def fake_get_instance(self, context, instance_id, want_objects=False,
expected_attrs=None):
return fake_instance.fake_instance_obj(context, **{'uuid': instance_id})

View File

@@ -3970,7 +3970,7 @@ class VolumeAttachmentsSampleBase(ServersSampleBase):
def _stub_compute_api_get(self):
def fake_compute_api_get(self, context, instance_id,
want_objects=False):
want_objects=False, expected_attrs=None):
if want_objects:
return fake_instance.fake_instance_obj(
context, **{'uuid': instance_id})