1 # Copyright 2011 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
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.
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.
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.
34 from httplib import HTTPConnection, HTTP
40 import pithos.api.faults
42 ERROR_CODES = {304:'Not Modified',
47 411:'Length Required',
48 412:'Precondition Failed',
49 416:'Range Not Satisfiable',
50 422:'Unprocessable Entity',
51 503:'Service Unavailable'}
53 class Fault(Exception):
54 def __init__(self, data='', status=None):
55 if data == '' and status in ERROR_CODES.keys():
56 data = ERROR_CODES[status]
57 Exception.__init__(self, data)
62 def __init__(self, host, account, api='v1', verbose=False, debug=False):
63 """`host` can also include a port, e.g '127.0.0.1:8000'."""
66 self.account = account
68 self.verbose = verbose or debug
71 def _chunked_transfer(self, path, method='PUT', f=stdin, headers=None,
73 http = HTTPConnection(self.host)
76 path = '/%s/%s%s' % (self.api, self.account, path)
77 http.putrequest(method, path)
78 http.putheader('Content-Type', 'application/octet-stream')
79 http.putheader('Transfer-Encoding', 'chunked')
81 for header,value in headers.items():
82 http.putheader(header, value)
90 block = f.read(blocksize)
93 data = '%s\r\n%s\r\n' % (hex(len(block)), block)
107 resp = http.getresponse()
109 headers = dict(resp.getheaders())
112 print '%d %s' % (resp.status, resp.reason)
113 for key, val in headers.items():
114 print '%s: %s' % (key.capitalize(), val)
117 length = resp.getheader('Content-length', None)
118 data = resp.read(length)
123 if int(resp.status) in ERROR_CODES.keys():
124 raise Fault(data, int(resp.status))
126 #print '*', resp.status, headers, data
127 return resp.status, headers, data
129 def req(self, method, path, body=None, headers=None, format='text',
131 full_path = '/%s/%s%s?format=%s' % (self.api, self.account, path,
134 for k,v in params.items():
136 full_path = '%s&%s=%s' %(full_path, k, v)
137 conn = HTTPConnection(self.host)
140 full_path = full_path.replace(' ', '%20')
143 kwargs['headers'] = headers or {}
145 'Transfer-Encoding' not in headers \
146 or headers['Transfer-Encoding'] != 'chunked':
147 kwargs['headers']['Content-Length'] = len(body) if body else 0
149 kwargs['body'] = body
150 kwargs['headers']['Content-Type'] = 'application/octet-stream'
151 #print '****', method, full_path, kwargs
153 conn.request(method, full_path, **kwargs)
154 except socket.error, e:
155 raise Fault(status=503)
157 resp = conn.getresponse()
158 headers = dict(resp.getheaders())
161 print '%d %s' % (resp.status, resp.reason)
162 for key, val in headers.items():
163 print '%s: %s' % (key.capitalize(), val)
166 length = resp.getheader('Content-length', None)
167 data = resp.read(length)
172 if int(resp.status) in ERROR_CODES.keys():
173 raise Fault(data, int(resp.status))
175 #print '*', resp.status, headers, data
176 return resp.status, headers, data
178 def delete(self, path, format='text'):
179 return self.req('DELETE', path, format=format)
181 def get(self, path, format='text', headers=None, params=None):
182 return self.req('GET', path, headers=headers, format=format,
185 def head(self, path, format='text', params=None):
186 return self.req('HEAD', path, format=format, params=params)
188 def post(self, path, body=None, format='text', headers=None):
189 return self.req('POST', path, body, headers=headers, format=format)
191 def put(self, path, body=None, format='text', headers=None):
192 return self.req('PUT', path, body, headers=headers, format=format)
194 def _list(self, path, detail=False, params=None, headers=None):
195 format = 'json' if detail else 'text'
196 status, headers, data = self.get(path, format=format, headers=headers,
199 data = json.loads(data)
201 data = data.strip().split('\n')
204 def _get_metadata(self, path, prefix=None, params=None):
205 status, headers, data = self.head(path, params=params)
206 prefixlen = len(prefix) if prefix else 0
208 for key, val in headers.items():
209 if prefix and not key.startswith(prefix):
211 elif prefix and key.startswith(prefix):
212 key = key[prefixlen:]
216 def _update_metadata(self, path, entity, **meta):
218 adds new and updates the values of previously set metadata
220 prefix = 'x-%s-meta-' % entity
221 prev_meta = self._get_metadata(path, prefix)
222 prev_meta.update(meta)
224 for key, val in prev_meta.items():
225 key = '%s%s' % (prefix, key)
226 key = '-'.join(elem.capitalize() for elem in key.split('-'))
228 self.post(path, headers=headers)
230 def _delete_metadata(self, path, entity, meta=[]):
232 delete previously set metadata
234 prefix = 'x-%s-meta-' % entity
235 prev_meta = self._get_metadata(path, prefix)
237 for key, val in prev_meta.items():
240 key = '%s%s' % (prefix, key)
241 key = '-'.join(elem.capitalize() for elem in key.split('-'))
243 self.post(path, headers=headers)
245 # Storage Account Services
247 def list_containers(self, detail=False, params=None, headers=None):
248 return self._list('', detail, params, headers)
250 def account_metadata(self, restricted=False, until=None):
251 prefix = 'x-account-meta-' if restricted else None
252 params = {'until':until} if until else None
253 return self._get_metadata('', prefix, params=params)
255 def update_account_metadata(self, **meta):
256 self._update_metadata('', 'account', **meta)
258 def delete_account_metadata(self, meta=[]):
259 self._delete_metadata('', 'account', meta)
261 def set_account_groups(self, groups):
263 for key, val in groups.items():
264 headers['X-Account-Group-%s' % key.capitalize()] = val
265 self.post('', headers=headers)
267 # Storage Container Services
269 def _filter(self, l, d):
271 filter out from l elements having the metadata values provided
275 if type(elem) == types.DictionaryType:
277 k = 'x_object_meta_%s' % key
278 if k in elem.keys() and elem[k] == d[key]:
283 def _filter_trashed(self, l):
284 return self._filter(l, {'trash':'true'})
286 def list_objects(self, container, detail=False, params=None, headers=None,
287 include_trashed=False):
288 l = self._list('/' + container, detail, params, headers)
289 if not include_trashed:
290 l = self._filter_trashed(l)
293 def create_container(self, container, headers=None):
294 status, header, data = self.put('/' + container, headers=headers)
298 raise Fault(data, int(status))
301 def delete_container(self, container):
302 self.delete('/' + container)
304 def retrieve_container_metadata(self, container, restricted=False,
306 prefix = 'x-container-meta-' if restricted else None
307 params = {'until':until} if until else None
308 return self._get_metadata('/%s' % container, prefix, params=params)
310 def update_container_metadata(self, container, **meta):
311 self._update_metadata('/' + container, 'container', **meta)
313 def delete_container_metadata(self, container, meta=[]):
314 path = '/%s' % (container)
315 self._delete_metadata(path, 'container', meta)
317 # Storage Object Services
319 def retrieve_object(self, container, object, detail=False, headers=None,
321 path = '/%s/%s' % (container, object)
322 format = 'json' if detail else 'text'
323 params = {'version':version} if version else None
324 status, headers, data = self.get(path, format, headers, params)
327 def create_directory_marker(self, container, object):
329 raise Fault('Directory markers have to be nested in a container')
330 h = {'Content-Type':'application/directory'}
331 self.create_object(container, object, f=None, headers=h)
333 def create_object(self, container, object, f=stdin, chunked=False,
334 blocksize=1024, headers=None):
337 if f is None then creates a zero length object
338 if f is stdin or chunked is set then performs chunked transfer
340 path = '/%s/%s' % (container, object)
341 if not chunked and f != stdin:
342 data = f.read() if f else None
343 return self.put(path, data, headers=headers)
345 return self._chunked_transfer(path, 'PUT', f, headers=headers,
348 def update_object(self, container, object, f=stdin, chunked=False,
349 blocksize=1024, headers=None):
350 path = '/%s/%s' % (container, object)
351 if not chunked and f != stdin:
352 data = f.read() if f else None
353 self.post(path, data, headers=headers)
355 self._chunked_transfer(path, 'POST', f, headers=headers,
358 def _change_obj_location(self, src_container, src_object, dst_container,
359 dst_object, remove=False, headers=None):
360 path = '/%s/%s' % (dst_container, dst_object)
364 headers['X-Move-From'] = '/%s/%s' % (src_container, src_object)
366 headers['X-Copy-From'] = '/%s/%s' % (src_container, src_object)
367 headers['Content-Length'] = 0
368 self.put(path, headers=headers)
370 def copy_object(self, src_container, src_object, dst_container,
371 dst_object, headers=None):
372 self._change_obj_location(src_container, src_object,
373 dst_container, dst_object,
376 def move_object(self, src_container, src_object, dst_container,
377 dst_object, headers=None):
378 self._change_obj_location(src_container, src_object,
379 dst_container, dst_object, True, headers)
381 def delete_object(self, container, object):
382 self.delete('/%s/%s' % (container, object))
384 def retrieve_object_metadata(self, container, object, restricted=False,
386 path = '/%s/%s' % (container, object)
387 prefix = 'x-object-meta-' if restricted else None
388 params = {'version':version} if version else None
389 return self._get_metadata(path, prefix, params=params)
391 def update_object_metadata(self, container, object, **meta):
392 path = '/%s/%s' % (container, object)
393 self._update_metadata(path, 'object', **meta)
395 def delete_object_metadata(self, container, object, meta=[]):
396 path = '/%s/%s' % (container, object)
397 self._delete_metadata(path, 'object', meta)
399 def trash_object(self, container, object):
402 actually resets all object metadata with trash = true
404 path = '/%s/%s' % (container, object)
405 meta = {'trash':'true'}
406 self._update_metadata(path, 'object', **meta)
408 def restore_object(self, container, object):
410 restores a trashed object
411 actualy removes trash object metadata info
413 self.delete_object_metadata(container, object, ['trash'])