root / pithos / lib / client.py @ 6cd1831a
History | View | Annotate | Download (10.8 kB)
1 |
from httplib import HTTPConnection, HTTP |
---|---|
2 |
from sys import stdin |
3 |
|
4 |
import json |
5 |
import types |
6 |
import socket |
7 |
import pithos.api.faults |
8 |
|
9 |
ERROR_CODES = {304:'Not Modified', |
10 |
400:'Bad Request', |
11 |
401:'Unauthorized', |
12 |
404:'Not Found', |
13 |
409:'Conflict', |
14 |
411:'Length Required', |
15 |
412:'Precondition Failed', |
16 |
416:'Range Not Satisfiable', |
17 |
422:'Unprocessable Entity', |
18 |
503:'Service Unavailable'} |
19 |
|
20 |
class Fault(Exception): |
21 |
def __init__(self, data='', status=None): |
22 |
if data == '' and status in ERROR_CODES.keys(): |
23 |
data = ERROR_CODES[status] |
24 |
Exception.__init__(self, data) |
25 |
self.data = data
|
26 |
self.status = status
|
27 |
|
28 |
class Client(object): |
29 |
def __init__(self, host, account, api='v1', verbose=False, debug=False): |
30 |
"""`host` can also include a port, e.g '127.0.0.1:8000'."""
|
31 |
|
32 |
self.host = host
|
33 |
self.account = account
|
34 |
self.api = api
|
35 |
self.verbose = verbose or debug |
36 |
self.debug = debug
|
37 |
|
38 |
def _chunked_transfer(self, path, method='PUT', f=stdin, headers=None, |
39 |
blocksize=1024):
|
40 |
http = HTTPConnection(self.host)
|
41 |
|
42 |
# write header
|
43 |
path = '/%s/%s%s' % (self.api, self.account, path) |
44 |
http.putrequest(method, path) |
45 |
http.putheader('Content-Type', 'application/octet-stream') |
46 |
http.putheader('Transfer-Encoding', 'chunked') |
47 |
if headers:
|
48 |
for header,value in headers.items(): |
49 |
http.putheader(header, value) |
50 |
http.endheaders() |
51 |
|
52 |
# write body
|
53 |
data = ''
|
54 |
while True: |
55 |
if f.closed:
|
56 |
break
|
57 |
block = f.read(blocksize) |
58 |
if block == '': |
59 |
break
|
60 |
data = '%s\r\n%s\r\n' % (hex(len(block)), block) |
61 |
try:
|
62 |
http.send(data) |
63 |
except:
|
64 |
#retry
|
65 |
http.send(data) |
66 |
data = '0x0\r\n'
|
67 |
try:
|
68 |
http.send(data) |
69 |
except:
|
70 |
#retry
|
71 |
http.send(data) |
72 |
|
73 |
# get response
|
74 |
resp = http.getresponse() |
75 |
|
76 |
headers = dict(resp.getheaders())
|
77 |
|
78 |
if self.verbose: |
79 |
print '%d %s' % (resp.status, resp.reason) |
80 |
for key, val in headers.items(): |
81 |
print '%s: %s' % (key.capitalize(), val) |
82 |
print
|
83 |
|
84 |
length = hasattr(headers, 'Content-length') \ |
85 |
and headers['Content-length'] or None |
86 |
|
87 |
data = resp.read(length) |
88 |
if self.debug: |
89 |
print data
|
90 |
print
|
91 |
|
92 |
if int(resp.status) in ERROR_CODES.keys(): |
93 |
raise Fault(data, int(resp.status)) |
94 |
|
95 |
return resp.status, headers, data
|
96 |
|
97 |
def req(self, method, path, body=None, headers=None, format='text', |
98 |
params=None):
|
99 |
full_path = '/%s/%s%s?format=%s' % (self.api, self.account, path, |
100 |
format) |
101 |
if params:
|
102 |
for k,v in params.items(): |
103 |
if v:
|
104 |
full_path = '%s&%s=%s' %(full_path, k, v)
|
105 |
conn = HTTPConnection(self.host)
|
106 |
|
107 |
#encode whitespace
|
108 |
full_path = full_path.replace(' ', '%20') |
109 |
|
110 |
kwargs = {} |
111 |
kwargs['headers'] = headers or {} |
112 |
if not headers or \ |
113 |
'Transfer-Encoding' not in headers \ |
114 |
or headers['Transfer-Encoding'] != 'chunked': |
115 |
kwargs['headers']['Content-Length'] = len(body) if body else 0 |
116 |
if body:
|
117 |
kwargs['body'] = body
|
118 |
kwargs['headers']['Content-Type'] = 'application/octet-stream' |
119 |
#print '****', method, full_path, kwargs
|
120 |
try:
|
121 |
conn.request(method, full_path, **kwargs) |
122 |
except socket.error, e:
|
123 |
raise Fault(status=503) |
124 |
|
125 |
resp = conn.getresponse() |
126 |
headers = dict(resp.getheaders())
|
127 |
|
128 |
if self.verbose: |
129 |
print '%d %s' % (resp.status, resp.reason) |
130 |
for key, val in headers.items(): |
131 |
print '%s: %s' % (key.capitalize(), val) |
132 |
print
|
133 |
|
134 |
length = hasattr(headers, 'Content-length') \ |
135 |
and headers['Content-length'] or None |
136 |
|
137 |
data = resp.read(length) |
138 |
if self.debug: |
139 |
print data
|
140 |
print
|
141 |
|
142 |
if int(resp.status) in ERROR_CODES.keys(): |
143 |
raise Fault(data, int(resp.status)) |
144 |
|
145 |
#print '*', resp.status, headers, data
|
146 |
return resp.status, headers, data
|
147 |
|
148 |
def delete(self, path, format='text'): |
149 |
return self.req('DELETE', path, format=format) |
150 |
|
151 |
def get(self, path, format='text', headers=None, params=None): |
152 |
return self.req('GET', path, headers=headers, format=format, |
153 |
params=params) |
154 |
|
155 |
def head(self, path, format='text', params=None): |
156 |
return self.req('HEAD', path, format=format, params=params) |
157 |
|
158 |
def post(self, path, body=None, format='text', headers=None): |
159 |
return self.req('POST', path, body, headers=headers, format=format) |
160 |
|
161 |
def put(self, path, body=None, format='text', headers=None): |
162 |
return self.req('PUT', path, body, headers=headers, format=format) |
163 |
|
164 |
def _list(self, path, detail=False, params=None, headers=None): |
165 |
format = 'json' if detail else 'text' |
166 |
status, headers, data = self.get(path, format=format, headers=headers,
|
167 |
params=params) |
168 |
if detail:
|
169 |
data = json.loads(data) |
170 |
else:
|
171 |
data = data.strip().split('\n')
|
172 |
return data
|
173 |
|
174 |
def _get_metadata(self, path, prefix=None, params=None): |
175 |
status, headers, data = self.head(path, params=params)
|
176 |
prefixlen = prefix and len(prefix) or 0 |
177 |
meta = {} |
178 |
for key, val in headers.items(): |
179 |
if prefix and not key.startswith(prefix): |
180 |
continue
|
181 |
elif prefix and key.startswith(prefix): |
182 |
key = key[prefixlen:] |
183 |
meta[key] = val |
184 |
return meta
|
185 |
|
186 |
def _set_metadata(self, path, entity, **meta): |
187 |
headers = {} |
188 |
for key, val in meta.items(): |
189 |
http_key = 'X-%s-Meta-%s' %(entity.capitalize(), key.capitalize())
|
190 |
headers[http_key] = val |
191 |
self.post(path, headers=headers)
|
192 |
|
193 |
# Storage Account Services
|
194 |
|
195 |
def list_containers(self, detail=False, params=None, headers=None): |
196 |
return self._list('', detail, params, headers) |
197 |
|
198 |
def account_metadata(self, restricted=False, until=None): |
199 |
prefix = restricted and 'x-account-meta-' or None |
200 |
params = until and {'until':until} or None |
201 |
return self._get_metadata('', prefix, params=params) |
202 |
|
203 |
def update_account_metadata(self, **meta): |
204 |
self._set_metadata('', 'account', **meta) |
205 |
|
206 |
# Storage Container Services
|
207 |
|
208 |
def list_objects(self, container, detail=False, params=None, headers=None): |
209 |
return self._list('/' + container, detail, params, headers) |
210 |
|
211 |
def create_container(self, container, headers=None): |
212 |
status, header, data = self.put('/' + container, headers=headers) |
213 |
if status == 202: |
214 |
return False |
215 |
elif status != 201: |
216 |
raise Fault(data, int(status)) |
217 |
return True |
218 |
|
219 |
def delete_container(self, container): |
220 |
self.delete('/' + container) |
221 |
|
222 |
def retrieve_container_metadata(self, container, restricted=False, |
223 |
until=None):
|
224 |
prefix = restricted and 'x-container-meta-' or None |
225 |
params = until and {'until':until} or None |
226 |
return self._get_metadata('/%s' % container, prefix, params=params) |
227 |
|
228 |
def update_container_metadata(self, container, **meta): |
229 |
self._set_metadata('/' + container, 'container', **meta) |
230 |
|
231 |
# Storage Object Services
|
232 |
|
233 |
def retrieve_object(self, container, object, detail=False, headers=None, |
234 |
version=None):
|
235 |
path = '/%s/%s' % (container, object) |
236 |
format = 'json' if detail else 'text' |
237 |
params = version and {'version':version} or None |
238 |
status, headers, data = self.get(path, format, headers, params)
|
239 |
return data
|
240 |
|
241 |
def create_object(self, container, object, f=stdin, chunked=False, |
242 |
blocksize=1024, headers=None): |
243 |
"""
|
244 |
creates an object
|
245 |
if f is None then creates a zero length object
|
246 |
if f is stdin or chunked is set then performs chunked transfer
|
247 |
"""
|
248 |
path = '/%s/%s' % (container, object) |
249 |
if not chunked and f != stdin: |
250 |
data = f and f.read() or None |
251 |
return self.put(path, data, headers=headers) |
252 |
else:
|
253 |
return self._chunked_transfer(path, 'PUT', f, headers=headers, |
254 |
blocksize=1024)
|
255 |
|
256 |
def update_object(self, container, object, f=stdin, chunked=False, |
257 |
blocksize=1024, headers=None): |
258 |
if not f: |
259 |
return
|
260 |
path = '/%s/%s' % (container, object) |
261 |
if not chunked and f != stdin: |
262 |
data = f.read() |
263 |
self.post(path, data, headers=headers)
|
264 |
else:
|
265 |
self._chunked_transfer(path, 'POST', f, headers=headers, |
266 |
blocksize=1024)
|
267 |
|
268 |
def _change_obj_location(self, src_container, src_object, dst_container, |
269 |
dst_object, remove=False, headers=None): |
270 |
path = '/%s/%s' % (dst_container, dst_object)
|
271 |
if not headers: |
272 |
headers = {} |
273 |
if remove:
|
274 |
headers['X-Move-From'] = '/%s/%s' % (src_container, src_object) |
275 |
else:
|
276 |
headers['X-Copy-From'] = '/%s/%s' % (src_container, src_object) |
277 |
headers['Content-Length'] = 0 |
278 |
self.put(path, headers=headers)
|
279 |
|
280 |
def copy_object(self, src_container, src_object, dst_container, |
281 |
dst_object, headers=None):
|
282 |
self._change_obj_location(src_container, src_object,
|
283 |
dst_container, dst_object, |
284 |
headers=headers) |
285 |
|
286 |
def move_object(self, src_container, src_object, dst_container, |
287 |
dst_object, headers=None):
|
288 |
self._change_obj_location(src_container, src_object,
|
289 |
dst_container, dst_object, True, headers)
|
290 |
|
291 |
def delete_object(self, container, object): |
292 |
self.delete('/%s/%s' % (container, object)) |
293 |
|
294 |
def retrieve_object_metadata(self, container, object, restricted=False, |
295 |
version=None):
|
296 |
path = '/%s/%s' % (container, object) |
297 |
prefix = restricted and 'x-object-meta-' or None |
298 |
params = version and {'version':version} or None |
299 |
return self._get_metadata(path, prefix, params=params) |
300 |
|
301 |
def update_object_metadata(self, container, object, **meta): |
302 |
path = '/%s/%s' % (container, object) |
303 |
self._set_metadata(path, 'object', **meta) |