Added mkdir functionality to storage
[kamaki] / kamaki / clients / __init__.py
1 # Copyright 2011-2012 GRNET S.A. All rights reserved.
2 #
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
5 # conditions are met:
6 #
7 #   1. Redistributions of source code must retain the above
8 #      copyright notice, this list of conditions and the following
9 #      disclaimer.
10 #
11 #   2. Redistributions in binary form must reproduce the above
12 #      copyright notice, this list of conditions and the following
13 #      disclaimer in the documentation and/or other materials
14 #      provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 # POSSIBILITY OF SUCH DAMAGE.
28 #
29 # The views and conclusions contained in the software and
30 # documentation are those of the authors and should not be
31 # interpreted as representing official policies, either expressed
32 # or implied, of GRNET S.A.
33
34 import json
35 import logging
36
37 import requests
38
39 from requests.auth import AuthBase
40
41
42 sendlog = logging.getLogger('clients.send')
43 recvlog = logging.getLogger('clients.recv')
44
45
46 # Add a convenience status property to the responses
47 def _status(self):
48     return requests.status_codes._codes[self.status_code][0].upper()
49 requests.Response.status = property(_status)
50
51
52 class ClientError(Exception):
53     def __init__(self, message, status=0, details=''):
54         super(ClientError, self).__init__(message, status, details)
55         self.message = message
56         self.status = status
57         self.details = details
58
59
60 class Client(object):
61     def __init__(self, base_url, token):
62         self.base_url = base_url
63         self.token = token
64
65     def raise_for_status(self, r):
66         message = "%d %s" % (r.status_code, r.status)
67         details = r.text
68         raise ClientError(message, r.status_code, details)
69
70     def request(self, method, path, **kwargs):
71         raw = kwargs.pop('raw', False)
72         success = kwargs.pop('success', 200)
73         directory = kwargs.pop('directory', False)
74
75         data = kwargs.pop('data', None)
76         headers = kwargs.pop('headers', {})
77         headers.setdefault('X-Auth-Token', self.token)
78
79         if directory:
80             headers.setdefault('Content-Type', 'application/directory')
81             headers.setdefault('Content-length', '0')
82         else:
83             if 'json' in kwargs:
84                 data = json.dumps(kwargs.pop('json'))
85                 headers.setdefault('Content-Type', 'application/json')
86             if data:
87                 headers.setdefault('Content-Length', str(len(data)))
88
89         url = self.base_url + path
90         kwargs.setdefault('verify', False)  # Disable certificate verification
91         r = requests.request(method, url, headers=headers, data=data, **kwargs)
92
93         req = r.request
94         sendlog.info('%s %s', req.method, req.url)
95         for key, val in req.headers.items():
96             sendlog.info('%s: %s', key, val)
97         sendlog.info('')
98         if req.data:
99             sendlog.info('%s', req.data)
100
101         recvlog.info('%d %s', r.status_code, r.status)
102         for key, val in r.headers.items():
103             recvlog.info('%s: %s', key, val)
104         recvlog.info('')
105         if not raw and r.content:
106             recvlog.debug(r.content)
107
108         if success is not None:
109             # Success can either be an in or a collection
110             success = (success,) if isinstance(success, int) else success
111             if r.status_code not in success:
112                 self.raise_for_status(r)
113
114         return r
115
116     def delete(self, path, **kwargs):
117         return self.request('delete', path, **kwargs)
118
119     def get(self, path, **kwargs):
120         return self.request('get', path, **kwargs)
121
122     def head(self, path, **kwargs):
123         return self.request('head', path, **kwargs)
124
125     def post(self, path, **kwargs):
126         return self.request('post', path, **kwargs)
127
128     def put(self, path, **kwargs):
129         return self.request('put', path, **kwargs)
130
131
132 from .compute import ComputeClient as compute
133 from .image import ImageClient as image
134 from .storage import StorageClient as storage
135 from .cyclades import CycladesClient as cyclades
136 from .pithos import PithosClient as pithos
137 from .astakos import AstakosClient as astakos