From 120ba04c1f74d6d6c4f4c09f9babf0659a502069 Mon Sep 17 00:00:00 2001 From: aviau Date: Tue, 23 Dec 2014 12:47:22 -0500 Subject: [PATCH] Added create function to host and service Change-Id: I630b62e324e362a79602cdea1759e7cedded6ab1 --- surveilclient/common/http.py | 21 ++++++++++++-- surveilclient/exc.py | 53 ++++++++++++++++++++++++++++++++++ surveilclient/v1_0/hosts.py | 8 +++++ surveilclient/v1_0/services.py | 8 +++++ 4 files changed, 87 insertions(+), 3 deletions(-) diff --git a/surveilclient/common/http.py b/surveilclient/common/http.py index a606d28..27a33d5 100644 --- a/surveilclient/common/http.py +++ b/surveilclient/common/http.py @@ -15,6 +15,7 @@ from six.moves import http_client as httplib +from surveilclient import exc from surveilclient.openstack.common.py3kcompat import urlutils import copy @@ -52,7 +53,17 @@ class HTTPClient(object): conn = self.get_connection() conn.request(method, self.endpoint_path + url, **kwargs) resp = conn.getresponse() - return resp + + body_str = resp.read() + + if 400 <= resp.status < 600: + raise exc.from_response( + response=resp, body=body_str, method=method, url=url) + elif resp.status == 300: + raise exc.from_response( + response=resp, body=body_str, method=method, url=url) + + return resp, body_str def json_request(self, url, method, **kwargs): """Send an http request with the specified characteristics. @@ -60,5 +71,9 @@ class HTTPClient(object): """ kwargs['headers'] = copy.deepcopy(kwargs.get('headers', {})) kwargs['headers'].setdefault('Content-Type', 'application/json') - resp = self._http_request(url, method, **kwargs) - return resp, json.loads(resp.read().decode()) + + if 'body' in kwargs: + kwargs['body'] = json.dumps(kwargs['body']) + + resp, body = self._http_request(url, method, **kwargs) + return resp, json.loads(body) diff --git a/surveilclient/exc.py b/surveilclient/exc.py index 3dd78d6..8d27005 100644 --- a/surveilclient/exc.py +++ b/surveilclient/exc.py @@ -12,6 +12,59 @@ # License for the specific language governing permissions and limitations # under the License. +import json + class CommandError(BaseException): """Invalid usage of CLI.""" + + +class ClientException(Exception): + """The base exception class for all exceptions this library raises.""" + pass + + +class HttpError(ClientException): + """The base exception class for all HTTP exceptions.""" + http_status = 0 + message = "HTTP Error" + + def __init__(self, message=None, details=None, + response=None, request_id=None, + url=None, method=None, http_status=None): + self.http_status = http_status or self.http_status + self.message = message or self.message + self.details = details + self.request_id = request_id + self.response = response + self.url = url + self.method = method + formatted_string = "%s (HTTP %s)" % (self.message, self.http_status) + if request_id: + formatted_string += " (Request-ID: %s)" % request_id + super(HttpError, self).__init__(formatted_string) + + +def from_response(response, body, method, url): + """Returns an instance of :class:`HttpError` or subclass based on response. + + :param response: instance of `requests.Response` class + :param method: HTTP method used for request + :param url: URL used for request + """ + + if response.getheader('Content-Type').startswith('application/json'): + try: + loaded_body = json.loads(body) + if 'faultstring' in loaded_body: + body = loaded_body['faultstring'] + except ValueError: + pass + + return HttpError( + response=response, + url=url, + method=method, + http_status=response.status, + message=body + ) \ No newline at end of file diff --git a/surveilclient/v1_0/hosts.py b/surveilclient/v1_0/hosts.py index c9cc4f7..66140a1 100644 --- a/surveilclient/v1_0/hosts.py +++ b/surveilclient/v1_0/hosts.py @@ -24,3 +24,11 @@ class HostsManager(surveil_manager.SurveilManager): HostsManager.base_url, 'GET' ) return body + + def create(self, **kwargs): + """Create a new host.""" + resp, body = self.http_client.json_request( + HostsManager.base_url, 'POST', + body=kwargs + ) + return body diff --git a/surveilclient/v1_0/services.py b/surveilclient/v1_0/services.py index 8b54921..5ebfa19 100644 --- a/surveilclient/v1_0/services.py +++ b/surveilclient/v1_0/services.py @@ -24,3 +24,11 @@ class ServicesManager(surveil_manager.SurveilManager): ServicesManager.base_url, 'GET' ) return body + + def create(self, **kwargs): + """Create a new host.""" + resp, body = self.http_client.json_request( + ServicesManager.base_url, 'POST', + body=kwargs + ) + return body