OpenStackClient plugin for action plan

In this changeset, I implemented the 'actionplan' commands.

Partially Implements: blueprint openstackclient-plugin

Change-Id: I932321b75981a35a20abd749cfdbe793a52416d7
This commit is contained in:
Vincent Francoise 2016-04-29 12:19:40 +02:00
parent 3b79b58f68
commit 0260775f30
3 changed files with 499 additions and 0 deletions

@ -49,6 +49,12 @@ openstack.infra_optim.v1 =
optimize_audit_update = watcherclient.v1.osc.audit_shell:UpdateAudit
optimize_audit_delete = watcherclient.v1.osc.audit_shell:DeleteAudit
optimize_actionplan_show = watcherclient.v1.osc.action_plan_shell:ShowActionPlan
optimize_actionplan_list = watcherclient.v1.osc.action_plan_shell:ListActionPlan
optimize_actionplan_create = watcherclient.v1.osc.action_plan_shell:CreateActionPlan
optimize_actionplan_update = watcherclient.v1.osc.action_plan_shell:UpdateActionPlan
optimize_actionplan_start = watcherclient.v1.osc.action_plan_shell:StartActionPlan
# The same as above but used by the 'watcher' command
watcherclient.v1 =
goal_show = watcherclient.v1.osc.goal_shell:ShowGoal
@ -69,6 +75,13 @@ watcherclient.v1 =
audit_update = watcherclient.v1.osc.audit_shell:UpdateAudit
audit_delete = watcherclient.v1.osc.audit_shell:DeleteAudit
actionplan_show = watcherclient.v1.osc.action_plan_shell:ShowActionPlan
actionplan_list = watcherclient.v1.osc.action_plan_shell:ListActionPlan
actionplan_create = watcherclient.v1.osc.action_plan_shell:CreateActionPlan
actionplan_update = watcherclient.v1.osc.action_plan_shell:UpdateActionPlan
actionplan_start = watcherclient.v1.osc.action_plan_shell:StartActionPlan
actionplan_delete = watcherclient.v1.osc.action_plan_shell:DeleteActionPlan
[pbr]
autodoc_index_modules = True

@ -0,0 +1,241 @@
# -*- encoding: utf-8 -*-
# Copyright (c) 2016 b<>com
#
# 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 datetime
import mock
import six
from watcherclient import exceptions
from watcherclient.tests.v1.osc import base
from watcherclient import v1 as resource
from watcherclient.v1 import resource_fields
from watcherclient import watcher as shell
ACTION_PLAN_1 = {
'uuid': 'd9d9978e-6db5-4a05-8eab-1531795d7004',
'audit_uuid': '770ef053-ecb3-48b0-85b5-d55a2dbc6588',
'state': 'RECOMMENDED',
'created_at': datetime.datetime.now().isoformat(),
'updated_at': None,
'deleted_at': None,
}
ACTION_PLAN_2 = {
'uuid': 'd6363285-5afa-4a26-96f2-89441e335765',
'audit_uuid': '239f02a5-9649-4e14-9d33-ac2bf67cb755',
'state': 'RECOMMENDED',
'created_at': datetime.datetime.now().isoformat(),
'updated_at': None,
'deleted_at': None,
}
class ActionPlanShellTest(base.CommandTestCase):
SHORT_LIST_FIELDS = resource_fields.ACTION_PLAN_SHORT_LIST_FIELDS
SHORT_LIST_FIELD_LABELS = (
resource_fields.ACTION_PLAN_SHORT_LIST_FIELD_LABELS)
FIELDS = resource_fields.ACTION_PLAN_FIELDS
FIELD_LABELS = resource_fields.ACTION_PLAN_FIELD_LABELS
def setUp(self):
super(self.__class__, self).setUp()
p_audit_manager = mock.patch.object(resource, 'AuditManager')
p_audit_template_manager = mock.patch.object(
resource, 'ActionPlanManager')
p_action_plan_manager = mock.patch.object(
resource, 'ActionPlanManager')
self.m_audit_mgr_cls = p_audit_manager.start()
self.m_audit_template_mgr_cls = p_audit_template_manager.start()
self.m_action_plan_mgr_cls = p_action_plan_manager.start()
self.addCleanup(p_audit_manager.stop)
self.addCleanup(p_audit_template_manager.stop)
self.addCleanup(p_action_plan_manager.stop)
self.m_audit_mgr = mock.Mock()
self.m_audit_template_mgr = mock.Mock()
self.m_action_plan_mgr = mock.Mock()
self.m_audit_mgr_cls.return_value = self.m_audit_mgr
self.m_audit_template_mgr_cls.return_value = self.m_audit_template_mgr
self.m_action_plan_mgr_cls.return_value = self.m_action_plan_mgr
self.stdout = six.StringIO()
self.cmd = shell.WatcherShell(stdout=self.stdout)
def test_do_action_plan_list(self):
action_plan1 = resource.ActionPlan(mock.Mock(), ACTION_PLAN_1)
action_plan2 = resource.ActionPlan(mock.Mock(), ACTION_PLAN_2)
self.m_action_plan_mgr.list.return_value = [
action_plan1, action_plan2]
exit_code, results = self.run_cmd('actionplan list')
self.assertEqual(0, exit_code)
self.assertEqual(
[self.resource_as_dict(action_plan1, self.SHORT_LIST_FIELDS,
self.SHORT_LIST_FIELD_LABELS),
self.resource_as_dict(action_plan2, self.SHORT_LIST_FIELDS,
self.SHORT_LIST_FIELD_LABELS)],
results)
self.m_action_plan_mgr.list.assert_called_once_with(detail=False)
def test_do_action_plan_list_detail(self):
action_plan1 = resource.ActionPlan(mock.Mock(), ACTION_PLAN_1)
action_plan2 = resource.ActionPlan(mock.Mock(), ACTION_PLAN_2)
self.m_action_plan_mgr.list.return_value = [
action_plan1, action_plan2]
exit_code, results = self.run_cmd('actionplan list --detail')
self.assertEqual(0, exit_code)
self.assertEqual(
[self.resource_as_dict(action_plan1, self.FIELDS,
self.FIELD_LABELS),
self.resource_as_dict(action_plan2, self.FIELDS,
self.FIELD_LABELS)],
results)
self.m_action_plan_mgr.list.assert_called_once_with(detail=True)
def test_do_action_plan_list_filter_by_audit(self):
action_plan1 = resource.ActionPlan(mock.Mock(), ACTION_PLAN_1)
self.m_action_plan_mgr.list.return_value = [action_plan1]
exit_code, results = self.run_cmd(
'actionplan list --audit '
'770ef053-ecb3-48b0-85b5-d55a2dbc6588')
self.assertEqual(0, exit_code)
self.assertEqual(
[self.resource_as_dict(action_plan1, self.SHORT_LIST_FIELDS,
self.SHORT_LIST_FIELD_LABELS)],
results)
self.m_action_plan_mgr.list.assert_called_once_with(
detail=False,
audit='770ef053-ecb3-48b0-85b5-d55a2dbc6588',
)
def test_do_action_plan_show_by_uuid(self):
action_plan = resource.ActionPlan(mock.Mock(), ACTION_PLAN_1)
self.m_action_plan_mgr.get.return_value = action_plan
exit_code, result = self.run_cmd(
'actionplan show d9d9978e-6db5-4a05-8eab-1531795d7004')
self.assertEqual(0, exit_code)
self.assertEqual(
self.resource_as_dict(
action_plan, self.FIELDS, self.FIELD_LABELS),
result)
self.m_action_plan_mgr.get.assert_called_once_with(
'd9d9978e-6db5-4a05-8eab-1531795d7004')
def test_do_action_plan_show_by_not_uuid(self):
self.m_action_plan_mgr.get.side_effect = exceptions.HTTPNotFound
exit_code, result = self.run_cmd(
'actionplan show not_uuid', formatting=None)
self.assertEqual(1, exit_code)
self.assertEqual('', result)
def test_do_action_plan_delete(self):
self.m_action_plan_mgr.delete.return_value = ''
exit_code, result = self.run_cmd(
'actionplan delete 5869da81-4876-4687-a1ed-12cd64cf53d9',
formatting=None)
self.assertEqual(0, exit_code)
self.assertEqual('', result)
self.m_action_plan_mgr.delete.assert_called_once_with(
'5869da81-4876-4687-a1ed-12cd64cf53d9')
def test_do_action_plan_delete_not_uuid(self):
exit_code, result = self.run_cmd(
'actionplan delete not_uuid', formatting=None)
self.assertEqual(1, exit_code)
self.assertEqual('', result)
def test_do_action_plan_delete_multiple(self):
self.m_action_plan_mgr.delete.return_value = ''
exit_code, result = self.run_cmd(
'actionplan delete 5869da81-4876-4687-a1ed-12cd64cf53d9 '
'c20627fa-ea70-4d56-ae15-4106358f773b',
formatting=None)
self.assertEqual(0, exit_code)
self.assertEqual('', result)
self.m_action_plan_mgr.delete.assert_any_call(
'5869da81-4876-4687-a1ed-12cd64cf53d9')
self.m_action_plan_mgr.delete.assert_any_call(
'c20627fa-ea70-4d56-ae15-4106358f773b')
def test_do_action_plan_update(self):
action_plan = resource.ActionPlan(mock.Mock(), ACTION_PLAN_1)
self.m_action_plan_mgr.update.return_value = action_plan
exit_code, result = self.run_cmd(
'actionplan update 5869da81-4876-4687-a1ed-12cd64cf53d9 '
'replace state=CANCELLED')
self.assertEqual(0, exit_code)
self.assertEqual(
self.resource_as_dict(action_plan, self.FIELDS, self.FIELD_LABELS),
result)
self.m_action_plan_mgr.update.assert_called_once_with(
'5869da81-4876-4687-a1ed-12cd64cf53d9',
[{'op': 'replace', 'path': '/state', 'value': 'CANCELLED'}])
def test_do_action_plan_update_not_uuid(self):
exit_code, result = self.run_cmd(
'actionplan update not_uuid '
'replace state=CANCELLED',
formatting=None)
self.assertEqual(1, exit_code)
self.assertEqual('', result)
def test_do_action_plan_start(self):
action_plan = resource.ActionPlan(mock.Mock(), ACTION_PLAN_1)
self.m_action_plan_mgr.start.return_value = action_plan
exit_code, result = self.run_cmd(
'actionplan start 5869da81-4876-4687-a1ed-12cd64cf53d9')
self.assertEqual(0, exit_code)
self.assertEqual(
self.resource_as_dict(action_plan, self.FIELDS, self.FIELD_LABELS),
result)
self.m_action_plan_mgr.start.assert_called_once_with(
'5869da81-4876-4687-a1ed-12cd64cf53d9')
def test_do_action_plan_start_not_uuid(self):
exit_code, result = self.run_cmd(
'actionplan start not_uuid',
formatting=None)
self.assertEqual(1, exit_code)
self.assertEqual('', result)

@ -0,0 +1,245 @@
# -*- encoding: utf-8 -*-
# Copyright (c) 2016 b<>com
#
# 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 openstackclient.common import utils
from oslo_utils import uuidutils
from watcherclient._i18n import _
from watcherclient.common import command
from watcherclient.common import utils as common_utils
from watcherclient import exceptions
from watcherclient.v1 import resource_fields as res_fields
class ShowActionPlan(command.ShowOne):
"""Show detailed information about a given action plan."""
def get_parser(self, prog_name):
parser = super(ShowActionPlan, self).get_parser(prog_name)
parser.add_argument(
'action_plan',
metavar='<action-plan>',
help=_('UUID of the action plan'),
)
return parser
def take_action(self, parsed_args):
client = getattr(self.app.client_manager, "infra-optim")
action_plan_uuid = parsed_args.action_plan
if not uuidutils.is_uuid_like(action_plan_uuid):
raise exceptions.ValidationError()
try:
action_plan = client.action_plan.get(action_plan_uuid)
except exceptions.HTTPNotFound as exc:
raise exceptions.CommandError(str(exc))
columns = res_fields.ACTION_PLAN_FIELDS
column_headers = res_fields.ACTION_PLAN_FIELD_LABELS
return column_headers, utils.get_item_properties(action_plan, columns)
class ListActionPlan(command.Lister):
"""List information on retrieved action plans."""
def get_parser(self, prog_name):
parser = super(ListActionPlan, self).get_parser(prog_name)
parser.add_argument(
'--audit',
metavar='<audit>',
help=_('UUID of an audit used for filtering.'))
parser.add_argument(
'--detail',
dest='detail',
action='store_true',
default=False,
help=_("Show detailed information about action plans."))
parser.add_argument(
'--limit',
metavar='<limit>',
type=int,
help=_('Maximum number of action plans to return per request, '
'0 for no limit. Default is the maximum number used '
'by the Watcher API Service.'))
parser.add_argument(
'--sort-key',
metavar='<field>',
help=_('Action Plan field that will be used for sorting.'))
parser.add_argument(
'--sort-dir',
metavar='<direction>',
choices=['asc', 'desc'],
help=_('Sort direction: "asc" (the default) or "desc".'))
return parser
def take_action(self, parsed_args):
client = getattr(self.app.client_manager, "infra-optim")
params = {}
if parsed_args.audit is not None:
params['audit'] = parsed_args.audit
if parsed_args.detail:
fields = res_fields.ACTION_PLAN_FIELDS
field_labels = res_fields.ACTION_PLAN_FIELD_LABELS
else:
fields = res_fields.ACTION_PLAN_SHORT_LIST_FIELDS
field_labels = res_fields.ACTION_PLAN_SHORT_LIST_FIELD_LABELS
params.update(common_utils.common_params_for_list(
parsed_args, fields, field_labels))
data = client.action_plan.list(**params)
return (field_labels,
(utils.get_item_properties(item, fields) for item in data))
class CreateActionPlan(command.ShowOne):
"""Create new audit."""
def get_parser(self, prog_name):
parser = super(CreateActionPlan, self).get_parser(prog_name)
parser.add_argument(
'-a', '--audit-template',
required=True,
dest='audit_template_uuid',
metavar='<audit_template>',
help=_('ActionPlan template used for this audit (name or uuid).'))
parser.add_argument(
'-d', '--deadline',
dest='deadline',
metavar='<deadline>',
help=_('Descrition of the audit.'))
parser.add_argument(
'-t', '--type',
dest='type',
metavar='<type>',
default='ONESHOT',
help=_("ActionPlan type."))
return parser
def take_action(self, parsed_args):
client = getattr(self.app.client_manager, "infra-optim")
field_list = ['audit_template_uuid', 'type', 'deadline']
fields = dict((k, v) for (k, v) in vars(parsed_args).items()
if k in field_list and v is not None)
if fields.get('audit_template_uuid'):
if not uuidutils.is_uuid_like(fields['audit_template_uuid']):
fields['audit_template_uuid'] = client.audit_template.get(
fields['audit_template_uuid']).uuid
audit = client.audit.create(**fields)
columns = res_fields.ACTION_PLAN_FIELDS
column_headers = res_fields.ACTION_PLAN_FIELD_LABELS
return column_headers, utils.get_item_properties(audit, columns)
class UpdateActionPlan(command.ShowOne):
"""Update action plan command."""
def get_parser(self, prog_name):
parser = super(UpdateActionPlan, self).get_parser(prog_name)
parser.add_argument(
'action_plan',
metavar='<action-plan>',
help=_("UUID of the action_plan."))
parser.add_argument(
'op',
metavar='<op>',
choices=['add', 'replace', 'remove'],
help=_("Operation: 'add'), 'replace', or 'remove'."))
parser.add_argument(
'attributes',
metavar='<path=value>',
nargs='+',
action='append',
default=[],
help=_("Attribute to add, replace, or remove. Can be specified "
"multiple times. For 'remove', only <path> is necessary."))
return parser
def take_action(self, parsed_args):
client = getattr(self.app.client_manager, "infra-optim")
if not uuidutils.is_uuid_like(parsed_args.action_plan):
raise exceptions.ValidationError()
patch = common_utils.args_array_to_patch(
parsed_args.op, parsed_args.attributes[0])
action_plan = client.action_plan.update(parsed_args.action_plan, patch)
columns = res_fields.ACTION_PLAN_FIELDS
column_headers = res_fields.ACTION_PLAN_FIELD_LABELS
return column_headers, utils.get_item_properties(action_plan, columns)
class StartActionPlan(command.ShowOne):
"""Start action plan command."""
def get_parser(self, prog_name):
parser = super(StartActionPlan, self).get_parser(prog_name)
parser.add_argument(
'action_plan',
metavar='<action-plan>',
help=_("UUID of the action_plan."))
return parser
def take_action(self, parsed_args):
client = getattr(self.app.client_manager, "infra-optim")
if not uuidutils.is_uuid_like(parsed_args.action_plan):
raise exceptions.ValidationError()
action_plan = client.action_plan.start(parsed_args.action_plan)
columns = res_fields.ACTION_PLAN_FIELDS
column_headers = res_fields.ACTION_PLAN_FIELD_LABELS
return column_headers, utils.get_item_properties(action_plan, columns)
class DeleteActionPlan(command.Command):
"""Delete action plan command."""
def get_parser(self, prog_name):
parser = super(DeleteActionPlan, self).get_parser(prog_name)
parser.add_argument(
'action_plans',
metavar='<action-plan>',
nargs='+',
help=_('UUID of the action plan'),
)
return parser
def take_action(self, parsed_args):
client = getattr(self.app.client_manager, "infra-optim")
for action_plan in parsed_args.action_plans:
if not uuidutils.is_uuid_like(action_plan):
raise exceptions.ValidationError()
client.action_plan.delete(action_plan)