root / snf-pithos-app / pithos / api / util.py @ 890c2065
History | View | Annotate | Download (39.8 kB)
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 |
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, unhexlify |
39 |
from datetime import datetime, tzinfo, timedelta |
40 |
from urllib import quote, unquote |
41 |
|
42 |
from django.conf import settings |
43 |
from django.http import HttpResponse |
44 |
from django.template.loader import render_to_string |
45 |
from django.utils import simplejson as json |
46 |
from django.utils.http import http_date, parse_etags |
47 |
from django.utils.encoding import smart_unicode, smart_str |
48 |
from django.core.files.uploadhandler import FileUploadHandler |
49 |
from django.core.files.uploadedfile import UploadedFile |
50 |
|
51 |
from synnefo.lib.parsedate import parse_http_date_safe, parse_http_date |
52 |
from synnefo.lib.astakos import get_user |
53 |
|
54 |
from pithos.api.faults import ( |
55 |
Fault, NotModified, BadRequest, Unauthorized, Forbidden, ItemNotFound, |
56 |
Conflict, LengthRequired, PreconditionFailed, RequestEntityTooLarge, |
57 |
RangeNotSatisfiable, InternalServerError, NotImplemented)
|
58 |
from pithos.api.short_url import encode_url |
59 |
from pithos.api.settings import (BACKEND_DB_MODULE, BACKEND_DB_CONNECTION, |
60 |
BACKEND_BLOCK_MODULE, BACKEND_BLOCK_PATH, |
61 |
BACKEND_BLOCK_UMASK, |
62 |
BACKEND_QUEUE_MODULE, BACKEND_QUEUE_HOSTS, |
63 |
BACKEND_QUEUE_EXCHANGE, |
64 |
QUOTAHOLDER_URL, QUOTAHOLDER_TOKEN, |
65 |
BACKEND_QUOTA, BACKEND_VERSIONING, |
66 |
BACKEND_FREE_VERSIONING, |
67 |
AUTHENTICATION_URL, AUTHENTICATION_USERS, |
68 |
SERVICE_TOKEN, COOKIE_NAME, USER_CATALOG_URL, |
69 |
RADOS_STORAGE, RADOS_POOL_BLOCKS, |
70 |
RADOS_POOL_MAPS) |
71 |
from pithos.backends import connect_backend |
72 |
from pithos.backends.base import (NotAllowedError, QuotaError, ItemNotExists, |
73 |
VersionNotExists) |
74 |
from synnefo.lib.astakos import (get_user_uuid, get_displayname, |
75 |
get_uuids, get_displaynames) |
76 |
|
77 |
import logging |
78 |
import re |
79 |
import hashlib |
80 |
import uuid |
81 |
import decimal |
82 |
|
83 |
|
84 |
logger = logging.getLogger(__name__) |
85 |
|
86 |
|
87 |
class UTC(tzinfo): |
88 |
def utcoffset(self, dt): |
89 |
return timedelta(0) |
90 |
|
91 |
def tzname(self, dt): |
92 |
return 'UTC' |
93 |
|
94 |
def dst(self, dt): |
95 |
return timedelta(0) |
96 |
|
97 |
|
98 |
def json_encode_decimal(obj): |
99 |
if isinstance(obj, decimal.Decimal): |
100 |
return str(obj) |
101 |
raise TypeError(repr(obj) + " is not JSON serializable") |
102 |
|
103 |
|
104 |
def isoformat(d): |
105 |
"""Return an ISO8601 date string that includes a timezone."""
|
106 |
|
107 |
return d.replace(tzinfo=UTC()).isoformat()
|
108 |
|
109 |
|
110 |
def rename_meta_key(d, old, new): |
111 |
if old not in d: |
112 |
return
|
113 |
d[new] = d[old] |
114 |
del(d[old])
|
115 |
|
116 |
|
117 |
def printable_header_dict(d): |
118 |
"""Format a meta dictionary for printing out json/xml.
|
119 |
|
120 |
Convert all keys to lower case and replace dashes with underscores.
|
121 |
Format 'last_modified' timestamp.
|
122 |
"""
|
123 |
|
124 |
if 'last_modified' in d and d['last_modified']: |
125 |
d['last_modified'] = isoformat(
|
126 |
datetime.fromtimestamp(d['last_modified']))
|
127 |
return dict([(k.lower().replace('-', '_'), v) for k, v in d.iteritems()]) |
128 |
|
129 |
|
130 |
def format_header_key(k): |
131 |
"""Convert underscores to dashes and capitalize intra-dash strings."""
|
132 |
return '-'.join([x.capitalize() for x in k.replace('_', '-').split('-')]) |
133 |
|
134 |
|
135 |
def get_header_prefix(request, prefix): |
136 |
"""Get all prefix-* request headers in a dict. Reformat keys with format_header_key()."""
|
137 |
|
138 |
prefix = 'HTTP_' + prefix.upper().replace('-', '_') |
139 |
# TODO: Document or remove '~' replacing.
|
140 |
return dict([(format_header_key(k[5:]), v.replace('~', '')) for k, v in request.META.iteritems() if k.startswith(prefix) and len(k) > len(prefix)]) |
141 |
|
142 |
|
143 |
def check_meta_headers(meta): |
144 |
if len(meta) > 90: |
145 |
raise BadRequest('Too many headers.') |
146 |
for k, v in meta.iteritems(): |
147 |
if len(k) > 128: |
148 |
raise BadRequest('Header name too large.') |
149 |
if len(v) > 256: |
150 |
raise BadRequest('Header value too large.') |
151 |
|
152 |
|
153 |
def get_account_headers(request): |
154 |
meta = get_header_prefix(request, 'X-Account-Meta-')
|
155 |
check_meta_headers(meta) |
156 |
groups = {} |
157 |
for k, v in get_header_prefix(request, 'X-Account-Group-').iteritems(): |
158 |
n = k[16:].lower()
|
159 |
if '-' in n or '_' in n: |
160 |
raise BadRequest('Bad characters in group name') |
161 |
groups[n] = v.replace(' ', '').split(',') |
162 |
while '' in groups[n]: |
163 |
groups[n].remove('')
|
164 |
return meta, groups
|
165 |
|
166 |
|
167 |
def put_account_translation_headers(response, accounts): |
168 |
for x in accounts: |
169 |
k = smart_str('X-Account-Presentation-%s' % x, strings_only=True) |
170 |
v = smart_str(retrieve_username(x), strings_only=True)
|
171 |
response[k] = v |
172 |
|
173 |
|
174 |
def put_account_headers(response, meta, groups, policy): |
175 |
if 'count' in meta: |
176 |
response['X-Account-Container-Count'] = meta['count'] |
177 |
if 'bytes' in meta: |
178 |
response['X-Account-Bytes-Used'] = meta['bytes'] |
179 |
response['Last-Modified'] = http_date(int(meta['modified'])) |
180 |
for k in [x for x in meta.keys() if x.startswith('X-Account-Meta-')]: |
181 |
response[smart_str( |
182 |
k, strings_only=True)] = smart_str(meta[k], strings_only=True) |
183 |
if 'until_timestamp' in meta: |
184 |
response['X-Account-Until-Timestamp'] = http_date(
|
185 |
int(meta['until_timestamp'])) |
186 |
for k, v in groups.iteritems(): |
187 |
k = smart_str(k, strings_only=True)
|
188 |
k = format_header_key('X-Account-Group-' + k)
|
189 |
v = smart_str(','.join(v), strings_only=True) |
190 |
response[k] = v |
191 |
for k, v in policy.iteritems(): |
192 |
response[smart_str(format_header_key('X-Account-Policy-' + k), strings_only=True)] = smart_str(v, strings_only=True) |
193 |
|
194 |
|
195 |
def get_container_headers(request): |
196 |
meta = get_header_prefix(request, 'X-Container-Meta-')
|
197 |
check_meta_headers(meta) |
198 |
policy = dict([(k[19:].lower(), v.replace(' ', '')) for k, v in get_header_prefix(request, 'X-Container-Policy-').iteritems()]) |
199 |
return meta, policy
|
200 |
|
201 |
|
202 |
def put_container_headers(request, response, meta, policy): |
203 |
if 'count' in meta: |
204 |
response['X-Container-Object-Count'] = meta['count'] |
205 |
if 'bytes' in meta: |
206 |
response['X-Container-Bytes-Used'] = meta['bytes'] |
207 |
response['Last-Modified'] = http_date(int(meta['modified'])) |
208 |
for k in [x for x in meta.keys() if x.startswith('X-Container-Meta-')]: |
209 |
response[smart_str( |
210 |
k, strings_only=True)] = smart_str(meta[k], strings_only=True) |
211 |
l = [smart_str(x, strings_only=True) for x in meta['object_meta'] |
212 |
if x.startswith('X-Object-Meta-')] |
213 |
response['X-Container-Object-Meta'] = ','.join([x[14:] for x in l]) |
214 |
response['X-Container-Block-Size'] = request.backend.block_size
|
215 |
response['X-Container-Block-Hash'] = request.backend.hash_algorithm
|
216 |
if 'until_timestamp' in meta: |
217 |
response['X-Container-Until-Timestamp'] = http_date(
|
218 |
int(meta['until_timestamp'])) |
219 |
for k, v in policy.iteritems(): |
220 |
response[smart_str(format_header_key('X-Container-Policy-' + k), strings_only=True)] = smart_str(v, strings_only=True) |
221 |
|
222 |
|
223 |
def get_object_headers(request): |
224 |
content_type = request.META.get('CONTENT_TYPE', None) |
225 |
meta = get_header_prefix(request, 'X-Object-Meta-')
|
226 |
check_meta_headers(meta) |
227 |
if request.META.get('HTTP_CONTENT_ENCODING'): |
228 |
meta['Content-Encoding'] = request.META['HTTP_CONTENT_ENCODING'] |
229 |
if request.META.get('HTTP_CONTENT_DISPOSITION'): |
230 |
meta['Content-Disposition'] = request.META['HTTP_CONTENT_DISPOSITION'] |
231 |
if request.META.get('HTTP_X_OBJECT_MANIFEST'): |
232 |
meta['X-Object-Manifest'] = request.META['HTTP_X_OBJECT_MANIFEST'] |
233 |
return content_type, meta, get_sharing(request), get_public(request)
|
234 |
|
235 |
|
236 |
def put_object_headers(response, meta, restricted=False): |
237 |
response['ETag'] = meta['checksum'] |
238 |
response['Content-Length'] = meta['bytes'] |
239 |
response['Content-Type'] = meta.get('type', 'application/octet-stream') |
240 |
response['Last-Modified'] = http_date(int(meta['modified'])) |
241 |
if not restricted: |
242 |
response['X-Object-Hash'] = meta['hash'] |
243 |
response['X-Object-UUID'] = meta['uuid'] |
244 |
modified_by = retrieve_displayname(meta['modified_by'])
|
245 |
response['X-Object-Modified-By'] = smart_str(
|
246 |
modified_by, strings_only=True)
|
247 |
response['X-Object-Version'] = meta['version'] |
248 |
response['X-Object-Version-Timestamp'] = http_date(
|
249 |
int(meta['version_timestamp'])) |
250 |
for k in [x for x in meta.keys() if x.startswith('X-Object-Meta-')]: |
251 |
response[smart_str( |
252 |
k, strings_only=True)] = smart_str(meta[k], strings_only=True) |
253 |
for k in ( |
254 |
'Content-Encoding', 'Content-Disposition', 'X-Object-Manifest', |
255 |
'X-Object-Sharing', 'X-Object-Shared-By', 'X-Object-Allowed-To', |
256 |
'X-Object-Public'):
|
257 |
if k in meta: |
258 |
response[k] = smart_str(meta[k], strings_only=True)
|
259 |
else:
|
260 |
for k in ('Content-Encoding', 'Content-Disposition'): |
261 |
if k in meta: |
262 |
response[k] = smart_str(meta[k], strings_only=True)
|
263 |
|
264 |
|
265 |
def update_manifest_meta(request, v_account, meta): |
266 |
"""Update metadata if the object has an X-Object-Manifest."""
|
267 |
|
268 |
if 'X-Object-Manifest' in meta: |
269 |
etag = ''
|
270 |
bytes = 0
|
271 |
try:
|
272 |
src_container, src_name = split_container_object_string( |
273 |
'/' + meta['X-Object-Manifest']) |
274 |
objects = request.backend.list_objects( |
275 |
request.user_uniq, v_account, |
276 |
src_container, prefix=src_name, virtual=False)
|
277 |
for x in objects: |
278 |
src_meta = request.backend.get_object_meta(request.user_uniq, |
279 |
v_account, src_container, x[0], 'pithos', x[1]) |
280 |
etag += src_meta['checksum']
|
281 |
bytes += src_meta['bytes'] |
282 |
except:
|
283 |
# Ignore errors.
|
284 |
return
|
285 |
meta['bytes'] = bytes |
286 |
md5 = hashlib.md5() |
287 |
md5.update(etag) |
288 |
meta['checksum'] = md5.hexdigest().lower()
|
289 |
|
290 |
def is_uuid(str): |
291 |
try:
|
292 |
uuid.UUID(str)
|
293 |
except ValueError: |
294 |
return False |
295 |
else:
|
296 |
return True |
297 |
|
298 |
def retrieve_displayname(uuid): |
299 |
try:
|
300 |
return get_displayname(
|
301 |
SERVICE_TOKEN, uuid, USER_CATALOG_URL, AUTHENTICATION_USERS) |
302 |
except:
|
303 |
# if it fails just leave the input intact
|
304 |
return uuid
|
305 |
|
306 |
def retrieve_displaynames(uuids): |
307 |
return get_displaynames(
|
308 |
SERVICE_TOKEN, uuids, USER_CATALOG_URL, AUTHENTICATION_USERS) |
309 |
|
310 |
def retrieve_uuid(displayname): |
311 |
if is_uuid(displayname):
|
312 |
return displayname
|
313 |
|
314 |
uuid = get_user_uuid( |
315 |
SERVICE_TOKEN, displayname, USER_CATALOG_URL, AUTHENTICATION_USERS) |
316 |
if not uuid: |
317 |
raise ItemNotExists(displayname)
|
318 |
return uuid
|
319 |
|
320 |
def retrieve_uuids(displaynames): |
321 |
return get_uuids(
|
322 |
SERVICE_TOKEN, displaynames, USER_CATALOG_URL, AUTHENTICATION_USERS) |
323 |
|
324 |
def replace_permissions_displayname(holder): |
325 |
try:
|
326 |
# check first for a group permission
|
327 |
account, group = holder.split(':')
|
328 |
except ValueError: |
329 |
return retrieve_uuid(holder)
|
330 |
else:
|
331 |
return ':'.join([retrieve_uuid(account), group]) |
332 |
|
333 |
def replace_permissions_uuid(holder): |
334 |
try:
|
335 |
# check first for a group permission
|
336 |
account, group = holder.split(':')
|
337 |
except ValueError: |
338 |
return retrieve_displayname(holder)
|
339 |
else:
|
340 |
return ':'.join([retrieve_displayname(account), group]) |
341 |
|
342 |
def update_sharing_meta(request, permissions, v_account, v_container, v_object, meta): |
343 |
if permissions is None: |
344 |
return
|
345 |
allowed, perm_path, perms = permissions |
346 |
if len(perms) == 0: |
347 |
return
|
348 |
|
349 |
perms['read'] = [replace_permissions_uuid(x) for x in perms.get('read', [])] |
350 |
perms['write'] = \
|
351 |
[replace_permissions_uuid(x) for x in perms.get('write', [])] |
352 |
|
353 |
ret = [] |
354 |
|
355 |
r = ','.join(perms.get('read', [])) |
356 |
if r:
|
357 |
ret.append('read=' + r)
|
358 |
w = ','.join(perms.get('write', [])) |
359 |
if w:
|
360 |
ret.append('write=' + w)
|
361 |
meta['X-Object-Sharing'] = '; '.join(ret) |
362 |
if '/'.join((v_account, v_container, v_object)) != perm_path: |
363 |
meta['X-Object-Shared-By'] = perm_path
|
364 |
if request.user_uniq != v_account:
|
365 |
meta['X-Object-Allowed-To'] = allowed
|
366 |
|
367 |
|
368 |
def update_public_meta(public, meta): |
369 |
if not public: |
370 |
return
|
371 |
meta['X-Object-Public'] = '/public/' + encode_url(public) |
372 |
|
373 |
|
374 |
def validate_modification_preconditions(request, meta): |
375 |
"""Check that the modified timestamp conforms with the preconditions set."""
|
376 |
|
377 |
if 'modified' not in meta: |
378 |
return # TODO: Always return? |
379 |
|
380 |
if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE')
|
381 |
if if_modified_since is not None: |
382 |
if_modified_since = parse_http_date_safe(if_modified_since) |
383 |
if if_modified_since is not None and int(meta['modified']) <= if_modified_since: |
384 |
raise NotModified('Resource has not been modified') |
385 |
|
386 |
if_unmodified_since = request.META.get('HTTP_IF_UNMODIFIED_SINCE')
|
387 |
if if_unmodified_since is not None: |
388 |
if_unmodified_since = parse_http_date_safe(if_unmodified_since) |
389 |
if if_unmodified_since is not None and int(meta['modified']) > if_unmodified_since: |
390 |
raise PreconditionFailed('Resource has been modified') |
391 |
|
392 |
|
393 |
def validate_matching_preconditions(request, meta): |
394 |
"""Check that the ETag conforms with the preconditions set."""
|
395 |
|
396 |
etag = meta['checksum']
|
397 |
if not etag: |
398 |
etag = None
|
399 |
|
400 |
if_match = request.META.get('HTTP_IF_MATCH')
|
401 |
if if_match is not None: |
402 |
if etag is None: |
403 |
raise PreconditionFailed('Resource does not exist') |
404 |
if if_match != '*' and etag not in [x.lower() for x in parse_etags(if_match)]: |
405 |
raise PreconditionFailed('Resource ETag does not match') |
406 |
|
407 |
if_none_match = request.META.get('HTTP_IF_NONE_MATCH')
|
408 |
if if_none_match is not None: |
409 |
# TODO: If this passes, must ignore If-Modified-Since header.
|
410 |
if etag is not None: |
411 |
if if_none_match == '*' or etag in [x.lower() for x in parse_etags(if_none_match)]: |
412 |
# TODO: Continue if an If-Modified-Since header is present.
|
413 |
if request.method in ('HEAD', 'GET'): |
414 |
raise NotModified('Resource ETag matches') |
415 |
raise PreconditionFailed('Resource exists or ETag matches') |
416 |
|
417 |
|
418 |
def split_container_object_string(s): |
419 |
if not len(s) > 0 or s[0] != '/': |
420 |
raise ValueError |
421 |
s = s[1:]
|
422 |
pos = s.find('/')
|
423 |
if pos == -1 or pos == len(s) - 1: |
424 |
raise ValueError |
425 |
return s[:pos], s[(pos + 1):] |
426 |
|
427 |
|
428 |
def copy_or_move_object(request, src_account, src_container, src_name, dest_account, dest_container, dest_name, move=False, delimiter=None): |
429 |
"""Copy or move an object."""
|
430 |
|
431 |
if 'ignore_content_type' in request.GET and 'CONTENT_TYPE' in request.META: |
432 |
del(request.META['CONTENT_TYPE']) |
433 |
content_type, meta, permissions, public = get_object_headers(request) |
434 |
src_version = request.META.get('HTTP_X_SOURCE_VERSION')
|
435 |
try:
|
436 |
if move:
|
437 |
version_id = request.backend.move_object( |
438 |
request.user_uniq, src_account, src_container, src_name, |
439 |
dest_account, dest_container, dest_name, |
440 |
content_type, 'pithos', meta, False, permissions, delimiter) |
441 |
else:
|
442 |
version_id = request.backend.copy_object( |
443 |
request.user_uniq, src_account, src_container, src_name, |
444 |
dest_account, dest_container, dest_name, |
445 |
content_type, 'pithos', meta, False, permissions, src_version, delimiter) |
446 |
except NotAllowedError:
|
447 |
raise Forbidden('Not allowed') |
448 |
except (ItemNotExists, VersionNotExists):
|
449 |
raise ItemNotFound('Container or object does not exist') |
450 |
except ValueError: |
451 |
raise BadRequest('Invalid sharing header') |
452 |
except QuotaError:
|
453 |
raise RequestEntityTooLarge('Quota exceeded') |
454 |
if public is not None: |
455 |
try:
|
456 |
request.backend.update_object_public(request.user_uniq, dest_account, dest_container, dest_name, public) |
457 |
except NotAllowedError:
|
458 |
raise Forbidden('Not allowed') |
459 |
except ItemNotExists:
|
460 |
raise ItemNotFound('Object does not exist') |
461 |
return version_id
|
462 |
|
463 |
|
464 |
def get_int_parameter(p): |
465 |
if p is not None: |
466 |
try:
|
467 |
p = int(p)
|
468 |
except ValueError: |
469 |
return None |
470 |
if p < 0: |
471 |
return None |
472 |
return p
|
473 |
|
474 |
|
475 |
def get_content_length(request): |
476 |
content_length = get_int_parameter(request.META.get('CONTENT_LENGTH'))
|
477 |
if content_length is None: |
478 |
raise LengthRequired('Missing or invalid Content-Length header') |
479 |
return content_length
|
480 |
|
481 |
|
482 |
def get_range(request, size): |
483 |
"""Parse a Range header from the request.
|
484 |
|
485 |
Either returns None, when the header is not existent or should be ignored,
|
486 |
or a list of (offset, length) tuples - should be further checked.
|
487 |
"""
|
488 |
|
489 |
ranges = request.META.get('HTTP_RANGE', '').replace(' ', '') |
490 |
if not ranges.startswith('bytes='): |
491 |
return None |
492 |
|
493 |
ret = [] |
494 |
for r in (x.strip() for x in ranges[6:].split(',')): |
495 |
p = re.compile('^(?P<offset>\d*)-(?P<upto>\d*)$')
|
496 |
m = p.match(r) |
497 |
if not m: |
498 |
return None |
499 |
offset = m.group('offset')
|
500 |
upto = m.group('upto')
|
501 |
if offset == '' and upto == '': |
502 |
return None |
503 |
|
504 |
if offset != '': |
505 |
offset = int(offset)
|
506 |
if upto != '': |
507 |
upto = int(upto)
|
508 |
if offset > upto:
|
509 |
return None |
510 |
ret.append((offset, upto - offset + 1))
|
511 |
else:
|
512 |
ret.append((offset, size - offset)) |
513 |
else:
|
514 |
length = int(upto)
|
515 |
ret.append((size - length, length)) |
516 |
|
517 |
return ret
|
518 |
|
519 |
|
520 |
def get_content_range(request): |
521 |
"""Parse a Content-Range header from the request.
|
522 |
|
523 |
Either returns None, when the header is not existent or should be ignored,
|
524 |
or an (offset, length, total) tuple - check as length, total may be None.
|
525 |
Returns (None, None, None) if the provided range is '*/*'.
|
526 |
"""
|
527 |
|
528 |
ranges = request.META.get('HTTP_CONTENT_RANGE', '') |
529 |
if not ranges: |
530 |
return None |
531 |
|
532 |
p = re.compile('^bytes (?P<offset>\d+)-(?P<upto>\d*)/(?P<total>(\d+|\*))$')
|
533 |
m = p.match(ranges) |
534 |
if not m: |
535 |
if ranges == 'bytes */*': |
536 |
return (None, None, None) |
537 |
return None |
538 |
offset = int(m.group('offset')) |
539 |
upto = m.group('upto')
|
540 |
total = m.group('total')
|
541 |
if upto != '': |
542 |
upto = int(upto)
|
543 |
else:
|
544 |
upto = None
|
545 |
if total != '*': |
546 |
total = int(total)
|
547 |
else:
|
548 |
total = None
|
549 |
if (upto is not None and offset > upto) or \ |
550 |
(total is not None and offset >= total) or \ |
551 |
(total is not None and upto is not None and upto >= total): |
552 |
return None |
553 |
|
554 |
if upto is None: |
555 |
length = None
|
556 |
else:
|
557 |
length = upto - offset + 1
|
558 |
return (offset, length, total)
|
559 |
|
560 |
|
561 |
def get_sharing(request): |
562 |
"""Parse an X-Object-Sharing header from the request.
|
563 |
|
564 |
Raises BadRequest on error.
|
565 |
"""
|
566 |
|
567 |
permissions = request.META.get('HTTP_X_OBJECT_SHARING')
|
568 |
if permissions is None: |
569 |
return None |
570 |
|
571 |
# TODO: Document or remove '~' replacing.
|
572 |
permissions = permissions.replace('~', '') |
573 |
|
574 |
ret = {} |
575 |
permissions = permissions.replace(' ', '') |
576 |
if permissions == '': |
577 |
return ret
|
578 |
for perm in (x for x in permissions.split(';')): |
579 |
if perm.startswith('read='): |
580 |
ret['read'] = list(set( |
581 |
[v.replace(' ', '').lower() for v in perm[5:].split(',')])) |
582 |
if '' in ret['read']: |
583 |
ret['read'].remove('') |
584 |
if '*' in ret['read']: |
585 |
ret['read'] = ['*'] |
586 |
if len(ret['read']) == 0: |
587 |
raise BadRequest(
|
588 |
'Bad X-Object-Sharing header value: invalid length')
|
589 |
elif perm.startswith('write='): |
590 |
ret['write'] = list(set( |
591 |
[v.replace(' ', '').lower() for v in perm[6:].split(',')])) |
592 |
if '' in ret['write']: |
593 |
ret['write'].remove('') |
594 |
if '*' in ret['write']: |
595 |
ret['write'] = ['*'] |
596 |
if len(ret['write']) == 0: |
597 |
raise BadRequest(
|
598 |
'Bad X-Object-Sharing header value: invalid length')
|
599 |
else:
|
600 |
raise BadRequest(
|
601 |
'Bad X-Object-Sharing header value: missing prefix')
|
602 |
|
603 |
# replace displayname with uuid
|
604 |
try:
|
605 |
ret['read'] = \
|
606 |
[replace_permissions_displayname(x) for x in ret.get('read', [])] |
607 |
ret['write'] = \
|
608 |
[replace_permissions_displayname(x) for x in ret.get('write', [])] |
609 |
except ItemNotExists, e:
|
610 |
raise BadRequest(
|
611 |
'Bad X-Object-Sharing header value: unknown account: %s' % e)
|
612 |
|
613 |
# Keep duplicates only in write list.
|
614 |
dups = [x for x in ret.get( |
615 |
'read', []) if x in ret.get('write', []) and x != '*'] |
616 |
if dups:
|
617 |
for x in dups: |
618 |
ret['read'].remove(x)
|
619 |
if len(ret['read']) == 0: |
620 |
del(ret['read']) |
621 |
|
622 |
return ret
|
623 |
|
624 |
|
625 |
def get_public(request): |
626 |
"""Parse an X-Object-Public header from the request.
|
627 |
|
628 |
Raises BadRequest on error.
|
629 |
"""
|
630 |
|
631 |
public = request.META.get('HTTP_X_OBJECT_PUBLIC')
|
632 |
if public is None: |
633 |
return None |
634 |
|
635 |
public = public.replace(' ', '').lower() |
636 |
if public == 'true': |
637 |
return True |
638 |
elif public == 'false' or public == '': |
639 |
return False |
640 |
raise BadRequest('Bad X-Object-Public header value') |
641 |
|
642 |
|
643 |
def raw_input_socket(request): |
644 |
"""Return the socket for reading the rest of the request."""
|
645 |
|
646 |
server_software = request.META.get('SERVER_SOFTWARE')
|
647 |
if server_software and server_software.startswith('mod_python'): |
648 |
return request._req
|
649 |
if 'wsgi.input' in request.environ: |
650 |
return request.environ['wsgi.input'] |
651 |
raise NotImplemented('Unknown server software') |
652 |
|
653 |
MAX_UPLOAD_SIZE = 5 * (1024 * 1024 * 1024) # 5GB |
654 |
|
655 |
|
656 |
def socket_read_iterator(request, length=0, blocksize=4096): |
657 |
"""Return a maximum of blocksize data read from the socket in each iteration.
|
658 |
|
659 |
Read up to 'length'. If 'length' is negative, will attempt a chunked read.
|
660 |
The maximum ammount of data read is controlled by MAX_UPLOAD_SIZE.
|
661 |
"""
|
662 |
|
663 |
sock = raw_input_socket(request) |
664 |
if length < 0: # Chunked transfers |
665 |
# Small version (server does the dechunking).
|
666 |
if request.environ.get('mod_wsgi.input_chunked', None) or request.META['SERVER_SOFTWARE'].startswith('gunicorn'): |
667 |
while length < MAX_UPLOAD_SIZE:
|
668 |
data = sock.read(blocksize) |
669 |
if data == '': |
670 |
return
|
671 |
yield data
|
672 |
raise BadRequest('Maximum size is reached') |
673 |
|
674 |
# Long version (do the dechunking).
|
675 |
data = ''
|
676 |
while length < MAX_UPLOAD_SIZE:
|
677 |
# Get chunk size.
|
678 |
if hasattr(sock, 'readline'): |
679 |
chunk_length = sock.readline() |
680 |
else:
|
681 |
chunk_length = ''
|
682 |
while chunk_length[-1:] != '\n': |
683 |
chunk_length += sock.read(1)
|
684 |
chunk_length.strip() |
685 |
pos = chunk_length.find(';')
|
686 |
if pos >= 0: |
687 |
chunk_length = chunk_length[:pos] |
688 |
try:
|
689 |
chunk_length = int(chunk_length, 16) |
690 |
except Exception, e: |
691 |
raise BadRequest('Bad chunk size') |
692 |
# TODO: Change to something more appropriate.
|
693 |
# Check if done.
|
694 |
if chunk_length == 0: |
695 |
if len(data) > 0: |
696 |
yield data
|
697 |
return
|
698 |
# Get the actual data.
|
699 |
while chunk_length > 0: |
700 |
chunk = sock.read(min(chunk_length, blocksize))
|
701 |
chunk_length -= len(chunk)
|
702 |
if length > 0: |
703 |
length += len(chunk)
|
704 |
data += chunk |
705 |
if len(data) >= blocksize: |
706 |
ret = data[:blocksize] |
707 |
data = data[blocksize:] |
708 |
yield ret
|
709 |
sock.read(2) # CRLF |
710 |
raise BadRequest('Maximum size is reached') |
711 |
else:
|
712 |
if length > MAX_UPLOAD_SIZE:
|
713 |
raise BadRequest('Maximum size is reached') |
714 |
while length > 0: |
715 |
data = sock.read(min(length, blocksize))
|
716 |
if not data: |
717 |
raise BadRequest()
|
718 |
length -= len(data)
|
719 |
yield data
|
720 |
|
721 |
|
722 |
class SaveToBackendHandler(FileUploadHandler): |
723 |
"""Handle a file from an HTML form the django way."""
|
724 |
|
725 |
def __init__(self, request=None): |
726 |
super(SaveToBackendHandler, self).__init__(request) |
727 |
self.backend = request.backend
|
728 |
|
729 |
def put_data(self, length): |
730 |
if len(self.data) >= length: |
731 |
block = self.data[:length]
|
732 |
self.file.hashmap.append(self.backend.put_block(block)) |
733 |
self.md5.update(block)
|
734 |
self.data = self.data[length:] |
735 |
|
736 |
def new_file(self, field_name, file_name, content_type, content_length, charset=None): |
737 |
self.md5 = hashlib.md5()
|
738 |
self.data = '' |
739 |
self.file = UploadedFile(
|
740 |
name=file_name, content_type=content_type, charset=charset) |
741 |
self.file.size = 0 |
742 |
self.file.hashmap = []
|
743 |
|
744 |
def receive_data_chunk(self, raw_data, start): |
745 |
self.data += raw_data
|
746 |
self.file.size += len(raw_data) |
747 |
self.put_data(self.request.backend.block_size) |
748 |
return None |
749 |
|
750 |
def file_complete(self, file_size): |
751 |
l = len(self.data) |
752 |
if l > 0: |
753 |
self.put_data(l)
|
754 |
self.file.etag = self.md5.hexdigest().lower() |
755 |
return self.file |
756 |
|
757 |
|
758 |
class ObjectWrapper(object): |
759 |
"""Return the object's data block-per-block in each iteration.
|
760 |
|
761 |
Read from the object using the offset and length provided in each entry of the range list.
|
762 |
"""
|
763 |
|
764 |
def __init__(self, backend, ranges, sizes, hashmaps, boundary): |
765 |
self.backend = backend
|
766 |
self.ranges = ranges
|
767 |
self.sizes = sizes
|
768 |
self.hashmaps = hashmaps
|
769 |
self.boundary = boundary
|
770 |
self.size = sum(self.sizes) |
771 |
|
772 |
self.file_index = 0 |
773 |
self.block_index = 0 |
774 |
self.block_hash = -1 |
775 |
self.block = '' |
776 |
|
777 |
self.range_index = -1 |
778 |
self.offset, self.length = self.ranges[0] |
779 |
|
780 |
def __iter__(self): |
781 |
return self |
782 |
|
783 |
def part_iterator(self): |
784 |
if self.length > 0: |
785 |
# Get the file for the current offset.
|
786 |
file_size = self.sizes[self.file_index] |
787 |
while self.offset >= file_size: |
788 |
self.offset -= file_size
|
789 |
self.file_index += 1 |
790 |
file_size = self.sizes[self.file_index] |
791 |
|
792 |
# Get the block for the current position.
|
793 |
self.block_index = int(self.offset / self.backend.block_size) |
794 |
if self.block_hash != self.hashmaps[self.file_index][self.block_index]: |
795 |
self.block_hash = self.hashmaps[ |
796 |
self.file_index][self.block_index] |
797 |
try:
|
798 |
self.block = self.backend.get_block(self.block_hash) |
799 |
except ItemNotExists:
|
800 |
raise ItemNotFound('Block does not exist') |
801 |
|
802 |
# Get the data from the block.
|
803 |
bo = self.offset % self.backend.block_size |
804 |
bs = self.backend.block_size
|
805 |
if (self.block_index == len(self.hashmaps[self.file_index]) - 1 and |
806 |
self.sizes[self.file_index] % self.backend.block_size): |
807 |
bs = self.sizes[self.file_index] % self.backend.block_size |
808 |
bl = min(self.length, bs - bo) |
809 |
data = self.block[bo:bo + bl]
|
810 |
self.offset += bl
|
811 |
self.length -= bl
|
812 |
return data
|
813 |
else:
|
814 |
raise StopIteration |
815 |
|
816 |
def next(self): |
817 |
if len(self.ranges) == 1: |
818 |
return self.part_iterator() |
819 |
if self.range_index == len(self.ranges): |
820 |
raise StopIteration |
821 |
try:
|
822 |
if self.range_index == -1: |
823 |
raise StopIteration |
824 |
return self.part_iterator() |
825 |
except StopIteration: |
826 |
self.range_index += 1 |
827 |
out = [] |
828 |
if self.range_index < len(self.ranges): |
829 |
# Part header.
|
830 |
self.offset, self.length = self.ranges[self.range_index] |
831 |
self.file_index = 0 |
832 |
if self.range_index > 0: |
833 |
out.append('')
|
834 |
out.append('--' + self.boundary) |
835 |
out.append('Content-Range: bytes %d-%d/%d' % (
|
836 |
self.offset, self.offset + self.length - 1, self.size)) |
837 |
out.append('Content-Transfer-Encoding: binary')
|
838 |
out.append('')
|
839 |
out.append('')
|
840 |
return '\r\n'.join(out) |
841 |
else:
|
842 |
# Footer.
|
843 |
out.append('')
|
844 |
out.append('--' + self.boundary + '--') |
845 |
out.append('')
|
846 |
return '\r\n'.join(out) |
847 |
|
848 |
|
849 |
def object_data_response(request, sizes, hashmaps, meta, public=False): |
850 |
"""Get the HttpResponse object for replying with the object's data."""
|
851 |
|
852 |
# Range handling.
|
853 |
size = sum(sizes)
|
854 |
ranges = get_range(request, size) |
855 |
if ranges is None: |
856 |
ranges = [(0, size)]
|
857 |
ret = 200
|
858 |
else:
|
859 |
check = [True for offset, length in ranges if |
860 |
length <= 0 or length > size or |
861 |
offset < 0 or offset >= size or |
862 |
offset + length > size] |
863 |
if len(check) > 0: |
864 |
raise RangeNotSatisfiable('Requested range exceeds object limits') |
865 |
ret = 206
|
866 |
if_range = request.META.get('HTTP_IF_RANGE')
|
867 |
if if_range:
|
868 |
try:
|
869 |
# Modification time has passed instead.
|
870 |
last_modified = parse_http_date(if_range) |
871 |
if last_modified != meta['modified']: |
872 |
ranges = [(0, size)]
|
873 |
ret = 200
|
874 |
except ValueError: |
875 |
if if_range != meta['checksum']: |
876 |
ranges = [(0, size)]
|
877 |
ret = 200
|
878 |
|
879 |
if ret == 206 and len(ranges) > 1: |
880 |
boundary = uuid.uuid4().hex |
881 |
else:
|
882 |
boundary = ''
|
883 |
wrapper = ObjectWrapper(request.backend, ranges, sizes, hashmaps, boundary) |
884 |
response = HttpResponse(wrapper, status=ret) |
885 |
put_object_headers(response, meta, public) |
886 |
if ret == 206: |
887 |
if len(ranges) == 1: |
888 |
offset, length = ranges[0]
|
889 |
response[ |
890 |
'Content-Length'] = length # Update with the correct length. |
891 |
response['Content-Range'] = 'bytes %d-%d/%d' % ( |
892 |
offset, offset + length - 1, size)
|
893 |
else:
|
894 |
del(response['Content-Length']) |
895 |
response['Content-Type'] = 'multipart/byteranges; boundary=%s' % ( |
896 |
boundary,) |
897 |
return response
|
898 |
|
899 |
|
900 |
def put_object_block(request, hashmap, data, offset): |
901 |
"""Put one block of data at the given offset."""
|
902 |
|
903 |
bi = int(offset / request.backend.block_size)
|
904 |
bo = offset % request.backend.block_size |
905 |
bl = min(len(data), request.backend.block_size - bo) |
906 |
if bi < len(hashmap): |
907 |
hashmap[bi] = request.backend.update_block(hashmap[bi], data[:bl], bo) |
908 |
else:
|
909 |
hashmap.append(request.backend.put_block(('\x00' * bo) + data[:bl]))
|
910 |
return bl # Return ammount of data written. |
911 |
|
912 |
|
913 |
def hashmap_md5(backend, hashmap, size): |
914 |
"""Produce the MD5 sum from the data in the hashmap."""
|
915 |
|
916 |
# TODO: Search backend for the MD5 of another object with the same hashmap and size...
|
917 |
md5 = hashlib.md5() |
918 |
bs = backend.block_size |
919 |
for bi, hash in enumerate(hashmap): |
920 |
data = backend.get_block(hash) # Blocks come in padded. |
921 |
if bi == len(hashmap) - 1: |
922 |
data = data[:size % bs] |
923 |
md5.update(data) |
924 |
return md5.hexdigest().lower()
|
925 |
|
926 |
|
927 |
def simple_list_response(request, l): |
928 |
if request.serialization == 'text': |
929 |
return '\n'.join(l) + '\n' |
930 |
if request.serialization == 'xml': |
931 |
return render_to_string('items.xml', {'items': l}) |
932 |
if request.serialization == 'json': |
933 |
return json.dumps(l)
|
934 |
|
935 |
|
936 |
from pithos.backends.util import PithosBackendPool |
937 |
POOL_SIZE = 5
|
938 |
if RADOS_STORAGE:
|
939 |
BLOCK_PARAMS = { 'mappool': RADOS_POOL_MAPS,
|
940 |
'blockpool': RADOS_POOL_BLOCKS,
|
941 |
} |
942 |
else:
|
943 |
BLOCK_PARAMS = { 'mappool': None, |
944 |
'blockpool': None, |
945 |
} |
946 |
|
947 |
|
948 |
_pithos_backend_pool = PithosBackendPool(size=POOL_SIZE, |
949 |
db_module=BACKEND_DB_MODULE, |
950 |
db_connection=BACKEND_DB_CONNECTION, |
951 |
block_module=BACKEND_BLOCK_MODULE, |
952 |
block_path=BACKEND_BLOCK_PATH, |
953 |
block_umask=BACKEND_BLOCK_UMASK, |
954 |
queue_module=BACKEND_QUEUE_MODULE, |
955 |
queue_hosts=BACKEND_QUEUE_HOSTS, |
956 |
queue_exchange=BACKEND_QUEUE_EXCHANGE, |
957 |
quotaholder_url=QUOTAHOLDER_URL, |
958 |
quotaholder_token=QUOTAHOLDER_TOKEN, |
959 |
free_versioning=BACKEND_FREE_VERSIONING, |
960 |
block_params=BLOCK_PARAMS) |
961 |
|
962 |
def get_backend(): |
963 |
backend = _pithos_backend_pool.pool_get() |
964 |
backend.default_policy['quota'] = BACKEND_QUOTA
|
965 |
backend.default_policy['versioning'] = BACKEND_VERSIONING
|
966 |
backend.messages = [] |
967 |
return backend
|
968 |
|
969 |
|
970 |
def update_request_headers(request): |
971 |
# Handle URL-encoded keys and values.
|
972 |
meta = dict([(
|
973 |
k, v) for k, v in request.META.iteritems() if k.startswith('HTTP_')]) |
974 |
for k, v in meta.iteritems(): |
975 |
try:
|
976 |
k.decode('ascii')
|
977 |
v.decode('ascii')
|
978 |
except UnicodeDecodeError: |
979 |
raise BadRequest('Bad character in headers.') |
980 |
if '%' in k or '%' in v: |
981 |
del(request.META[k])
|
982 |
request.META[unquote(k)] = smart_unicode(unquote( |
983 |
v), strings_only=True)
|
984 |
|
985 |
|
986 |
def update_response_headers(request, response): |
987 |
if request.serialization == 'xml': |
988 |
response['Content-Type'] = 'application/xml; charset=UTF-8' |
989 |
elif request.serialization == 'json': |
990 |
response['Content-Type'] = 'application/json; charset=UTF-8' |
991 |
elif not response['Content-Type']: |
992 |
response['Content-Type'] = 'text/plain; charset=UTF-8' |
993 |
|
994 |
if (not response.has_header('Content-Length') and |
995 |
not (response.has_header('Content-Type') and |
996 |
response['Content-Type'].startswith('multipart/byteranges'))): |
997 |
response['Content-Length'] = len(response.content) |
998 |
|
999 |
# URL-encode unicode in headers.
|
1000 |
meta = response.items() |
1001 |
for k, v in meta: |
1002 |
if (k.startswith('X-Account-') or k.startswith('X-Container-') or |
1003 |
k.startswith('X-Object-') or k.startswith('Content-')): |
1004 |
del(response[k])
|
1005 |
response[quote(k)] = quote(v, safe='/=,:@; ')
|
1006 |
|
1007 |
|
1008 |
def render_fault(request, fault): |
1009 |
if isinstance(fault, InternalServerError) and settings.DEBUG: |
1010 |
fault.details = format_exc(fault) |
1011 |
|
1012 |
request.serialization = 'text'
|
1013 |
data = fault.message + '\n'
|
1014 |
if fault.details:
|
1015 |
data += '\n' + fault.details
|
1016 |
response = HttpResponse(data, status=fault.code) |
1017 |
update_response_headers(request, response) |
1018 |
return response
|
1019 |
|
1020 |
|
1021 |
def request_serialization(request, format_allowed=False): |
1022 |
"""Return the serialization format requested.
|
1023 |
|
1024 |
Valid formats are 'text' and 'json', 'xml' if 'format_allowed' is True.
|
1025 |
"""
|
1026 |
|
1027 |
if not format_allowed: |
1028 |
return 'text' |
1029 |
|
1030 |
format = request.GET.get('format')
|
1031 |
if format == 'json': |
1032 |
return 'json' |
1033 |
elif format == 'xml': |
1034 |
return 'xml' |
1035 |
|
1036 |
for item in request.META.get('HTTP_ACCEPT', '').split(','): |
1037 |
accept, sep, rest = item.strip().partition(';')
|
1038 |
if accept == 'application/json': |
1039 |
return 'json' |
1040 |
elif accept == 'application/xml' or accept == 'text/xml': |
1041 |
return 'xml' |
1042 |
|
1043 |
return 'text' |
1044 |
|
1045 |
def get_pithos_usage(usage): |
1046 |
for u in usage: |
1047 |
if u.get('name') == 'pithos+.diskspace': |
1048 |
return u
|
1049 |
|
1050 |
def api_method(http_method=None, format_allowed=False, user_required=True, |
1051 |
request_usage=False):
|
1052 |
"""Decorator function for views that implement an API method."""
|
1053 |
|
1054 |
def decorator(func): |
1055 |
@wraps(func)
|
1056 |
def wrapper(request, *args, **kwargs): |
1057 |
try:
|
1058 |
if http_method and request.method != http_method: |
1059 |
raise BadRequest('Method not allowed.') |
1060 |
|
1061 |
if user_required:
|
1062 |
token = None
|
1063 |
if request.method in ('HEAD', 'GET') and COOKIE_NAME in request.COOKIES: |
1064 |
cookie_value = unquote( |
1065 |
request.COOKIES.get(COOKIE_NAME, ''))
|
1066 |
account, sep, token = cookie_value.partition('|')
|
1067 |
get_user(request, |
1068 |
AUTHENTICATION_URL, |
1069 |
AUTHENTICATION_USERS, |
1070 |
token, |
1071 |
user_required) |
1072 |
if getattr(request, 'user', None) is None: |
1073 |
raise Unauthorized('Access denied') |
1074 |
assert getattr(request, 'user_uniq', None) != None |
1075 |
request.user_usage = get_pithos_usage( |
1076 |
request.user.get('usage', []))
|
1077 |
|
1078 |
# The args variable may contain up to (account, container, object).
|
1079 |
if len(args) > 1 and len(args[1]) > 256: |
1080 |
raise BadRequest('Container name too large.') |
1081 |
if len(args) > 2 and len(args[2]) > 1024: |
1082 |
raise BadRequest('Object name too large.') |
1083 |
|
1084 |
# Format and check headers.
|
1085 |
update_request_headers(request) |
1086 |
|
1087 |
# Fill in custom request variables.
|
1088 |
request.serialization = request_serialization( |
1089 |
request, format_allowed) |
1090 |
request.backend = get_backend() |
1091 |
|
1092 |
response = func(request, *args, **kwargs) |
1093 |
update_response_headers(request, response) |
1094 |
return response
|
1095 |
except Fault, fault:
|
1096 |
if fault.code >= 500: |
1097 |
logger.exception("API Fault")
|
1098 |
return render_fault(request, fault)
|
1099 |
except BaseException, e: |
1100 |
logger.exception('Unexpected error: %s' % e)
|
1101 |
fault = InternalServerError('Unexpected error: %s' % e)
|
1102 |
return render_fault(request, fault)
|
1103 |
finally:
|
1104 |
if getattr(request, 'backend', None) is not None: |
1105 |
request.backend.close() |
1106 |
return wrapper
|
1107 |
return decorator
|