diff --git a/setup.cfg b/setup.cfg index b985df4..f4913d5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -43,6 +43,12 @@ openstack.infra_optim.v1 = optimize_audittemplate_update = watcherclient.v1.osc.audit_template_shell:UpdateAuditTemplate optimize_audittemplate_delete = watcherclient.v1.osc.audit_template_shell:DeleteAuditTemplate + optimize_audit_show = watcherclient.v1.osc.audit_shell:ShowAudit + optimize_audit_list = watcherclient.v1.osc.audit_shell:ListAudit + optimize_audit_create = watcherclient.v1.osc.audit_shell:CreateAudit + optimize_audit_update = watcherclient.v1.osc.audit_shell:UpdateAudit + optimize_audit_delete = watcherclient.v1.osc.audit_shell:DeleteAudit + # The same as above but used by the 'watcher' command watcherclient.v1 = goal_show = watcherclient.v1.osc.goal_shell:ShowGoal @@ -57,6 +63,12 @@ watcherclient.v1 = audittemplate_update = watcherclient.v1.osc.audit_template_shell:UpdateAuditTemplate audittemplate_delete = watcherclient.v1.osc.audit_template_shell:DeleteAuditTemplate + audit_show = watcherclient.v1.osc.audit_shell:ShowAudit + audit_list = watcherclient.v1.osc.audit_shell:ListAudit + audit_create = watcherclient.v1.osc.audit_shell:CreateAudit + audit_update = watcherclient.v1.osc.audit_shell:UpdateAudit + audit_delete = watcherclient.v1.osc.audit_shell:DeleteAudit + [pbr] autodoc_index_modules = True diff --git a/watcherclient/tests/v1/osc/test_audit_shell.py b/watcherclient/tests/v1/osc/test_audit_shell.py new file mode 100644 index 0000000..af1d96d --- /dev/null +++ b/watcherclient/tests/v1/osc/test_audit_shell.py @@ -0,0 +1,279 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2013 IBM Corp +# +# 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 + +AUDIT_TEMPLATE_1 = { + 'uuid': 'f8e47706-efcf-49a4-a5c4-af604eb492f2', + 'name': 'at1', + 'description': 'Audit Template 1 description', + 'host_aggregate': 5, + 'extra': {'automatic': False}, + 'goal_uuid': '7568667b-51fe-4087-9eb1-29b26891036f', + 'strategy_uuid': 'bbe6b966-f98e-439b-a01a-17b9b3b8478b', + 'created_at': datetime.datetime.now().isoformat(), + 'updated_at': None, + 'deleted_at': None, +} + +AUDIT_1 = { + 'uuid': '5869da81-4876-4687-a1ed-12cd64cf53d9', + 'deadline': None, + 'type': 'ONESHOT', + 'state': 'PENDING', + 'audit_template_uuid': 'f8e47706-efcf-49a4-a5c4-af604eb492f2', + 'audit_template_name': 'at1', + 'created_at': datetime.datetime.now().isoformat(), + 'updated_at': None, + 'deleted_at': None, +} + +AUDIT_2 = { + 'uuid': 'a5199d0e-0702-4613-9234-5ae2af8dafea', + 'deadline': None, + 'type': 'ONESHOT', + 'audit_template_uuid': '770ef053-ecb3-48b0-85b5-d55a2dbc6588', + 'audit_template_name': 'at2', + 'state': 'PENDING', + 'created_at': datetime.datetime.now().isoformat(), + 'updated_at': None, + 'deleted_at': None, +} + + +class AuditShellTest(base.CommandTestCase): + + SHORT_LIST_FIELDS = resource_fields.AUDIT_SHORT_LIST_FIELDS + SHORT_LIST_FIELD_LABELS = resource_fields.AUDIT_SHORT_LIST_FIELD_LABELS + FIELDS = resource_fields.AUDIT_FIELDS + FIELD_LABELS = resource_fields.AUDIT_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, 'AuditTemplateManager') + self.m_audit_mgr_cls = p_audit_manager.start() + self.m_audit_template_mgr_cls = p_audit_template_manager.start() + self.addCleanup(p_audit_manager.stop) + self.addCleanup(p_audit_template_manager.stop) + + self.m_audit_mgr = mock.Mock() + self.m_audit_template_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.stdout = six.StringIO() + self.cmd = shell.WatcherShell(stdout=self.stdout) + + def test_do_audit_list(self): + audit1 = resource.Audit(mock.Mock(), AUDIT_1) + audit2 = resource.Audit(mock.Mock(), AUDIT_2) + self.m_audit_mgr.list.return_value = [ + audit1, audit2] + + exit_code, results = self.run_cmd('audit list') + + self.assertEqual(0, exit_code) + self.assertEqual( + [self.resource_as_dict(audit1, self.SHORT_LIST_FIELDS, + self.SHORT_LIST_FIELD_LABELS), + self.resource_as_dict(audit2, self.SHORT_LIST_FIELDS, + self.SHORT_LIST_FIELD_LABELS)], + results) + + self.m_audit_mgr.list.assert_called_once_with(detail=False) + + def test_do_audit_list_detail(self): + audit1 = resource.Audit(mock.Mock(), AUDIT_1) + audit2 = resource.Audit(mock.Mock(), AUDIT_2) + self.m_audit_mgr.list.return_value = [ + audit1, audit2] + + exit_code, results = self.run_cmd('audit list --detail') + + self.assertEqual(0, exit_code) + self.assertEqual( + [self.resource_as_dict(audit1, self.FIELDS, + self.FIELD_LABELS), + self.resource_as_dict(audit2, self.FIELDS, + self.FIELD_LABELS)], + results) + + self.m_audit_mgr.list.assert_called_once_with(detail=True) + + def test_do_audit_show_by_uuid(self): + audit = resource.Audit(mock.Mock(), AUDIT_1) + self.m_audit_mgr.get.return_value = audit + self.m_audit_template_mgr.get.return_value = audit + + exit_code, result = self.run_cmd( + 'audit show 5869da81-4876-4687-a1ed-12cd64cf53d9') + + self.assertEqual(0, exit_code) + self.assertEqual( + self.resource_as_dict(audit, self.FIELDS, self.FIELD_LABELS), + result) + self.m_audit_mgr.get.assert_called_once_with( + '5869da81-4876-4687-a1ed-12cd64cf53d9') + + def test_do_audit_show_by_not_uuid(self): + self.m_audit_mgr.get.side_effect = exceptions.HTTPNotFound + + exit_code, result = self.run_cmd( + 'audit show not_uuid', formatting=None) + + self.assertEqual(1, exit_code) + self.assertEqual('', result) + + def test_do_audit_delete(self): + self.m_audit_mgr.delete.return_value = '' + + exit_code, result = self.run_cmd( + 'audit delete 5869da81-4876-4687-a1ed-12cd64cf53d9', + formatting=None) + + self.assertEqual(0, exit_code) + self.assertEqual('', result) + self.m_audit_mgr.delete.assert_called_once_with( + '5869da81-4876-4687-a1ed-12cd64cf53d9') + + def test_do_audit_delete_multiple(self): + self.m_audit_mgr.delete.return_value = '' + + exit_code, result = self.run_cmd( + 'audit delete 5869da81-4876-4687-a1ed-12cd64cf53d9 ' + '5b157edd-5a7e-4aaa-b511-f7b33ec86e9f', + formatting=None) + + self.assertEqual(0, exit_code) + self.assertEqual('', result) + self.m_audit_mgr.delete.assert_any_call( + '5869da81-4876-4687-a1ed-12cd64cf53d9') + self.m_audit_mgr.delete.assert_any_call( + '5b157edd-5a7e-4aaa-b511-f7b33ec86e9f') + + def test_do_audit_delete_with_not_uuid(self): + self.m_audit_mgr.delete.return_value = '' + + exit_code, result = self.run_cmd( + 'audit delete not_uuid', + formatting=None) + + self.assertEqual(1, exit_code) + self.assertEqual('', result) + + def test_do_audit_update(self): + audit = resource.Audit(mock.Mock(), AUDIT_1) + self.m_audit_mgr.update.return_value = audit + + exit_code, result = self.run_cmd( + 'audit update 5869da81-4876-4687-a1ed-12cd64cf53d9 ' + 'replace state=PENDING') + + self.assertEqual(0, exit_code) + self.assertEqual( + self.resource_as_dict(audit, self.FIELDS, self.FIELD_LABELS), + result) + self.m_audit_mgr.update.assert_called_once_with( + '5869da81-4876-4687-a1ed-12cd64cf53d9', + [{'op': 'replace', 'path': '/state', 'value': 'PENDING'}]) + + def test_do_audit_update_with_not_uuid(self): + self.m_audit_mgr.update.return_value = '' + + exit_code, result = self.run_cmd( + 'audit update not_uuid replace state=PENDING', formatting=None) + + self.assertEqual(1, exit_code) + self.assertEqual('', result) + + def test_do_audit_create_with_audit_template_uuid(self): + audit = resource.Audit(mock.Mock(), AUDIT_1) + self.m_audit_mgr.create.return_value = audit + + exit_code, result = self.run_cmd( + 'audit create -a f8e47706-efcf-49a4-a5c4-af604eb492f2') + + self.assertEqual(0, exit_code) + self.assertEqual( + self.resource_as_dict(audit, self.FIELDS, self.FIELD_LABELS), + result) + self.m_audit_mgr.create.assert_called_once_with( + audit_template_uuid='f8e47706-efcf-49a4-a5c4-af604eb492f2', + type='ONESHOT') + + def test_do_audit_create_with_audit_template_name(self): + audit = resource.Audit(mock.Mock(), AUDIT_1) + audit_template = resource.AuditTemplate(mock.Mock(), AUDIT_TEMPLATE_1) + self.m_audit_template_mgr.get.return_value = audit_template + self.m_audit_mgr.create.return_value = audit + + exit_code, result = self.run_cmd('audit create -a at1') + + self.assertEqual(0, exit_code) + self.assertEqual( + self.resource_as_dict(audit, self.FIELDS, self.FIELD_LABELS), + result) + self.m_audit_mgr.create.assert_called_once_with( + audit_template_uuid='f8e47706-efcf-49a4-a5c4-af604eb492f2', + type='ONESHOT') + + def test_do_audit_create_with_deadline(self): + audit = resource.Audit(mock.Mock(), AUDIT_1) + audit_template = resource.AuditTemplate(mock.Mock(), AUDIT_TEMPLATE_1) + self.m_audit_template_mgr.get.return_value = audit_template + self.m_audit_mgr.create.return_value = audit + + exit_code, result = self.run_cmd( + 'audit create -a at1 -d 2016-04-28T10:48:32.064802') + + self.assertEqual(0, exit_code) + self.assertEqual( + self.resource_as_dict(audit, self.FIELDS, self.FIELD_LABELS), + result) + self.m_audit_mgr.create.assert_called_once_with( + audit_template_uuid='f8e47706-efcf-49a4-a5c4-af604eb492f2', + type='ONESHOT', + deadline='2016-04-28T10:48:32.064802') + + def test_do_audit_create_with_type(self): + audit = resource.Audit(mock.Mock(), AUDIT_1) + audit_template = resource.AuditTemplate(mock.Mock(), AUDIT_TEMPLATE_1) + self.m_audit_template_mgr.get.return_value = audit_template + self.m_audit_mgr.create.return_value = audit + + exit_code, result = self.run_cmd( + 'audit create -a at1 -t ONESHOT') + + self.assertEqual(0, exit_code) + self.assertEqual( + self.resource_as_dict(audit, self.FIELDS, self.FIELD_LABELS), + result) + self.m_audit_mgr.create.assert_called_once_with( + audit_template_uuid='f8e47706-efcf-49a4-a5c4-af604eb492f2', + type='ONESHOT') diff --git a/watcherclient/v1/osc/audit_shell.py b/watcherclient/v1/osc/audit_shell.py new file mode 100644 index 0000000..c3da48d --- /dev/null +++ b/watcherclient/v1/osc/audit_shell.py @@ -0,0 +1,219 @@ +# -*- 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 ShowAudit(command.ShowOne): + """Show detailed information about a given audit.""" + + def get_parser(self, prog_name): + parser = super(ShowAudit, self).get_parser(prog_name) + parser.add_argument( + 'audit', + metavar='', + help=_('UUID of the audit'), + ) + return parser + + def take_action(self, parsed_args): + client = getattr(self.app.client_manager, "infra-optim") + + try: + audit = client.audit.get(parsed_args.audit) + except exceptions.HTTPNotFound as exc: + raise exceptions.CommandError(str(exc)) + + columns = res_fields.AUDIT_FIELDS + column_headers = res_fields.AUDIT_FIELD_LABELS + + return column_headers, utils.get_item_properties(audit, columns) + + +class ListAudit(command.Lister): + """List information on retrieved audits.""" + + def get_parser(self, prog_name): + parser = super(ListAudit, self).get_parser(prog_name) + parser.add_argument( + '--audit-template', + metavar='', + dest='audit_template', + help=_('Name or UUID of an audit template used for filtering.')) + parser.add_argument( + '--detail', + dest='detail', + action='store_true', + default=False, + help=_("Show detailed information about audits.")) + parser.add_argument( + '--limit', + metavar='', + type=int, + help=_('Maximum number of audits 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='', + help=_('Audit field that will be used for sorting.')) + parser.add_argument( + '--sort-dir', + metavar='', + 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_template is not None: + params['audit_template'] = parsed_args.audit_template + if parsed_args.detail: + fields = res_fields.AUDIT_FIELDS + field_labels = res_fields.AUDIT_FIELD_LABELS + else: + fields = res_fields.AUDIT_SHORT_LIST_FIELDS + field_labels = res_fields.AUDIT_SHORT_LIST_FIELD_LABELS + + params.update(common_utils.common_params_for_list( + parsed_args, fields, field_labels)) + + try: + data = client.audit.list(**params) + except exceptions.HTTPNotFound as ex: + raise exceptions.CommandError(str(ex)) + + return (field_labels, + (utils.get_item_properties(item, fields) for item in data)) + + +class CreateAudit(command.ShowOne): + """Create new audit.""" + + def get_parser(self, prog_name): + parser = super(CreateAudit, self).get_parser(prog_name) + parser.add_argument( + '-a', '--audit-template', + required=True, + dest='audit_template_uuid', + metavar='', + help=_('Audit template used for this audit (name or uuid).')) + parser.add_argument( + '-d', '--deadline', + dest='deadline', + metavar='', + help=_('Descrition of the audit.')) + parser.add_argument( + '-t', '--type', + dest='type', + metavar='', + default='ONESHOT', + help=_("Audit 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.AUDIT_FIELDS + column_headers = res_fields.AUDIT_FIELD_LABELS + + return column_headers, utils.get_item_properties(audit, columns) + + +class UpdateAudit(command.ShowOne): + """Update audit command.""" + + def get_parser(self, prog_name): + parser = super(UpdateAudit, self).get_parser(prog_name) + parser.add_argument( + 'audit', + metavar='', + help=_("UUID of the audit.")) + parser.add_argument( + 'op', + metavar='', + choices=['add', 'replace', 'remove'], + help=_("Operation: 'add'), 'replace', or 'remove'.")) + parser.add_argument( + 'attributes', + metavar='', + nargs='+', + action='append', + default=[], + help=_("Attribute to add, replace, or remove. Can be specified " + "multiple times. For 'remove', only 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.audit): + raise exceptions.ValidationError() + + patch = common_utils.args_array_to_patch( + parsed_args.op, parsed_args.attributes[0]) + + audit = client.audit.update(parsed_args.audit, patch) + + columns = res_fields.AUDIT_FIELDS + column_headers = res_fields.AUDIT_FIELD_LABELS + + return column_headers, utils.get_item_properties(audit, columns) + + +class DeleteAudit(command.Command): + """Delete audit command.""" + + def get_parser(self, prog_name): + parser = super(DeleteAudit, self).get_parser(prog_name) + parser.add_argument( + 'audits', + metavar='', + nargs='+', + help=_('UUID of the audit'), + ) + return parser + + def take_action(self, parsed_args): + client = getattr(self.app.client_manager, "infra-optim") + + for audit in parsed_args.audits: + if not uuidutils.is_uuid_like(audit): + raise exceptions.ValidationError() + + client.audit.delete(audit)