diff --git a/almanachclient/commands/get_entity.py b/almanachclient/commands/get_entity.py new file mode 100644 index 0000000..f768033 --- /dev/null +++ b/almanachclient/commands/get_entity.py @@ -0,0 +1,50 @@ +# Copyright 2017 INAP +# +# 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 cliff.lister import Lister + + +class GetEntityCommand(Lister): + """Get entity""" + + columns = ('Tenant ID', 'Type', 'Name', 'Start', 'End', 'Properties') + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + parser.add_argument('entity_id', help='Entity ID') + return parser + + def take_action(self, parsed_args): + entities = self.app.get_client().get_entity(parsed_args.entity_id) + return self.columns, self._format_rows(entities) + + def _format_rows(self, entities): + rows = [] + + for entity in entities: + entity_type = entity.get('entity_type') + + if entity_type == 'instance': + properties = dict(flavor=entity.get('flavor'), + image=entity.get('image_meta', entity.get('os'))) + elif entity_type == 'volume': + properties = dict(volume_type=entity.get('volume_type'), + size=entity.get('size'), + attached_to=entity.get('attached_to')) + else: + properties = None + + rows.append((entity.get('project_id'), entity_type, entity.get('name'), + entity.get('start'), entity.get('end'), properties)) + return rows diff --git a/almanachclient/http_client.py b/almanachclient/http_client.py index b1e090b..973a5f9 100644 --- a/almanachclient/http_client.py +++ b/almanachclient/http_client.py @@ -58,12 +58,25 @@ class HttpClient(metaclass=abc.ABCMeta): return self._parse_response(response, 202) def _parse_response(self, response, expected_status=200): - body = response.json() if len(response.text) > 0 else '' - if response.status_code != expected_status: - raise exceptions.HTTPError('{} ({})'.format(body.get('error') or 'HTTP Error', response.status_code)) + raise exceptions.HTTPError('{} ({})'.format(self._get_error_message(response), response.status_code)) - return body + return self._get_body(response) + + def _get_body(self, response): + if self._is_json_response(response) and self._has_content(response): + return response.json() + return '' + + def _get_error_message(self, response, default_message='HTTP Error'): + body = self._get_body(response) + return body.get('error', default_message) if isinstance(body, dict) else response.text + + def _is_json_response(self, response): + return 'Content-Type' in response.headers and 'application/json' in response.headers['Content-Type'] + + def _has_content(self, response): + return 'Content-Length' in response.headers and int(response.headers['Content-Length']) > 0 def _get_headers(self): return { diff --git a/almanachclient/shell.py b/almanachclient/shell.py index b548037..7f1eb36 100644 --- a/almanachclient/shell.py +++ b/almanachclient/shell.py @@ -23,6 +23,7 @@ from almanachclient.commands.create_volume_type import CreateVolumeTypeCommand from almanachclient.commands.delete_instance import DeleteInstanceCommand from almanachclient.commands.delete_volume_type import DeleteVolumeTypeCommand from almanachclient.commands.endpoint import EndpointCommand +from almanachclient.commands.get_entity import GetEntityCommand from almanachclient.commands.get_volume_type import GetVolumeTypeCommand from almanachclient.commands.list_entity import ListEntityCommand from almanachclient.commands.list_instance import ListInstanceCommand @@ -47,6 +48,7 @@ class AlmanachCommandManager(commandmanager.CommandManager): 'list-instances': ListInstanceCommand, 'create-instance': CreateInstanceCommand, 'delete-instance': DeleteInstanceCommand, + 'get-entity': GetEntityCommand, 'list-entities': ListEntityCommand, 'update instance': UpdateInstanceEntityCommand, } diff --git a/almanachclient/tests/commands/test_get_entity.py b/almanachclient/tests/commands/test_get_entity.py new file mode 100644 index 0000000..c01cfef --- /dev/null +++ b/almanachclient/tests/commands/test_get_entity.py @@ -0,0 +1,42 @@ +# Copyright 2017 INAP +# +# 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 argparse import Namespace +from unittest import mock + +from almanachclient.commands.get_entity import GetEntityCommand + +from almanachclient.tests import base + + +class TestGetEntityCommand(base.TestCase): + + def setUp(self): + super().setUp() + self.app = mock.Mock() + self.app_args = mock.Mock() + self.args = Namespace(entity_id='some uuid') + + self.client = mock.Mock() + self.app.get_client.return_value = self.client + self.command = GetEntityCommand(self.app, self.app_args) + + def test_execute_command(self): + self.client.get_entity.return_value = [{'entity_id': 'some uuid', 'project_id': 'tenant id'}] + + expected = (('Tenant ID', 'Type', 'Name', 'Start', 'End', 'Properties'), + [('tenant id', None, None, None, None, None)]) + + self.assertEqual(expected, self.command.take_action(self.args)) + self.client.get_entity.assert_called_once_with(self.args.entity_id) diff --git a/almanachclient/tests/v1/test_client.py b/almanachclient/tests/v1/test_client.py index 32c91b2..cd36517 100644 --- a/almanachclient/tests/v1/test_client.py +++ b/almanachclient/tests/v1/test_client.py @@ -25,7 +25,8 @@ class TestClient(base.TestCase): def setUp(self): super().setUp() - self.response = mock.Mock(text='sample data') + self.response = mock.Mock(headers={'Content-Type': 'application/json; charset=utf-8', + 'Content-Length': '1'}) self.url = 'http://almanach_url' self.token = 'token' self.headers = {'Content-Type': 'application/json', @@ -74,6 +75,20 @@ class TestClient(base.TestCase): params=params, headers=self.headers) + @mock.patch('requests.get') + def test_get_entity(self, requests): + expected = [mock.Mock()] + + requests.return_value = self.response + self.response.json.return_value = expected + self.response.status_code = 200 + + self.assertEqual(expected, self.client.get_entity('entity_id')) + + requests.assert_called_once_with('{}{}'.format(self.url, '/v1/entity/entity_id'), + params=None, + headers=self.headers) + @mock.patch('requests.put') def test_update_instance_entity(self, requests): expected = dict(name='some entity') @@ -116,7 +131,7 @@ class TestClient(base.TestCase): @mock.patch('requests.post') def test_create_volume_type(self, requests): data = {'type_id': 'some uuid', 'type_name': 'some name'} - self.response.text = '' + self.response.headers['Content-Length'] = 0 requests.return_value = self.response self.response.status_code = 201 @@ -129,7 +144,7 @@ class TestClient(base.TestCase): @mock.patch('requests.delete') def test_delete_volume_type(self, requests): - self.response.text = '' + self.response.headers['Content-Length'] = 0 requests.return_value = self.response self.response.status_code = 202 @@ -142,7 +157,7 @@ class TestClient(base.TestCase): @mock.patch('requests.delete') def test_delete_instance(self, requests): - self.response.text = '' + self.response.headers['Content-Length'] = 0 date = datetime.now() requests.return_value = self.response @@ -156,7 +171,7 @@ class TestClient(base.TestCase): @mock.patch('requests.post') def test_create_instance(self, requests): - self.response.text = '' + self.response.headers['Content-Length'] = 0 date = datetime.now() requests.return_value = self.response diff --git a/almanachclient/v1/client.py b/almanachclient/v1/client.py index a57cd7f..5413e9f 100644 --- a/almanachclient/v1/client.py +++ b/almanachclient/v1/client.py @@ -142,6 +142,10 @@ class Client(HttpClient): self._delete('{}/{}/instance/{}'.format(self.url, self.api_version, instance_id), data=data) return True + def get_entity(self, entity_id): + url = '{}/{}/entity/{}'.format(self.url, self.api_version, entity_id) + return self._get(url) + def get_tenant_entities(self, tenant_id, start, end): """List instances and volumes for a tenant. diff --git a/doc/source/usage.rst b/doc/source/usage.rst index 7fc4238..43acc4d 100644 --- a/doc/source/usage.rst +++ b/doc/source/usage.rst @@ -57,6 +57,24 @@ Arguments: * :code:`start`: Start date (ISO8601 format) * :code:`end`: End date (ISO8601 format) +Get one Entity +-------------- + +Usage: :code:`almanach get-entity ` + +.. code:: bash + + almanach get-entity 3e3b22e6-a10c-4c00-b8e5-05fcc8422b11 + + +----------------------------------+--------+------+---------------------------+------+-------------------------------------------------------------+ + | Tenant ID | Type | Name | Start | End | Properties | + +----------------------------------+--------+------+---------------------------+------+-------------------------------------------------------------+ + | bca89ae64dba46b8b74653d8d9ae8364 | volume | vol1 | 2017-05-15 19:11:14+00:00 | None | {'size': 1, 'attached_to': [], 'volume_type': 'solidfire0'} | + +----------------------------------+--------+------+---------------------------+------+-------------------------------------------------------------+ + +Arguments: + +* :code:`entity_id`: Entity ID (UUID) List Instances Entities -----------------------