Release a new 'fuel2 role *' commands

Releases a new 'fuel2 role *' commands
(list, download, update, create, delete)
instead deprecated ones in old cli:

  fuel2 role list
  fuel2 role download
  fuel2 role update
  fuel2 role create
  fuel2 role delete

DocImpact

Change-Id: I2a3a284fa3363097b3b8c8ba8afeb54ce79dcd5c
This commit is contained in:
tivaliy 2016-08-25 13:39:51 +03:00
parent b1320a100a
commit 012447925f
10 changed files with 606 additions and 0 deletions

View File

@ -72,6 +72,7 @@ def get_client(resource, version='v1', connection=None):
'openstack-config': v1.openstack_config,
'plugins': v1.plugins,
'release': v1.release,
'role': v1.role,
'snapshot': v1.snapshot,
'task': v1.task,
'vip': v1.vip

221
fuelclient/commands/role.py Normal file
View File

@ -0,0 +1,221 @@
# -*- coding: utf-8 -*-
#
# Copyright 2016 Vitalii Kulanov
#
# 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.
import abc
import os
from oslo_utils import fileutils
import six
from fuelclient.cli import error
from fuelclient.commands import base
from fuelclient.common import data_utils
class RoleMixIn(object):
entity_name = 'role'
supported_file_formats = ('json', 'yaml')
@staticmethod
def get_file_path(directory, release_id, role_name, file_format):
return os.path.join(os.path.abspath(directory),
'release_{id}'.format(id=release_id),
'{}.{}'.format(role_name, file_format))
@six.add_metaclass(abc.ABCMeta)
class BaseUploadCommand(RoleMixIn, base.BaseCommand):
"""Base class for uploading metadata of a role."""
@abc.abstractproperty
def action(self):
"""String with the name of the action."""
pass
@abc.abstractproperty
def uploader(self):
"""Callable for uploading data."""
pass
def get_parser(self, prog_name):
parser = super(BaseUploadCommand, self).get_parser(prog_name)
parser.add_argument('-r',
'--release',
type=int,
required=True,
help='Id of the release')
parser.add_argument('-n',
'--name',
required=True,
help='Name of role.')
parser.add_argument('-f',
'--format',
required=True,
choices=self.supported_file_formats,
help='Format of serialized role description.')
parser.add_argument('-d',
'--directory',
required=False,
default=os.path.curdir,
help='Source directory. Defaults to '
'the current directory.')
return parser
def take_action(self, parsed_args):
params = {"release_id": parsed_args.release,
"role_name": parsed_args.name}
file_path = self.get_file_path(parsed_args.directory,
parsed_args.release,
parsed_args.name,
parsed_args.format)
try:
with open(file_path, 'r') as stream:
data = data_utils.safe_load(parsed_args.format, stream)
self.uploader(data, **params)
except (OSError, IOError):
msg = "Could not read description for role '{}' at {}".format(
parsed_args.name, file_path)
raise error.InvalidFileException(msg)
msg = ("Description of role '{role}' for release with id {id} was "
"{action}d from {file_path}\n".format(role=parsed_args.name,
id=parsed_args.release,
action=self.action,
file_path=file_path))
self.app.stdout.write(msg)
class RoleList(RoleMixIn, base.BaseListCommand):
"""Show list of all available roles for release."""
columns = ("name",
"group",
"conflicts",
"description")
def get_parser(self, prog_name):
parser = super(RoleList, self).get_parser(prog_name)
parser.add_argument('-r',
'--release',
type=int,
required=True,
help='Id of the release')
return parser
def take_action(self, parsed_args):
data = self.client.get_all(parsed_args.release)
data = data_utils.get_display_data_multi(self.columns, data)
return self.columns, data
class RoleDownload(RoleMixIn, base.BaseCommand):
"""Download full role description to file."""
def get_parser(self, prog_name):
parser = super(RoleDownload, self).get_parser(prog_name)
parser.add_argument('-r',
'--release',
type=int,
required=True,
help='Id of the release')
parser.add_argument('-n',
'--name',
required=True,
help='Name of role.')
parser.add_argument('-f',
'--format',
required=True,
choices=self.supported_file_formats,
help='Format of serialized role description.')
parser.add_argument('-d',
'--directory',
required=False,
default=os.path.curdir,
help='Destination directory. Defaults to '
'the current directory.')
return parser
def take_action(self, parsed_args):
file_path = self.get_file_path(parsed_args.directory,
parsed_args.release,
parsed_args.name,
parsed_args.format)
data = self.client.get_one(parsed_args.release, parsed_args.name)
try:
fileutils.ensure_tree(os.path.dirname(file_path))
fileutils.delete_if_exists(file_path)
with open(file_path, 'w') as stream:
data_utils.safe_dump(parsed_args.format, stream, data)
except (OSError, IOError):
msg = ("Could not store description data "
"for role {} at {}".format(parsed_args.name, file_path))
raise error.InvalidFileException(msg)
msg = ("Description data of role '{}' within release id {} "
"was stored in {}\n".format(parsed_args.name,
parsed_args.release,
file_path))
self.app.stdout.write(msg)
class RoleUpdate(BaseUploadCommand):
"""Update a role from file description."""
action = "update"
@property
def uploader(self):
return self.client.update
class RoleCreate(BaseUploadCommand):
"""Create a role from file description"""
action = "create"
@property
def uploader(self):
return self.client.create
class RoleDelete(RoleMixIn, base.BaseCommand):
"""Delete a role from release"""
def get_parser(self, prog_name):
parser = super(RoleDelete, self).get_parser(prog_name)
parser.add_argument('-r',
'--release',
type=int,
required=True,
help='Id of the release')
parser.add_argument('-n',
'--name',
required=True,
help='Name of role.')
return parser
def take_action(self, parsed_args):
self.client.delete(parsed_args.release, parsed_args.name)
msg = "Role '{}' was deleted from release with id {}\n".format(
parsed_args.name, parsed_args.release)
self.app.stdout.write(msg)

View File

@ -22,6 +22,7 @@ from fuelclient.objects.node import Node
from fuelclient.objects.node import NodeCollection
from fuelclient.objects.openstack_config import OpenstackConfig
from fuelclient.objects.release import Release
from fuelclient.objects.role import Role
from fuelclient.objects.task import DeployTask
from fuelclient.objects.task import SnapshotTask
from fuelclient.objects.task import Task

View File

@ -0,0 +1,170 @@
# -*- coding: utf-8 -*-
#
# Copyright 2016 Vitalii Kulanov
#
# 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.
import json
import mock
import yaml
from fuelclient.tests.unit.v2.cli import test_engine
from fuelclient.tests.utils import fake_role
class TestRoleCommand(test_engine.BaseCLITest):
"""Tests for fuel2 role * commands."""
def test_role_list_for_release(self):
self.m_client.get_all.return_value = [
{"name": "fake_role_1",
"group": "fake_group",
"conflicts": ["fake_role_2", "fake_role_3"],
"description": "some fake description"},
{"name": "fake_role_2",
"group": "fake_group",
"conflicts": ["fake_role_1", "fake_role_3"],
"description": "some fake description"}
]
release_id = 45
args = 'role list -r {id}'.format(id=release_id)
self.exec_command(args)
self.m_client.get_all.assert_called_once_with(release_id)
self.m_get_client.assert_called_once_with('role', mock.ANY)
@mock.patch('sys.stderr')
def test_role_list_for_release_fail(self, mocked_stderr):
args = 'role list'
self.assertRaises(SystemExit, self.exec_command, args)
self.assertIn('-r/--release',
mocked_stderr.write.call_args_list[-1][0][0])
@mock.patch('json.dump')
def test_role_download_json(self, m_dump):
release_id = 45
role_name = 'fake_role'
test_data = fake_role.get_fake_role(fake_role)
args = 'role download -r {} -n {} -f json -d /tmp'.format(release_id,
role_name)
expected_path = '/tmp/release_{id}/{name}.json'.format(id=release_id,
name=role_name)
self.m_client.get_one.return_value = test_data
m_open = mock.mock_open()
with mock.patch('fuelclient.commands.role.open', m_open, create=True):
self.exec_command(args)
m_open.assert_called_once_with(expected_path, 'w')
m_dump.assert_called_once_with(test_data, mock.ANY, indent=4)
self.m_get_client.assert_called_once_with('role', mock.ANY)
self.m_client.get_one.assert_called_once_with(release_id, role_name)
@mock.patch('yaml.safe_dump')
def test_role_download_yaml(self, m_safe_dump):
release_id = 45
role_name = 'fake_role'
test_data = fake_role.get_fake_role(fake_role)
args = 'role download -r {} -n {} -f yaml -d /tmp'.format(release_id,
role_name)
expected_path = '/tmp/release_{id}/{name}.yaml'.format(id=release_id,
name=role_name)
self.m_client.get_one.return_value = test_data
m_open = mock.mock_open()
with mock.patch('fuelclient.commands.role.open', m_open, create=True):
self.exec_command(args)
m_open.assert_called_once_with(expected_path, 'w')
m_safe_dump.assert_called_once_with(test_data, mock.ANY,
default_flow_style=False)
self.m_get_client.assert_called_once_with('role', mock.ANY)
self.m_client.get_one.assert_called_once_with(release_id, role_name)
def test_role_update_json(self):
release_id = 45
role_name = 'fake_role'
params = {"release_id": release_id, "role_name": role_name}
args = 'role update -r {} -n {} -f json -d /tmp'.format(release_id,
role_name)
test_data = fake_role.get_fake_role(role_name)
expected_path = '/tmp/release_{}/fake_role.json'.format(release_id)
m_open = mock.mock_open(read_data=json.dumps(test_data))
with mock.patch('fuelclient.commands.role.open', m_open, create=True):
self.exec_command(args)
m_open.assert_called_once_with(expected_path, 'r')
self.m_get_client.assert_called_once_with('role', mock.ANY)
self.m_client.update.assert_called_once_with(test_data, **params)
def test_role_update_yaml(self):
release_id = 45
role_name = 'fake_role'
params = {"release_id": release_id, "role_name": role_name}
args = 'role update -r {} -n {} -f yaml -d /tmp'.format(release_id,
role_name)
test_data = fake_role.get_fake_role(role_name)
expected_path = '/tmp/release_{}/fake_role.yaml'.format(release_id)
m_open = mock.mock_open(read_data=yaml.safe_dump(test_data))
with mock.patch('fuelclient.commands.role.open', m_open, create=True):
self.exec_command(args)
m_open.assert_called_once_with(expected_path, 'r')
self.m_get_client.assert_called_once_with('role', mock.ANY)
self.m_client.update.assert_called_once_with(test_data, **params)
def test_role_create_json(self):
release_id = 45
role_name = 'fake_role'
params = {"release_id": release_id, "role_name": role_name}
args = 'role create -r {} -n {} -f json -d /tmp'.format(release_id,
role_name)
test_data = fake_role.get_fake_role(role_name)
expected_path = '/tmp/release_{}/fake_role.json'.format(release_id)
m_open = mock.mock_open(read_data=json.dumps(test_data))
with mock.patch('fuelclient.commands.role.open', m_open, create=True):
self.exec_command(args)
m_open.assert_called_once_with(expected_path, 'r')
self.m_get_client.assert_called_once_with('role', mock.ANY)
self.m_client.create.assert_called_once_with(test_data, **params)
def test_role_create_yaml(self):
release_id = 45
role_name = 'fake_role'
params = {"release_id": release_id, "role_name": role_name}
args = 'role create -r {} -n {} -f yaml -d /tmp'.format(release_id,
role_name)
test_data = fake_role.get_fake_role(role_name)
expected_path = '/tmp/release_{}/fake_role.yaml'.format(release_id)
m_open = mock.mock_open(read_data=yaml.safe_dump(test_data))
with mock.patch('fuelclient.commands.role.open', m_open, create=True):
self.exec_command(args)
m_open.assert_called_once_with(expected_path, 'r')
self.m_get_client.assert_called_once_with('role', mock.ANY)
self.m_client.create.assert_called_once_with(test_data, **params)
def test_role_delete(self):
release_id = 45
role_name = 'fake_role'
args = 'role delete -r {} -n {}'.format(release_id, role_name)
self.exec_command(args)
self.m_get_client.assert_called_once_with('role', mock.ANY)
self.m_client.delete.assert_called_once_with(release_id, role_name)

View File

@ -0,0 +1,91 @@
# -*- coding: utf-8 -*-
#
# Copyright 2016 Vitalii Kulanov
#
# 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.
import fuelclient
from fuelclient.tests.unit.v2.lib import test_api
from fuelclient.tests import utils
class TestRoleFacade(test_api.BaseLibTest):
def setUp(self):
super(TestRoleFacade, self).setUp()
self.version = 'v1'
self.res_uri = '/api/{version}/releases/'.format(
version=self.version)
self.role_name = 'fake_role'
self.fake_role = utils.get_fake_role(self.role_name)
self.fake_roles = utils.get_fake_roles(10)
self.client = fuelclient.get_client('role', self.version)
def test_role_list(self):
release_id = 42
expected_uri = self.get_object_uri(self.res_uri, release_id, '/roles/')
matcher = self.m_request.get(expected_uri, json=self.fake_roles)
self.client.get_all(release_id)
self.assertTrue(matcher.called)
def test_role_download(self):
release_id = 45
expected_uri = self.get_object_uri(self.res_uri,
release_id,
'/roles/{}/'.format(self.role_name))
role_matcher = self.m_request.get(expected_uri, json=self.fake_role)
role = self.client.get_one(release_id, self.role_name)
self.assertTrue(expected_uri, role_matcher.called)
self.assertEqual(role, self.fake_role)
def test_role_update(self):
release_id = 45
params = {"release_id": release_id, "role_name": self.role_name}
expected_uri = self.get_object_uri(self.res_uri,
release_id,
'/roles/{}/'.format(self.role_name))
upd_matcher = self.m_request.put(expected_uri, json=self.fake_role)
self.client.update(self.fake_role, **params)
self.assertTrue(upd_matcher.called)
self.assertEqual(self.fake_role, upd_matcher.last_request.json())
def test_role_create(self):
release_id = 45
params = {"release_id": release_id}
expected_uri = self.get_object_uri(self.res_uri,
release_id,
'/roles/'.format(self.role_name))
post_matcher = self.m_request.post(expected_uri, json=self.fake_role)
self.client.create(self.fake_role, **params)
self.assertTrue(post_matcher.called)
self.assertEqual(self.fake_role, post_matcher.last_request.json())
def test_role_delete(self):
release_id = 45
expected_uri = self.get_object_uri(self.res_uri,
release_id,
'/roles/{}/'.format(self.role_name))
delete_matcher = self.m_request.delete(expected_uri, json={})
self.client.delete(release_id, self.role_name)
self.assertTrue(delete_matcher.called)

View File

@ -45,6 +45,8 @@ from fuelclient.tests.utils.fake_release import get_fake_releases
from fuelclient.tests.utils.fake_release import get_fake_attributes_metadata
from fuelclient.tests.utils.fake_release import get_fake_release_component
from fuelclient.tests.utils.fake_release import get_fake_release_components
from fuelclient.tests.utils.fake_role import get_fake_role
from fuelclient.tests.utils.fake_role import get_fake_roles
__all__ = (get_fake_deployment_history,
@ -59,6 +61,8 @@ __all__ = (get_fake_deployment_history,
get_fake_attributes_metadata,
get_fake_release_component,
get_fake_release_components,
get_fake_role,
get_fake_roles,
get_fake_fuel_version,
get_fake_interface_config,
get_fake_network_group,

View File

@ -0,0 +1,51 @@
# -*- coding: utf-8 -*-
#
# Copyright 2016 Vitalii Kulanov
#
# 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.
def get_fake_role(name=None, meta=None, volumes_roles_mapping=None):
"""Create a random fake role
Returns the serialized and parametrized representation of a dumped Fuel
role. Represents the average amount of data.
"""
return {
"name": name or "controller",
"meta": meta or {
"group": "base",
"name": "Controller",
"conflicts": ["compute", "ceph-osd"],
"description": "The Controller initiates orchestration activities "
"and provides an external API. Other components "
"like Glance (image storage), Keystone (identity "
"management), Horizon (OpenStack dashboard) and "
"Nova-Scheduler are installed on the controller "
"as well."
},
"volumes_roles_mapping": volumes_roles_mapping or [
{"id": "os", "allocate_size": "min"},
{"id": "logs", "allocate_size": "min"},
{"id": "image", "allocate_size": "all"},
{"id": "mysql", "allocate_size": "min"},
{"id": "horizon", "allocate_size": "min"}
]
}
def get_fake_roles(role_count, **kwargs):
"""Create a random fake list of roles."""
return [get_fake_role(**kwargs)
for _ in range(role_count)]

View File

@ -23,6 +23,7 @@ from fuelclient.v1 import network_group
from fuelclient.v1 import node
from fuelclient.v1 import openstack_config
from fuelclient.v1 import release
from fuelclient.v1 import role
from fuelclient.v1 import plugins
from fuelclient.v1 import snapshot
from fuelclient.v1 import task
@ -41,6 +42,7 @@ __all__ = ('cluster_settings',
'openstack_config',
'plugins',
'release',
'role',
'snapshot',
'task',
'vip')

60
fuelclient/v1/role.py Normal file
View File

@ -0,0 +1,60 @@
# -*- coding: utf-8 -*-
#
# Copyright 2016 Vitalii Kulanov
#
# 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 fuelclient import objects
from fuelclient.v1 import base_v1
class RoleClient(base_v1.BaseV1Client):
_entity_wrapper = objects.Role
def get_all(self, release_id):
"""Get all available roles for specific release.
:param release_id: Id of release
:type release_id: int
:return: roles data as a list of dict
:rtype: list
"""
data = self._entity_wrapper.get_all(release_id=release_id)
# Retrieve nested data from 'meta' and add it as a new key-value pair
for role in data:
role_meta = role.pop('meta')
role['group'] = role_meta.get('group')
role['conflicts'] = role_meta.get('conflicts')
role['description'] = role_meta.get('description')
return data
def get_one(self, release_id, role_name):
return self._entity_wrapper.get_one(release_id, role_name)
def update(self, data, **kwargs):
return self._entity_wrapper.update(kwargs['release_id'],
kwargs['role_name'],
data)
def create(self, data, **kwargs):
return self._entity_wrapper.create(kwargs['release_id'], data)
def delete(self, release_id, role_name):
return self._entity_wrapper.delete(release_id, role_name)
def get_client(connection):
return RoleClient(connection)

View File

@ -97,6 +97,11 @@ fuelclient =
release_list=fuelclient.commands.release:ReleaseList
release_repos_list=fuelclient.commands.release:ReleaseReposList
release_repos_update=fuelclient.commands.release:ReleaseReposUpdate
role_create=fuelclient.commands.role:RoleCreate
role_delete=fuelclient.commands.role:RoleDelete
role_download=fuelclient.commands.role:RoleDownload
role_list=fuelclient.commands.role:RoleList
role_update=fuelclient.commands.role:RoleUpdate
task_delete=fuelclient.commands.task:TaskDelete
task_deployment-info_download=fuelclient.commands.task:TaskDeploymentInfoDownload
task_history_show=fuelclient.commands.task:TaskHistoryShow