root / pithos / api / util.py @ cb146cf9
History | View | Annotate | Download (23.7 kB)
1 |
# Copyright 2011 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 |
from functools import wraps |
35 |
from time import time |
36 |
from traceback import format_exc |
37 |
from wsgiref.handlers import format_date_time |
38 |
from binascii import hexlify |
39 |
|
40 |
from django.conf import settings |
41 |
from django.http import HttpResponse |
42 |
from django.utils.http import http_date, parse_etags |
43 |
|
44 |
from pithos.api.compat import parse_http_date_safe |
45 |
from pithos.api.faults import (Fault, NotModified, BadRequest, ItemNotFound, LengthRequired, |
46 |
PreconditionFailed, RangeNotSatisfiable, ServiceUnavailable) |
47 |
from pithos.backends import backend |
48 |
|
49 |
import datetime |
50 |
import logging |
51 |
import re |
52 |
import hashlib |
53 |
import uuid |
54 |
|
55 |
|
56 |
logger = logging.getLogger(__name__) |
57 |
|
58 |
|
59 |
def printable_meta_dict(d): |
60 |
"""Format a meta dictionary for printing out json/xml.
|
61 |
|
62 |
Convert all keys to lower case and replace dashes to underscores.
|
63 |
Change 'modified' key from backend to 'last_modified' and format date.
|
64 |
"""
|
65 |
|
66 |
if 'modified' in d: |
67 |
d['last_modified'] = datetime.datetime.fromtimestamp(int(d['modified'])).isoformat() |
68 |
del(d['modified']) |
69 |
return dict([(k.lower().replace('-', '_'), v) for k, v in d.iteritems()]) |
70 |
|
71 |
def format_meta_key(k): |
72 |
"""Convert underscores to dashes and capitalize intra-dash strings."""
|
73 |
|
74 |
return '-'.join([x.capitalize() for x in k.replace('_', '-').split('-')]) |
75 |
|
76 |
def get_meta_prefix(request, prefix): |
77 |
"""Get all prefix-* request headers in a dict. Reformat keys with format_meta_key()."""
|
78 |
|
79 |
prefix = 'HTTP_' + prefix.upper().replace('-', '_') |
80 |
return dict([(format_meta_key(k[5:]), v) for k, v in request.META.iteritems() if k.startswith(prefix)]) |
81 |
|
82 |
def get_account_meta(request): |
83 |
"""Get metadata from an account request."""
|
84 |
|
85 |
meta = get_meta_prefix(request, 'X-Account-Meta-')
|
86 |
return meta
|
87 |
|
88 |
def put_account_meta(response, meta): |
89 |
"""Put metadata in an account response."""
|
90 |
|
91 |
response['X-Account-Container-Count'] = meta['count'] |
92 |
response['X-Account-Bytes-Used'] = meta['bytes'] |
93 |
if 'modified' in meta: |
94 |
response['Last-Modified'] = http_date(int(meta['modified'])) |
95 |
for k in [x for x in meta.keys() if x.startswith('X-Account-Meta-')]: |
96 |
response[k.encode('utf-8')] = meta[k].encode('utf-8') |
97 |
if 'until_timestamp' in meta: |
98 |
response['X-Account-Until-Timestamp'] = http_date(int(meta['until_timestamp'])) |
99 |
|
100 |
def get_container_meta(request): |
101 |
"""Get metadata from a container request."""
|
102 |
|
103 |
meta = get_meta_prefix(request, 'X-Container-Meta-')
|
104 |
return meta
|
105 |
|
106 |
def put_container_meta(response, meta): |
107 |
"""Put metadata in a container response."""
|
108 |
|
109 |
response['X-Container-Object-Count'] = meta['count'] |
110 |
response['X-Container-Bytes-Used'] = meta['bytes'] |
111 |
response['Last-Modified'] = http_date(int(meta['modified'])) |
112 |
for k in [x for x in meta.keys() if x.startswith('X-Container-Meta-')]: |
113 |
response[k.encode('utf-8')] = meta[k].encode('utf-8') |
114 |
response['X-Container-Object-Meta'] = [x[14:] for x in meta['object_meta'] if x.startswith('X-Object-Meta-')] |
115 |
response['X-Container-Block-Size'] = backend.block_size
|
116 |
response['X-Container-Block-Hash'] = backend.hash_algorithm
|
117 |
if 'until_timestamp' in meta: |
118 |
response['X-Container-Until-Timestamp'] = http_date(int(meta['until_timestamp'])) |
119 |
|
120 |
def get_object_meta(request): |
121 |
"""Get metadata from an object request."""
|
122 |
|
123 |
meta = get_meta_prefix(request, 'X-Object-Meta-')
|
124 |
if request.META.get('CONTENT_TYPE'): |
125 |
meta['Content-Type'] = request.META['CONTENT_TYPE'] |
126 |
if request.META.get('HTTP_CONTENT_ENCODING'): |
127 |
meta['Content-Encoding'] = request.META['HTTP_CONTENT_ENCODING'] |
128 |
if request.META.get('HTTP_CONTENT_DISPOSITION'): |
129 |
meta['Content-Disposition'] = request.META['HTTP_CONTENT_DISPOSITION'] |
130 |
if request.META.get('HTTP_X_OBJECT_MANIFEST'): |
131 |
meta['X-Object-Manifest'] = request.META['HTTP_X_OBJECT_MANIFEST'] |
132 |
if request.META.get('HTTP_X_OBJECT_PUBLIC'): |
133 |
meta['X-Object-Public'] = request.META['HTTP_X_OBJECT_PUBLIC'] |
134 |
return meta
|
135 |
|
136 |
def put_object_meta(response, meta, public=False): |
137 |
"""Put metadata in an object response."""
|
138 |
|
139 |
response['ETag'] = meta['hash'] |
140 |
response['Content-Length'] = meta['bytes'] |
141 |
response['Content-Type'] = meta.get('Content-Type', 'application/octet-stream') |
142 |
response['Last-Modified'] = http_date(int(meta['modified'])) |
143 |
if not public: |
144 |
response['X-Object-Version'] = meta['version'] |
145 |
response['X-Object-Version-Timestamp'] = meta['version_timestamp'] |
146 |
for k in [x for x in meta.keys() if x.startswith('X-Object-Meta-')]: |
147 |
response[k.encode('utf-8')] = meta[k].encode('utf-8') |
148 |
for k in ('Content-Encoding', 'Content-Disposition', 'X-Object-Manifest', 'X-Object-Public'): |
149 |
if k in meta: |
150 |
response[k] = meta[k] |
151 |
else:
|
152 |
for k in ('Content-Encoding', 'Content-Disposition'): |
153 |
if k in meta: |
154 |
response[k] = meta[k] |
155 |
|
156 |
def update_manifest_meta(request, v_account, meta): |
157 |
"""Update metadata if the object has an X-Object-Manifest."""
|
158 |
|
159 |
if 'X-Object-Manifest' in meta: |
160 |
hash = ''
|
161 |
bytes = 0
|
162 |
try:
|
163 |
src_container, src_name = split_container_object_string('/' + meta['X-Object-Manifest']) |
164 |
objects = backend.list_objects(request.user, v_account, src_container, prefix=src_name, virtual=False)
|
165 |
for x in objects: |
166 |
src_meta = backend.get_object_meta(request.user, v_account, src_container, x[0], x[1]) |
167 |
hash += src_meta['hash'] |
168 |
bytes += src_meta['bytes'] |
169 |
except:
|
170 |
# Ignore errors.
|
171 |
return
|
172 |
meta['bytes'] = bytes |
173 |
md5 = hashlib.md5() |
174 |
md5.update(hash)
|
175 |
meta['hash'] = md5.hexdigest().lower()
|
176 |
|
177 |
def validate_modification_preconditions(request, meta): |
178 |
"""Check that the modified timestamp conforms with the preconditions set."""
|
179 |
|
180 |
if 'modified' not in meta: |
181 |
return # TODO: Always return? |
182 |
|
183 |
if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE')
|
184 |
if if_modified_since is not None: |
185 |
if_modified_since = parse_http_date_safe(if_modified_since) |
186 |
if if_modified_since is not None and int(meta['modified']) <= if_modified_since: |
187 |
raise NotModified('Resource has not been modified') |
188 |
|
189 |
if_unmodified_since = request.META.get('HTTP_IF_UNMODIFIED_SINCE')
|
190 |
if if_unmodified_since is not None: |
191 |
if_unmodified_since = parse_http_date_safe(if_unmodified_since) |
192 |
if if_unmodified_since is not None and int(meta['modified']) > if_unmodified_since: |
193 |
raise PreconditionFailed('Resource has been modified') |
194 |
|
195 |
def validate_matching_preconditions(request, meta): |
196 |
"""Check that the ETag conforms with the preconditions set."""
|
197 |
|
198 |
if 'hash' not in meta: |
199 |
return # TODO: Always return? |
200 |
|
201 |
if_match = request.META.get('HTTP_IF_MATCH')
|
202 |
if if_match is not None and if_match != '*': |
203 |
if meta['hash'] not in [x.lower() for x in parse_etags(if_match)]: |
204 |
raise PreconditionFailed('Resource Etag does not match') |
205 |
|
206 |
if_none_match = request.META.get('HTTP_IF_NONE_MATCH')
|
207 |
if if_none_match is not None: |
208 |
if if_none_match == '*' or meta['hash'] in [x.lower() for x in parse_etags(if_none_match)]: |
209 |
raise NotModified('Resource Etag matches') |
210 |
|
211 |
def split_container_object_string(s): |
212 |
if not len(s) > 0 or s[0] != '/': |
213 |
raise ValueError |
214 |
s = s[1:]
|
215 |
pos = s.find('/')
|
216 |
if pos == -1: |
217 |
raise ValueError |
218 |
return s[:pos], s[(pos + 1):] |
219 |
|
220 |
def copy_or_move_object(request, v_account, src_container, src_name, dest_container, dest_name, move=False): |
221 |
"""Copy or move an object."""
|
222 |
|
223 |
meta = get_object_meta(request) |
224 |
# Keep previous values of 'Content-Type' (if a new one is absent) and 'hash'.
|
225 |
try:
|
226 |
src_meta = backend.get_object_meta(request.user, v_account, src_container, src_name) |
227 |
except NameError: |
228 |
raise ItemNotFound('Container or object does not exist') |
229 |
if 'Content-Type' in meta and 'Content-Type' in src_meta: |
230 |
del(src_meta['Content-Type']) |
231 |
for k in ('Content-Type', 'hash'): |
232 |
if k in src_meta: |
233 |
meta[k] = src_meta[k] |
234 |
|
235 |
try:
|
236 |
if move:
|
237 |
backend.move_object(request.user, v_account, src_container, src_name, dest_container, dest_name, meta, True)
|
238 |
else:
|
239 |
src_version = request.META.get('HTTP_X_SOURCE_VERSION')
|
240 |
backend.copy_object(request.user, v_account, src_container, src_name, dest_container, dest_name, meta, True, src_version)
|
241 |
except NameError: |
242 |
raise ItemNotFound('Container or object does not exist') |
243 |
|
244 |
def get_int_parameter(request, name): |
245 |
p = request.GET.get(name) |
246 |
if p is not None: |
247 |
try:
|
248 |
p = int(p)
|
249 |
except ValueError: |
250 |
return None |
251 |
if p < 0: |
252 |
return None |
253 |
return p
|
254 |
|
255 |
def get_content_length(request): |
256 |
content_length = request.META.get('CONTENT_LENGTH')
|
257 |
if not content_length: |
258 |
raise LengthRequired('Missing Content-Length header') |
259 |
try:
|
260 |
content_length = int(content_length)
|
261 |
if content_length < 0: |
262 |
raise ValueError |
263 |
except ValueError: |
264 |
raise BadRequest('Invalid Content-Length header') |
265 |
return content_length
|
266 |
|
267 |
def get_range(request, size): |
268 |
"""Parse a Range header from the request.
|
269 |
|
270 |
Either returns None, when the header is not existent or should be ignored,
|
271 |
or a list of (offset, length) tuples - should be further checked.
|
272 |
"""
|
273 |
|
274 |
ranges = request.META.get('HTTP_RANGE', '').replace(' ', '') |
275 |
if not ranges.startswith('bytes='): |
276 |
return None |
277 |
|
278 |
ret = [] |
279 |
for r in (x.strip() for x in ranges[6:].split(',')): |
280 |
p = re.compile('^(?P<offset>\d*)-(?P<upto>\d*)$')
|
281 |
m = p.match(r) |
282 |
if not m: |
283 |
return None |
284 |
offset = m.group('offset')
|
285 |
upto = m.group('upto')
|
286 |
if offset == '' and upto == '': |
287 |
return None |
288 |
|
289 |
if offset != '': |
290 |
offset = int(offset)
|
291 |
if upto != '': |
292 |
upto = int(upto)
|
293 |
if offset > upto:
|
294 |
return None |
295 |
ret.append((offset, upto - offset + 1))
|
296 |
else:
|
297 |
ret.append((offset, size - offset)) |
298 |
else:
|
299 |
length = int(upto)
|
300 |
ret.append((size - length, length)) |
301 |
|
302 |
return ret
|
303 |
|
304 |
def get_content_range(request): |
305 |
"""Parse a Content-Range header from the request.
|
306 |
|
307 |
Either returns None, when the header is not existent or should be ignored,
|
308 |
or an (offset, length, total) tuple - check as length, total may be None.
|
309 |
Returns (None, None, None) if the provided range is '*/*'.
|
310 |
"""
|
311 |
|
312 |
ranges = request.META.get('HTTP_CONTENT_RANGE', '') |
313 |
if not ranges: |
314 |
return None |
315 |
|
316 |
p = re.compile('^bytes (?P<offset>\d+)-(?P<upto>\d*)/(?P<total>(\d+|\*))$')
|
317 |
m = p.match(ranges) |
318 |
if not m: |
319 |
if ranges == 'bytes */*': |
320 |
return (None, None, None) |
321 |
return None |
322 |
offset = int(m.group('offset')) |
323 |
upto = m.group('upto')
|
324 |
total = m.group('total')
|
325 |
if upto != '': |
326 |
upto = int(upto)
|
327 |
else:
|
328 |
upto = None
|
329 |
if total != '*': |
330 |
total = int(total)
|
331 |
else:
|
332 |
total = None
|
333 |
if (upto is not None and offset > upto) or \ |
334 |
(total is not None and offset >= total) or \ |
335 |
(total is not None and upto is not None and upto >= total): |
336 |
return None |
337 |
|
338 |
if upto is None: |
339 |
length = None
|
340 |
else:
|
341 |
length = upto - offset + 1
|
342 |
return (offset, length, total)
|
343 |
|
344 |
def raw_input_socket(request): |
345 |
"""Return the socket for reading the rest of the request."""
|
346 |
|
347 |
server_software = request.META.get('SERVER_SOFTWARE')
|
348 |
if not server_software: |
349 |
if 'wsgi.input' in request.environ: |
350 |
return request.environ['wsgi.input'] |
351 |
raise ServiceUnavailable('Unknown server software') |
352 |
if server_software.startswith('WSGIServer'): |
353 |
return request.environ['wsgi.input'] |
354 |
elif server_software.startswith('mod_python'): |
355 |
return request._req
|
356 |
raise ServiceUnavailable('Unknown server software') |
357 |
|
358 |
MAX_UPLOAD_SIZE = 10 * (1024 * 1024) # 10MB |
359 |
|
360 |
def socket_read_iterator(sock, length=0, blocksize=4096): |
361 |
"""Return a maximum of blocksize data read from the socket in each iteration.
|
362 |
|
363 |
Read up to 'length'. If 'length' is negative, will attempt a chunked read.
|
364 |
The maximum ammount of data read is controlled by MAX_UPLOAD_SIZE.
|
365 |
"""
|
366 |
|
367 |
if length < 0: # Chunked transfers |
368 |
data = ''
|
369 |
while length < MAX_UPLOAD_SIZE:
|
370 |
# Get chunk size.
|
371 |
if hasattr(sock, 'readline'): |
372 |
chunk_length = sock.readline() |
373 |
else:
|
374 |
chunk_length = ''
|
375 |
while chunk_length[-1:] != '\n': |
376 |
chunk_length += sock.read(1)
|
377 |
chunk_length.strip() |
378 |
pos = chunk_length.find(';')
|
379 |
if pos >= 0: |
380 |
chunk_length = chunk_length[:pos] |
381 |
try:
|
382 |
chunk_length = int(chunk_length, 16) |
383 |
except Exception, e: |
384 |
raise BadRequest('Bad chunk size') # TODO: Change to something more appropriate. |
385 |
# Check if done.
|
386 |
if chunk_length == 0: |
387 |
if len(data) > 0: |
388 |
yield data
|
389 |
return
|
390 |
# Get the actual data.
|
391 |
while chunk_length > 0: |
392 |
chunk = sock.read(min(chunk_length, blocksize))
|
393 |
chunk_length -= len(chunk)
|
394 |
if length > 0: |
395 |
length += len(chunk)
|
396 |
data += chunk |
397 |
if len(data) >= blocksize: |
398 |
ret = data[:blocksize] |
399 |
data = data[blocksize:] |
400 |
yield ret
|
401 |
sock.read(2) # CRLF |
402 |
# TODO: Raise something to note that maximum size is reached.
|
403 |
else:
|
404 |
if length > MAX_UPLOAD_SIZE:
|
405 |
# TODO: Raise something to note that maximum size is reached.
|
406 |
pass
|
407 |
while length > 0: |
408 |
data = sock.read(min(length, blocksize))
|
409 |
length -= len(data)
|
410 |
yield data
|
411 |
|
412 |
class ObjectWrapper(object): |
413 |
"""Return the object's data block-per-block in each iteration.
|
414 |
|
415 |
Read from the object using the offset and length provided in each entry of the range list.
|
416 |
"""
|
417 |
|
418 |
def __init__(self, ranges, sizes, hashmaps, boundary): |
419 |
self.ranges = ranges
|
420 |
self.sizes = sizes
|
421 |
self.hashmaps = hashmaps
|
422 |
self.boundary = boundary
|
423 |
self.size = sum(self.sizes) |
424 |
|
425 |
self.file_index = 0 |
426 |
self.block_index = 0 |
427 |
self.block_hash = -1 |
428 |
self.block = '' |
429 |
|
430 |
self.range_index = -1 |
431 |
self.offset, self.length = self.ranges[0] |
432 |
|
433 |
def __iter__(self): |
434 |
return self |
435 |
|
436 |
def part_iterator(self): |
437 |
if self.length > 0: |
438 |
# Get the file for the current offset.
|
439 |
file_size = self.sizes[self.file_index] |
440 |
while self.offset >= file_size: |
441 |
self.offset -= file_size
|
442 |
self.file_index += 1 |
443 |
file_size = self.sizes[self.file_index] |
444 |
|
445 |
# Get the block for the current position.
|
446 |
self.block_index = int(self.offset / backend.block_size) |
447 |
if self.block_hash != self.hashmaps[self.file_index][self.block_index]: |
448 |
self.block_hash = self.hashmaps[self.file_index][self.block_index] |
449 |
try:
|
450 |
self.block = backend.get_block(self.block_hash) |
451 |
except NameError: |
452 |
raise ItemNotFound('Block does not exist') |
453 |
|
454 |
# Get the data from the block.
|
455 |
bo = self.offset % backend.block_size
|
456 |
bl = min(self.length, len(self.block) - bo) |
457 |
data = self.block[bo:bo + bl]
|
458 |
self.offset += bl
|
459 |
self.length -= bl
|
460 |
return data
|
461 |
else:
|
462 |
raise StopIteration |
463 |
|
464 |
def next(self): |
465 |
if len(self.ranges) == 1: |
466 |
return self.part_iterator() |
467 |
if self.range_index == len(self.ranges): |
468 |
raise StopIteration |
469 |
try:
|
470 |
if self.range_index == -1: |
471 |
raise StopIteration |
472 |
return self.part_iterator() |
473 |
except StopIteration: |
474 |
self.range_index += 1 |
475 |
out = [] |
476 |
if self.range_index < len(self.ranges): |
477 |
# Part header.
|
478 |
self.offset, self.length = self.ranges[self.range_index] |
479 |
self.file_index = 0 |
480 |
if self.range_index > 0: |
481 |
out.append('')
|
482 |
out.append('--' + self.boundary) |
483 |
out.append('Content-Range: bytes %d-%d/%d' % (self.offset, self.offset + self.length - 1, self.size)) |
484 |
out.append('Content-Transfer-Encoding: binary')
|
485 |
out.append('')
|
486 |
out.append('')
|
487 |
return '\r\n'.join(out) |
488 |
else:
|
489 |
# Footer.
|
490 |
out.append('')
|
491 |
out.append('--' + self.boundary + '--') |
492 |
out.append('')
|
493 |
return '\r\n'.join(out) |
494 |
|
495 |
def object_data_response(request, sizes, hashmaps, meta, public=False): |
496 |
"""Get the HttpResponse object for replying with the object's data."""
|
497 |
|
498 |
# Range handling.
|
499 |
size = sum(sizes)
|
500 |
ranges = get_range(request, size) |
501 |
if ranges is None: |
502 |
ranges = [(0, size)]
|
503 |
ret = 200
|
504 |
else:
|
505 |
check = [True for offset, length in ranges if |
506 |
length <= 0 or length > size or |
507 |
offset < 0 or offset >= size or |
508 |
offset + length > size] |
509 |
if len(check) > 0: |
510 |
raise RangeNotSatisfiable('Requested range exceeds object limits') |
511 |
ret = 206
|
512 |
|
513 |
if ret == 206 and len(ranges) > 1: |
514 |
boundary = uuid.uuid4().hex |
515 |
else:
|
516 |
boundary = ''
|
517 |
wrapper = ObjectWrapper(ranges, sizes, hashmaps, boundary) |
518 |
response = HttpResponse(wrapper, status=ret) |
519 |
put_object_meta(response, meta, public) |
520 |
if ret == 206: |
521 |
if len(ranges) == 1: |
522 |
offset, length = ranges[0]
|
523 |
response['Content-Length'] = length # Update with the correct length. |
524 |
response['Content-Range'] = 'bytes %d-%d/%d' % (offset, offset + length - 1, size) |
525 |
else:
|
526 |
del(response['Content-Length']) |
527 |
response['Content-Type'] = 'multipart/byteranges; boundary=%s' % (boundary,) |
528 |
return response
|
529 |
|
530 |
def put_object_block(hashmap, data, offset): |
531 |
"""Put one block of data at the given offset."""
|
532 |
|
533 |
bi = int(offset / backend.block_size)
|
534 |
bo = offset % backend.block_size |
535 |
bl = min(len(data), backend.block_size - bo) |
536 |
if bi < len(hashmap): |
537 |
hashmap[bi] = backend.update_block(hashmap[bi], data[:bl], bo) |
538 |
else:
|
539 |
hashmap.append(backend.put_block(('\x00' * bo) + data[:bl]))
|
540 |
return bl # Return ammount of data written. |
541 |
|
542 |
def hashmap_hash(hashmap): |
543 |
"""Produce the root hash, treating the hashmap as a Merkle-like tree."""
|
544 |
|
545 |
def subhash(d): |
546 |
h = hashlib.new(backend.hash_algorithm) |
547 |
h.update(d) |
548 |
return h.digest()
|
549 |
|
550 |
if len(hashmap) == 0: |
551 |
return hexlify(subhash('')) |
552 |
if len(hashmap) == 1: |
553 |
return hexlify(subhash(hashmap[0])) |
554 |
s = 2
|
555 |
while s < len(hashmap): |
556 |
s = s * 2
|
557 |
h = hashmap + ([('\x00' * len(hashmap[0]))] * (s - len(hashmap))) |
558 |
h = [subhash(h[x] + (h[x + 1] if x + 1 < len(h) else '')) for x in range(0, len(h), 2)] |
559 |
while len(h) > 1: |
560 |
h = [subhash(h[x] + (h[x + 1] if x + 1 < len(h) else '')) for x in range(0, len(h), 2)] |
561 |
return hexlify(h[0]) |
562 |
|
563 |
def update_response_headers(request, response): |
564 |
if request.serialization == 'xml': |
565 |
response['Content-Type'] = 'application/xml; charset=UTF-8' |
566 |
elif request.serialization == 'json': |
567 |
response['Content-Type'] = 'application/json; charset=UTF-8' |
568 |
elif not response['Content-Type']: |
569 |
response['Content-Type'] = 'text/plain; charset=UTF-8' |
570 |
|
571 |
if settings.TEST:
|
572 |
response['Date'] = format_date_time(time())
|
573 |
|
574 |
def render_fault(request, fault): |
575 |
if settings.DEBUG or settings.TEST: |
576 |
fault.details = format_exc(fault) |
577 |
|
578 |
request.serialization = 'text'
|
579 |
data = '\n'.join((fault.message, fault.details)) + '\n' |
580 |
response = HttpResponse(data, status=fault.code) |
581 |
update_response_headers(request, response) |
582 |
return response
|
583 |
|
584 |
def request_serialization(request, format_allowed=False): |
585 |
"""Return the serialization format requested.
|
586 |
|
587 |
Valid formats are 'text' and 'json', 'xml' if 'format_allowed' is True.
|
588 |
"""
|
589 |
|
590 |
if not format_allowed: |
591 |
return 'text' |
592 |
|
593 |
format = request.GET.get('format')
|
594 |
if format == 'json': |
595 |
return 'json' |
596 |
elif format == 'xml': |
597 |
return 'xml' |
598 |
|
599 |
for item in request.META.get('HTTP_ACCEPT', '').split(','): |
600 |
accept, sep, rest = item.strip().partition(';')
|
601 |
if accept == 'application/json': |
602 |
return 'json' |
603 |
elif accept == 'application/xml' or accept == 'text/xml': |
604 |
return 'xml' |
605 |
|
606 |
return 'text' |
607 |
|
608 |
def api_method(http_method=None, format_allowed=False): |
609 |
"""Decorator function for views that implement an API method."""
|
610 |
|
611 |
def decorator(func): |
612 |
@wraps(func)
|
613 |
def wrapper(request, *args, **kwargs): |
614 |
try:
|
615 |
if http_method and request.method != http_method: |
616 |
raise BadRequest('Method not allowed.') |
617 |
|
618 |
# The args variable may contain up to (account, container, object).
|
619 |
if len(args) > 1 and len(args[1]) > 256: |
620 |
raise BadRequest('Container name too large.') |
621 |
if len(args) > 2 and len(args[2]) > 1024: |
622 |
raise BadRequest('Object name too large.') |
623 |
|
624 |
# Fill in custom request variables.
|
625 |
request.serialization = request_serialization(request, format_allowed) |
626 |
# TODO: Authenticate.
|
627 |
request.user = "test"
|
628 |
|
629 |
response = func(request, *args, **kwargs) |
630 |
update_response_headers(request, response) |
631 |
return response
|
632 |
except Fault, fault:
|
633 |
return render_fault(request, fault)
|
634 |
except BaseException, e: |
635 |
logger.exception('Unexpected error: %s' % e)
|
636 |
fault = ServiceUnavailable('Unexpected error')
|
637 |
return render_fault(request, fault)
|
638 |
return wrapper
|
639 |
return decorator
|