怎样写 OpenStack Neutron 的 Extension (四)

上文说到需要在 /neutronclient/v2_0/myextension/extension.py 中分别定义五个 class:List/Show/Create/Delete/UpdateExtension。具体形式如下:

import argparse
import logging

from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _

RESOURCE = 'myextension'
class ListExtension(neutronV20.ListCommand): """List extensions""" resource = RESOURCE log = logging.getLogger(__name__ + '.ListExtension') list_columns = ['id', 'name'] class ShowExtension(neutronV20.ShowCommand): """Show information of a given extension.""" resource = RESOURCE log = logging.getLogger(__name__ + '.ShowExtension') class CreatePhysicalGateway(neutronV20.CreateCommand): """Create an extension.""" resource = RESOURCE log = logging.getLogger(__name__ + '.CreateExtension') def add_known_arguments(self, parser): parser.add_argument( 'name', metavar='NAME', help=_('Name of extension to create')) def args2body(self, parsed_args): body = {self.resource: { 'name': parsed_args.name}} return body

class UpdateExtension(neutronV20.UpdateCommand):
    """update a given extension."""

    resource = RESOURCE
    log = logging.getLogger(__name__ + '.UpdateExtension')      
class DeleteExtension(neutronV20.DeleteCommand):
    """Delete a given extension."""

    resource = RESOURCE
    log = logging.getLogger(__name__ + '.DeleteExtension')       

这些 class 处在接受 CLI 命令的第一线,负责将命令转化成 API call。需要特别注意的是 CreateExtension 这个类,它有两个方法 add_known_arguments 和 args2body。前者定义了 CLI 命令接受哪些参数,后者规定如何将收到的参数打包起来。

这些参数打包之后就会发给 neutron 后台中我们自己定义的 plugin controller,但是如何发送这些参数还需要我们去 /neutronclient/v2_0/client.py 的 Client 类中设置:

首先是 uri 路径:

    myextensions_path = "/myextensions"
    myextension_path = "/myextensions/%s"

然后是每个操作所对应的传递方法:

   @APIParamsCall
    def list_myextensions(self, retrieve_all=True, **_params):
        """Fetches a list of all myextensions for a tenant."""
        return self.list('myextensions', self.myextensions_path, retrieve_all,
                         **_params)
                         
    @APIParamsCall
    def show_myextension(self, myextension, **_params):
        """Fetches information of a certain entry in myextension."""
        return self.get(self.myextension_path % (myextension), params=_params)
        
    @APIParamsCall
    def create_myextension(self, body=None):
        """Creates a new myextension entry."""
        return self.post(self.myextensions_path, body=body)
        
    @APIParamsCall
    def delete_myextension(self, myextension):
        """Deletes the specified myextension."""
        return self.delete(self.myextension_path % (myextension))

   @APIParamsCall
    def update_myextension(self, myextension, body=None):
        """Updates a myextension."""
        return self.put(self.myextension_path % (myextension), body=body)

如此一来,我们自己实现的 neutron plugin 就能够收到 CLI 发送过来的命令啦。

下一章再来说说怎么修改 OpenStack 的 Dashboard 来显示我们在 extension 中添加的新元素。

posted @ 2014-08-21 05:46  云耳  阅读(2238)  评论(5编辑  收藏  举报