OpenStack Mitaka Nova API 接口扩展之instance

时间:2022-06-01 12:51:52

# Mitaka NOVA API 接口开发

背景: OpenStack官方默认Resize接口支持local storage 不是很好,问题很多,因此重新定

制Resize接口,实现云主机套餐变更,比之前的接口提高了很多时间

### 配置 Resize 路由 vim /usr/lib/python2.7/site-packages/nova-13.1.0-py2.7.egg-info/entry_points.txt  [nova.api.v21.extensions]          instance_resize = nova.api.openstack.compute.instance_resize:InstanceResize     access_ips = nova.api.openstack.compute.access_ips:AccessIPs     admin_actions = nova.api.openstack.compute.admin_actions:AdminActions     admin_password = nova.api.openstack.compute.admin_password:AdminPassword     agents = nova.api.openstack.compute.agents:Agents     aggregates = nova.api.openstack.compute.aggregates:Aggregates     assisted_volume_snapshots = nova.api.openstack.compute.assisted_volume_snapshots:AssistedVolumeSnapshots     attach_interfaces = nova.api.openstack.compute.attach_interfaces:AttachInterfaces     availability_zone = nova.api.openstack.compute.availability_zone:AvailabilityZone     baremetal_nodes = nova.api.openstack.compute.baremetal_nodes:BareMetalNodes     block_device_mapping = nova.api.openstack.compute.block_device_mapping:BlockDeviceMapping     cells = nova.api.openstack.compute.cells:Cells     certificates = nova.api.openstack.compute.certificates:Certificates     cloudpipe = nova.api.openstack.compute.cloudpipe:Cloudpipe     config_drive = nova.api.openstack.compute.config_drive:ConfigDrive     console_auth_tokens = nova.api.openstack.compute.console_auth_tokens:ConsoleAuthTokens     console_output = nova.api.openstack.compute.console_output:ConsoleOutput

### 定制API 接口

* Mitaka 接口开发目录与Havana 版本发生变化,所有的接口放在nova/api/openstack/compute/目录中,在此目录中创建Resize 接口 

    # Copyright 2013 Rackspace Hosting     # 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     #     #              #     #    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.     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     #from nova.i18n import _     from oslo_log import log as logging     from nova.extend import api as extend_api     from nova import utils     LOG = logging.getLogger(__name__)     ALIAS = "os-instance-resize"     authorize = extensions.os_compute_authorizer(ALIAS)     class InstanceResizeController(wsgi.Controller):         def __init__(self):             #super(InstanceResizeController, self).__init__()             self.compute_api = compute.API(skip_policy_check=True)         @wsgi.Controller.api_version("2.1", "2.20")         def _get_instance(self, req, context, server_id):             return common.get_instance(self.compute_api, context, server_id)         @extensions.expected_errors(404)         def index(self,req):             """Returns the list of actions recorded for a given instance."""             context = req.environ["nova.context"]             LOG.info("index.dir %s" %context)             LOG.info("index.InstanceResizeController is ok")             return "True"         @extensions.expected_errors(404)         def create(self,req,body):             try:                 """Return data about the given instance action."""                 context = req.environ["nova.context"]                 flavor = body[‘flavor‘]                 instance_uuid  = body[‘instance_uuid‘]                 resize_api = extend_api.LocalAPI()                 result = resize_api.instance_resize(context,req,flavor,instance_uuid)                 #Reboot to instances                 body = {‘reboot‘: {‘type‘: ‘SOFT‘}}                 reboot_type = body[‘reboot‘][‘type‘].upper()                 instance = self._get_instance(req, context, instance_uuid)                 try:                     self.compute_api.reboot(context, instance, reboot_type)                 except exception.InstanceIsLocked as e:                     raise exc.HTTPConflict(explanation=e.format_message())                 except exception.InstanceInvalidState as state_error:                     common.raise_http_conflict_for_instance_invalid_state(state_error,                             ‘reboot‘, id)                 LOG.info("create.InstanceResizeController is ok %s.%s.%s" % (result,flavor,instance_uuid))                 return str(result )             except:                 return "False"                 LOG.error(traceback.format_exc())         @extensions.expected_errors(404)         def delete(self,req):             """Return data about the given instance action."""             LOG.info("delete.InstanceResizeController is ok")             return "True"         @extensions.expected_errors(404)         def update(self,req):             """Return data about the given instance action."""             LOG.info("update.InstanceResizeController is ok")             return "True"         @extensions.expected_errors(404)         def show(self,req):             """Return data about the given instance action."""             LOG.info("show.InstanceResizeController is ok")             return "True"     class InstanceResize(extensions.V21APIExtensionBase):         """View a log of actions and events taken on an instance."""         name = "InstanceResize"         alias = ALIAS         version = 1         def get_resources(self):             ext = extensions.ResourceExtension(ALIAS,                                                InstanceResizeController(),)             return [ext]         def get_controller_extensions(self):             """It‘s an abstract function V21APIExtensionBase and the extension             will not be loaded without it.             """             return []