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