nova扩展API

增加文件 nova/api/openstack/compute/clusters.py

# Copyright (c) 2012 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 clusters admin extension."""

from oslo_log import log as logging

from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.policies import clusters as cl_policies
from ics_sdk import manager

LOG = logging.getLogger(__name__)

ALIAS = "clusters"


class ClustersController(wsgi.Controller):
    """The Clusters API controller for the OpenStack API."""

    def __init__(self):
        user = 'admin'
        passwd = 'admin@inspur'
        self.ics_manager = manager.Manager(user, passwd, 'https://100.2.30.85')
        super(ClustersController, self).__init__()

    @extensions.expected_errors(404)
    def hosts(self, req, id):
        context = req.environ['nova.context']
        context.can(cl_policies.BASE_POLICY_NAME)
        id = 'e4829ed55bb38924015bb38fc96b007b'
        ics_hosts = self.ics_manager.host.get_hosts_in_cluster(id)\
            .get('items')
        hosts = []
        keys = ['id', 'clusterId', 'clusterName', 'ip', 'totalcpu', 'cpuUsage',
                'totalMem', 'memoryUsage', 'pnicNum', 'status']
        for ics_host in ics_hosts:
            host = {}
            for k in keys:
                host[k] = ics_host.get(k)
            hosts.append(host)
        return dict(hosts=hosts)


class Clusters(extensions.V21APIExtensionBase):
    """Admin-only cluster administration."""

    name = "Clusters"
    alias = ALIAS
    version = 1

    def get_resources(self):
        m_actions = {'hosts': 'GET'}
        resources = [extensions.ResourceExtension(ALIAS, ClustersController(),
                                                  member_actions=m_actions)]

        return resources

    def get_controller_extensions(self):
        return []

修改文件 setup.cfg, 在nova.api.v21.extensions后面追加一行配置

clusters = nova.api.openstack.compute.clusters:Clusters

增加文件 nova/policies/clusters.py

# Copyright 2016 Cloudbase Solutions Srl
# 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.

from oslo_policy import policy

from nova.policies import base


BASE_POLICY_NAME = 'os_compute_api:clusters'
POLICY_ROOT = 'os_compute_api:clusters:%s'


clusters_policies = [
    policy.RuleDefault(
        name=POLICY_ROOT % 'discoverable',
        check_str=base.RULE_ANY),
    policy.RuleDefault(
        name=BASE_POLICY_NAME,
        check_str=base.RULE_ADMIN_API),
]


def list_rules():
    return clusters_policies

修改文件 nova/policies/__init__.py,增加导入

from nova.policies import clusters

修改list_rules方法,在return itertools.chain的参数列表中增加

clusters.list_rules(),

执行命令

python setup.py egg_info

重启 nova-api 进程

在novaclient中增加相关命令

增加文件 novaclient/v2/clusters.py

# Copyright 2012 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.

"""
Clusters interface (1.1 extension).
"""

from novaclient import base


class Cluster(base.Resource):
    NAME_ATTR = 'clusterName'

    def __repr__(self):
        return "<Cluster: %s>" % self.id


class ClusterManager(base.ManagerWithFind):
    resource_class = Cluster
    is_alphanum_id_allowed = True

    def list(self, detailed=True):
        return []

    def hosts(self, cluster):
        """
        Get hosts list for a specific cluster.
        """
        return self._list("/clusters/%s/hosts" % cluster, 'hosts')

修改文件 novaclient/v2/client.py,增加导入

from novaclient.v2 import clusters

在类 Client 的 __init__ 方法中增加实例变量

self.clusters = clusters.ClusterManager(self)

修改文件 novaclient/v2/shell.py,增加方法

@utils.arg(
    'cluster',
    metavar='<cluster>',
    help=_('Name or ID of the cluster to show hosts list of.'))
def do_cluster_hosts(cs, args): # 方法名决定命令行 nova cluster-hosts <cluster>
    """List hosts of the specified cluster."""
    # hyper = _find_cluster(cs, args.cluster)
    hyper = cs.clusters.hosts(args.cluster)

    # Output the hosts information
    cols = ['id', 'status', 'clusterName', 'cpuUsage', 'totalcpu', 'totalMem', 'memoryUsage', 'pnicNum', 'name']
    formatters = {}
    def fun(key):
        return lambda x: getattr(x, key, '')
    for i in cols:
        formatters[i] = fun(i)
    utils.print_list(hyper, cols, formatters=formatters)
    # 参数formatters针对那些带大写字母的key,详情参见print_list的实现逻辑

执行命令测试

nova cluster-hosts ics.e4829787878787887878007b
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值