Statistics
| Branch: | Tag: | Revision:

root / pithos / api / functions.py @ 3436eeb0

History | View | Annotate | Download (27.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
import os
35
import logging
36
import hashlib
37

    
38
from django.http import HttpResponse
39
from django.template.loader import render_to_string
40
from django.utils import simplejson as json
41
from django.utils.http import parse_etags
42

    
43
from pithos.api.faults import (Fault, NotModified, BadRequest, Unauthorized, ItemNotFound, Conflict,
44
    LengthRequired, PreconditionFailed, RangeNotSatisfiable, UnprocessableEntity)
45
from pithos.api.util import (format_meta_key, printable_meta_dict, get_account_meta,
46
    put_account_meta, get_container_meta, put_container_meta, get_object_meta, put_object_meta,
47
    update_manifest_meta, format_permissions, validate_modification_preconditions,
48
    validate_matching_preconditions, split_container_object_string, copy_or_move_object,
49
    get_int_parameter, get_content_length, get_content_range, get_sharing, raw_input_socket,
50
    socket_read_iterator, object_data_response, put_object_block, hashmap_hash, api_method)
51
from pithos.backends import backend
52

    
53

    
54
logger = logging.getLogger(__name__)
55

    
56

    
57
def top_demux(request):
58
    if request.method == 'GET':
59
        return authenticate(request)
60
    else:
61
        return method_not_allowed(request)
62

    
63
def account_demux(request, v_account):
64
    if request.method == 'HEAD':
65
        return account_meta(request, v_account)
66
    elif request.method == 'POST':
67
        return account_update(request, v_account)
68
    elif request.method == 'GET':
69
        return container_list(request, v_account)
70
    else:
71
        return method_not_allowed(request)
72

    
73
def container_demux(request, v_account, v_container):
74
    if request.method == 'HEAD':
75
        return container_meta(request, v_account, v_container)
76
    elif request.method == 'PUT':
77
        return container_create(request, v_account, v_container)
78
    elif request.method == 'POST':
79
        return container_update(request, v_account, v_container)
80
    elif request.method == 'DELETE':
81
        return container_delete(request, v_account, v_container)
82
    elif request.method == 'GET':
83
        return object_list(request, v_account, v_container)
84
    else:
85
        return method_not_allowed(request)
86

    
87
def object_demux(request, v_account, v_container, v_object):
88
    if request.method == 'HEAD':
89
        return object_meta(request, v_account, v_container, v_object)
90
    elif request.method == 'GET':
91
        return object_read(request, v_account, v_container, v_object)
92
    elif request.method == 'PUT':
93
        return object_write(request, v_account, v_container, v_object)
94
    elif request.method == 'COPY':
95
        return object_copy(request, v_account, v_container, v_object)
96
    elif request.method == 'MOVE':
97
        return object_move(request, v_account, v_container, v_object)
98
    elif request.method == 'POST':
99
        return object_update(request, v_account, v_container, v_object)
100
    elif request.method == 'DELETE':
101
        return object_delete(request, v_account, v_container, v_object)
102
    else:
103
        return method_not_allowed(request)
104

    
105
@api_method('GET')
106
def authenticate(request):
107
    # Normal Response Codes: 204
108
    # Error Response Codes: serviceUnavailable (503),
109
    #                       unauthorized (401),
110
    #                       badRequest (400)
111
    
112
    x_auth_user = request.META.get('HTTP_X_AUTH_USER')
113
    x_auth_key = request.META.get('HTTP_X_AUTH_KEY')
114
    if not x_auth_user or not x_auth_key:
115
        raise BadRequest('Missing X-Auth-User or X-Auth-Key header')
116
    response = HttpResponse(status=204)
117
    response['X-Auth-Token'] = '0000'
118
    response['X-Storage-Url'] = os.path.join(request.build_absolute_uri(), 'demo')
119
    return response
120

    
121
@api_method('HEAD')
122
def account_meta(request, v_account):
123
    # Normal Response Codes: 204
124
    # Error Response Codes: serviceUnavailable (503),
125
    #                       unauthorized (401),
126
    #                       badRequest (400)
127
    
128
    until = get_int_parameter(request, 'until')
129
    meta = backend.get_account_meta(request.user, v_account, until)
130
    
131
    response = HttpResponse(status=204)
132
    put_account_meta(response, meta)
133
    return response
134

    
135
@api_method('POST')
136
def account_update(request, v_account):
137
    # Normal Response Codes: 202
138
    # Error Response Codes: serviceUnavailable (503),
139
    #                       unauthorized (401),
140
    #                       badRequest (400)
141
    
142
    meta = get_account_meta(request)    
143
    backend.update_account_meta(request.user, v_account, meta, replace=True)
144
    return HttpResponse(status=202)
145

    
146
@api_method('GET', format_allowed=True)
147
def container_list(request, v_account):
148
    # Normal Response Codes: 200, 204
149
    # Error Response Codes: serviceUnavailable (503),
150
    #                       itemNotFound (404),
151
    #                       unauthorized (401),
152
    #                       badRequest (400)
153
    
154
    until = get_int_parameter(request, 'until')
155
    meta = backend.get_account_meta(request.user, v_account, until)
156
    
157
    validate_modification_preconditions(request, meta)
158
    
159
    response = HttpResponse()
160
    put_account_meta(response, meta)
161
    
162
    marker = request.GET.get('marker')
163
    limit = request.GET.get('limit')
164
    if limit:
165
        try:
166
            limit = int(limit)
167
            if limit <= 0:
168
                raise ValueError
169
        except ValueError:
170
            limit = 10000
171
    
172
    try:
173
        containers = backend.list_containers(request.user, v_account, marker, limit, until)
174
    except NameError:
175
        containers = []
176
    
177
    if request.serialization == 'text':
178
        if len(containers) == 0:
179
            # The cloudfiles python bindings expect 200 if json/xml.
180
            response.status_code = 204
181
            return response
182
        response.status_code = 200
183
        response.content = '\n'.join([x[0] for x in containers]) + '\n'
184
        return response
185
    
186
    container_meta = []
187
    for x in containers:
188
        if x[1] is not None:
189
            try:
190
                meta = backend.get_container_meta(request.user, v_account, x[0], until)
191
                container_meta.append(printable_meta_dict(meta))
192
            except NameError:
193
                pass
194
    if request.serialization == 'xml':
195
        data = render_to_string('containers.xml', {'account': v_account, 'containers': container_meta})
196
    elif request.serialization  == 'json':
197
        data = json.dumps(container_meta)
198
    response.status_code = 200
199
    response.content = data
200
    return response
201

    
202
@api_method('HEAD')
203
def container_meta(request, v_account, v_container):
204
    # Normal Response Codes: 204
205
    # Error Response Codes: serviceUnavailable (503),
206
    #                       itemNotFound (404),
207
    #                       unauthorized (401),
208
    #                       badRequest (400)
209
    
210
    until = get_int_parameter(request, 'until')
211
    try:
212
        meta = backend.get_container_meta(request.user, v_account, v_container, until)
213
        meta['object_meta'] = backend.list_object_meta(request.user, v_account, v_container, until)
214
    except NameError:
215
        raise ItemNotFound('Container does not exist')
216
    
217
    response = HttpResponse(status=204)
218
    put_container_meta(response, meta)
219
    return response
220

    
221
@api_method('PUT')
222
def container_create(request, v_account, v_container):
223
    # Normal Response Codes: 201, 202
224
    # Error Response Codes: serviceUnavailable (503),
225
    #                       itemNotFound (404),
226
    #                       unauthorized (401),
227
    #                       badRequest (400)
228
    
229
    meta = get_container_meta(request)
230
    
231
    try:
232
        backend.put_container(request.user, v_account, v_container)
233
        ret = 201
234
    except NameError:
235
        ret = 202
236
    
237
    if len(meta) > 0:
238
        backend.update_container_meta(request.user, v_account, v_container, meta, replace=True)
239
    
240
    return HttpResponse(status=ret)
241

    
242
@api_method('POST')
243
def container_update(request, v_account, v_container):
244
    # Normal Response Codes: 202
245
    # Error Response Codes: serviceUnavailable (503),
246
    #                       itemNotFound (404),
247
    #                       unauthorized (401),
248
    #                       badRequest (400)
249
    
250
    meta = get_container_meta(request)
251
    try:
252
        backend.update_container_meta(request.user, v_account, v_container, meta, replace=True)
253
    except NameError:
254
        raise ItemNotFound('Container does not exist')
255
    return HttpResponse(status=202)
256

    
257
@api_method('DELETE')
258
def container_delete(request, v_account, v_container):
259
    # Normal Response Codes: 204
260
    # Error Response Codes: serviceUnavailable (503),
261
    #                       conflict (409),
262
    #                       itemNotFound (404),
263
    #                       unauthorized (401),
264
    #                       badRequest (400)
265
    
266
    try:
267
        backend.delete_container(request.user, v_account, v_container)
268
    except NameError:
269
        raise ItemNotFound('Container does not exist')
270
    except IndexError:
271
        raise Conflict('Container is not empty')
272
    return HttpResponse(status=204)
273

    
274
@api_method('GET', format_allowed=True)
275
def object_list(request, v_account, v_container):
276
    # Normal Response Codes: 200, 204
277
    # Error Response Codes: serviceUnavailable (503),
278
    #                       itemNotFound (404),
279
    #                       unauthorized (401),
280
    #                       badRequest (400)
281
    
282
    until = get_int_parameter(request, 'until')
283
    try:
284
        meta = backend.get_container_meta(request.user, v_account, v_container, until)
285
        meta['object_meta'] = backend.list_object_meta(request.user, v_account, v_container, until)
286
    except NameError:
287
        raise ItemNotFound('Container does not exist')
288
    
289
    validate_modification_preconditions(request, meta)
290
    
291
    response = HttpResponse()
292
    put_container_meta(response, meta)
293
    
294
    path = request.GET.get('path')
295
    prefix = request.GET.get('prefix')
296
    delimiter = request.GET.get('delimiter')
297
    
298
    # Path overrides prefix and delimiter.
299
    virtual = True
300
    if path:
301
        prefix = path
302
        delimiter = '/'
303
        virtual = False
304
    
305
    # Naming policy.
306
    if prefix and delimiter:
307
        prefix = prefix + delimiter
308
    if not prefix:
309
        prefix = ''
310
    prefix = prefix.lstrip('/')
311
    
312
    marker = request.GET.get('marker')
313
    limit = request.GET.get('limit')
314
    if limit:
315
        try:
316
            limit = int(limit)
317
            if limit <= 0:
318
                raise ValueError
319
        except ValueError:
320
            limit = 10000
321
    
322
    keys = request.GET.get('meta')
323
    if keys:
324
        keys = keys.split(',')
325
        keys = [format_meta_key('X-Object-Meta-' + x.strip()) for x in keys if x.strip() != '']
326
    else:
327
        keys = []
328
    
329
    try:
330
        objects = backend.list_objects(request.user, v_account, v_container, prefix, delimiter, marker, limit, virtual, keys, until)
331
    except NameError:
332
        raise ItemNotFound('Container does not exist')
333
    
334
    if request.serialization == 'text':
335
        if len(objects) == 0:
336
            # The cloudfiles python bindings expect 200 if json/xml.
337
            response.status_code = 204
338
            return response
339
        response.status_code = 200
340
        response.content = '\n'.join([x[0] for x in objects]) + '\n'
341
        return response
342
    
343
    object_meta = []
344
    for x in objects:
345
        if x[1] is None:
346
            # Virtual objects/directories.
347
            object_meta.append({'subdir': x[0]})
348
        else:
349
            try:
350
                meta = backend.get_object_meta(request.user, v_account, v_container, x[0], x[1])
351
                permissions = backend.get_object_permissions(request.user, v_account, v_container, x[0])
352
            except NameError:
353
                pass
354
            if permissions:
355
                meta['X-Object-Sharing'] = format_permissions(permissions)
356
            object_meta.append(printable_meta_dict(meta))
357
    if request.serialization == 'xml':
358
        data = render_to_string('objects.xml', {'container': v_container, 'objects': object_meta})
359
    elif request.serialization  == 'json':
360
        data = json.dumps(object_meta)
361
    response.status_code = 200
362
    response.content = data
363
    return response
364

    
365
@api_method('HEAD')
366
def object_meta(request, v_account, v_container, v_object):
367
    # Normal Response Codes: 204
368
    # Error Response Codes: serviceUnavailable (503),
369
    #                       itemNotFound (404),
370
    #                       unauthorized (401),
371
    #                       badRequest (400)
372
    
373
    version = get_int_parameter(request, 'version')
374
    try:
375
        meta = backend.get_object_meta(request.user, v_account, v_container, v_object, version)
376
        permissions = backend.get_object_permissions(request.user, v_account, v_container, v_object)
377
    except NameError:
378
        raise ItemNotFound('Object does not exist')
379
    except IndexError:
380
        raise ItemNotFound('Version does not exist')
381
    
382
    if permissions:
383
        meta['X-Object-Sharing'] = format_permissions(permissions)
384
    update_manifest_meta(request, v_account, meta)
385
    
386
    response = HttpResponse(status=200)
387
    put_object_meta(response, meta)
388
    return response
389

    
390
@api_method('GET', format_allowed=True)
391
def object_read(request, v_account, v_container, v_object):
392
    # Normal Response Codes: 200, 206
393
    # Error Response Codes: serviceUnavailable (503),
394
    #                       rangeNotSatisfiable (416),
395
    #                       preconditionFailed (412),
396
    #                       itemNotFound (404),
397
    #                       unauthorized (401),
398
    #                       badRequest (400),
399
    #                       notModified (304)
400
    
401
    version = get_int_parameter(request, 'version')
402
    version_list = False
403
    if version is None and request.GET.get('version') == 'list':
404
        version_list = True
405
    try:
406
        meta = backend.get_object_meta(request.user, v_account, v_container, v_object, version)
407
        permissions = backend.get_object_permissions(request.user, v_account, v_container, v_object)
408
    except NameError:
409
        raise ItemNotFound('Object does not exist')
410
    except IndexError:
411
        raise ItemNotFound('Version does not exist')
412
    
413
    if permissions:
414
        meta['X-Object-Sharing'] = format_permissions(permissions)
415
    update_manifest_meta(request, v_account, meta)
416
    
417
    # Evaluate conditions.
418
    validate_modification_preconditions(request, meta)
419
    try:
420
        validate_matching_preconditions(request, meta)
421
    except NotModified:
422
        response = HttpResponse(status=304)
423
        response['ETag'] = meta['hash']
424
        return response
425
    
426
    # Reply with the version list.
427
    if version_list:
428
        if request.serialization == 'text':
429
            raise BadRequest('No format specified for version list.')
430
        
431
        d = {'versions': backend.list_versions(request.user, v_account, v_container, v_object)}
432
        if request.serialization == 'xml':
433
            d['object'] = v_object
434
            data = render_to_string('versions.xml', d)
435
        elif request.serialization  == 'json':
436
            data = json.dumps(d)
437
        
438
        response = HttpResponse(data, status=200)
439
        put_object_meta(response, meta)
440
        response['Content-Length'] = len(data)
441
        return response
442
    
443
    sizes = []
444
    hashmaps = []
445
    if 'X-Object-Manifest' in meta:
446
        try:
447
            src_container, src_name = split_container_object_string('/' + meta['X-Object-Manifest'])
448
            objects = backend.list_objects(request.user, v_account, src_container, prefix=src_name, virtual=False)
449
        except ValueError:
450
            raise BadRequest('Invalid X-Object-Manifest header')
451
        except NameError:
452
            raise ItemNotFound('Container does not exist')
453
        
454
        try:
455
            for x in objects:
456
                s, h = backend.get_object_hashmap(request.user, v_account, src_container, x[0], x[1])
457
                sizes.append(s)
458
                hashmaps.append(h)
459
        except NameError:
460
            raise ItemNotFound('Object does not exist')
461
        except IndexError:
462
            raise ItemNotFound('Version does not exist')
463
    else:
464
        try:
465
            s, h = backend.get_object_hashmap(request.user, v_account, v_container, v_object, version)
466
            sizes.append(s)
467
            hashmaps.append(h)
468
        except NameError:
469
            raise ItemNotFound('Object does not exist')
470
        except IndexError:
471
            raise ItemNotFound('Version does not exist')
472
    
473
    # Reply with the hashmap.
474
    if request.serialization != 'text':
475
        size = sum(sizes)
476
        hashmap = sum(hashmaps, [])
477
        d = {'block_size': backend.block_size, 'block_hash': backend.hash_algorithm, 'bytes': size, 'hashes': hashmap}
478
        if request.serialization == 'xml':
479
            d['object'] = v_object
480
            data = render_to_string('hashes.xml', d)
481
        elif request.serialization  == 'json':
482
            data = json.dumps(d)
483
        
484
        response = HttpResponse(data, status=200)
485
        put_object_meta(response, meta)
486
        response['Content-Length'] = len(data)
487
        return response
488
    
489
    return object_data_response(request, sizes, hashmaps, meta)
490

    
491
@api_method('PUT')
492
def object_write(request, v_account, v_container, v_object):
493
    # Normal Response Codes: 201
494
    # Error Response Codes: serviceUnavailable (503),
495
    #                       unprocessableEntity (422),
496
    #                       lengthRequired (411),
497
    #                       conflict (409),
498
    #                       itemNotFound (404),
499
    #                       unauthorized (401),
500
    #                       badRequest (400)
501
    
502
    copy_from = request.META.get('HTTP_X_COPY_FROM')
503
    move_from = request.META.get('HTTP_X_MOVE_FROM')
504
    if copy_from or move_from:
505
        # TODO: Why is this required? Copy this ammount?
506
        content_length = get_content_length(request)
507
        
508
        if move_from:
509
            try:
510
                src_container, src_name = split_container_object_string(move_from)
511
            except ValueError:
512
                raise BadRequest('Invalid X-Move-From header')
513
            copy_or_move_object(request, v_account, src_container, src_name, v_container, v_object, move=True)
514
        else:
515
            try:
516
                src_container, src_name = split_container_object_string(copy_from)
517
            except ValueError:
518
                raise BadRequest('Invalid X-Copy-From header')
519
            copy_or_move_object(request, v_account, src_container, src_name, v_container, v_object, move=False)
520
        return HttpResponse(status=201)
521
    
522
    meta = get_object_meta(request)
523
    permissions = get_sharing(request)
524
    content_length = -1
525
    if request.META.get('HTTP_TRANSFER_ENCODING') != 'chunked':
526
        content_length = get_content_length(request)
527
    # Should be BadRequest, but API says otherwise.
528
    if 'Content-Type' not in meta:
529
        raise LengthRequired('Missing Content-Type header')
530
    
531
    md5 = hashlib.md5()
532
    size = 0
533
    hashmap = []
534
    sock = raw_input_socket(request)
535
    for data in socket_read_iterator(sock, content_length, backend.block_size):
536
        # TODO: Raise 408 (Request Timeout) if this takes too long.
537
        # TODO: Raise 499 (Client Disconnect) if a length is defined and we stop before getting this much data.
538
        size += len(data)
539
        hashmap.append(backend.put_block(data))
540
        md5.update(data)
541
    
542
    meta['hash'] = md5.hexdigest().lower()
543
    etag = request.META.get('HTTP_ETAG')
544
    if etag and parse_etags(etag)[0].lower() != meta['hash']:
545
        raise UnprocessableEntity('Object ETag does not match')
546
    
547
    try:
548
        backend.update_object_hashmap(request.user, v_account, v_container, v_object, size, hashmap, meta, True, permissions)
549
    except NameError:
550
        raise ItemNotFound('Container does not exist')
551
    except ValueError:
552
        raise BadRequest('Invalid sharing header')
553
    except AttributeError:
554
        raise Conflict('Sharing already set above or below this path in the hierarchy')
555
    
556
    response = HttpResponse(status=201)
557
    response['ETag'] = meta['hash']
558
    return response
559

    
560
@api_method('COPY')
561
def object_copy(request, v_account, v_container, v_object):
562
    # Normal Response Codes: 201
563
    # Error Response Codes: serviceUnavailable (503),
564
    #                       itemNotFound (404),
565
    #                       unauthorized (401),
566
    #                       badRequest (400)
567
    
568
    dest_path = request.META.get('HTTP_DESTINATION')
569
    if not dest_path:
570
        raise BadRequest('Missing Destination header')
571
    try:
572
        dest_container, dest_name = split_container_object_string(dest_path)
573
    except ValueError:
574
        raise BadRequest('Invalid Destination header')
575
    copy_or_move_object(request, v_account, v_container, v_object, dest_container, dest_name, move=False)
576
    return HttpResponse(status=201)
577

    
578
@api_method('MOVE')
579
def object_move(request, v_account, v_container, v_object):
580
    # Normal Response Codes: 201
581
    # Error Response Codes: serviceUnavailable (503),
582
    #                       itemNotFound (404),
583
    #                       unauthorized (401),
584
    #                       badRequest (400)
585
    
586
    dest_path = request.META.get('HTTP_DESTINATION')
587
    if not dest_path:
588
        raise BadRequest('Missing Destination header')
589
    try:
590
        dest_container, dest_name = split_container_object_string(dest_path)
591
    except ValueError:
592
        raise BadRequest('Invalid Destination header')
593
    copy_or_move_object(request, v_account, v_container, v_object, dest_container, dest_name, move=True)
594
    return HttpResponse(status=201)
595

    
596
@api_method('POST')
597
def object_update(request, v_account, v_container, v_object):
598
    # Normal Response Codes: 202, 204
599
    # Error Response Codes: serviceUnavailable (503),
600
    #                       conflict (409),
601
    #                       itemNotFound (404),
602
    #                       unauthorized (401),
603
    #                       badRequest (400)
604
    
605
    meta = get_object_meta(request)
606
    permissions = get_sharing(request)
607
    content_type = meta.get('Content-Type')
608
    if content_type:
609
        del(meta['Content-Type']) # Do not allow changing the Content-Type.
610
    
611
    try:
612
        prev_meta = backend.get_object_meta(request.user, v_account, v_container, v_object)
613
    except NameError:
614
        raise ItemNotFound('Object does not exist')
615
    
616
    # Handle metadata changes.
617
    if len(meta) != 0:
618
        # Keep previous values of 'Content-Type' and 'hash'.
619
        for k in ('Content-Type', 'hash'):
620
            if k in prev_meta:
621
                meta[k] = prev_meta[k]
622
        try:
623
            backend.update_object_meta(request.user, v_account, v_container, v_object, meta, replace=True)
624
        except NameError:
625
            raise ItemNotFound('Object does not exist')
626
    
627
    # Handle permission changes.
628
    if permissions:
629
        try:
630
            backend.update_object_permissions(request.user, v_account, v_container, v_object, permissions)
631
        except NameError:
632
            raise ItemNotFound('Object does not exist')
633
        except ValueError:
634
            raise BadRequest('Invalid sharing header')
635
        except AttributeError:
636
            raise Conflict('Sharing already set above or below this path in the hierarchy')
637
    
638
    # TODO: Merge above functions with updating the hashmap if there is data in the request.
639
    
640
    # A Content-Type or Content-Range header may indicate data updates.
641
    if content_type is None:
642
        return HttpResponse(status=202)
643
    if content_type.startswith('multipart/byteranges'):
644
        # TODO: Support multiple update ranges.
645
        return HttpResponse(status=202)
646
    # Single range update. Range must be in Content-Range.
647
    # Based on: http://code.google.com/p/gears/wiki/ContentRangePostProposal
648
    # (with the addition that '*' is allowed for the range - will append).
649
    if content_type != 'application/octet-stream':
650
        return HttpResponse(status=202)
651
    content_range = request.META.get('HTTP_CONTENT_RANGE')
652
    if not content_range:
653
        return HttpResponse(status=202)
654
    ranges = get_content_range(request)
655
    if not ranges:
656
        return HttpResponse(status=202)
657
    # Require either a Content-Length, or 'chunked' Transfer-Encoding.
658
    content_length = -1
659
    if request.META.get('HTTP_TRANSFER_ENCODING') != 'chunked':
660
        content_length = get_content_length(request)
661
    
662
    try:
663
        size, hashmap = backend.get_object_hashmap(request.user, v_account, v_container, v_object)
664
    except NameError:
665
        raise ItemNotFound('Object does not exist')
666
    
667
    offset, length, total = ranges
668
    if offset is None:
669
        offset = size
670
    elif offset > size:
671
        raise RangeNotSatisfiable('Supplied offset is beyond object limits')
672
    if length is None or content_length == -1:
673
        length = content_length # Nevermind the error.
674
    elif length != content_length:
675
        raise BadRequest('Content length does not match range length')
676
    if total is not None and (total != size or offset >= size or (length > 0 and offset + length >= size)):
677
        raise RangeNotSatisfiable('Supplied range will change provided object limits')
678
    
679
    sock = raw_input_socket(request)
680
    data = ''
681
    for d in socket_read_iterator(sock, length, backend.block_size):
682
        # TODO: Raise 408 (Request Timeout) if this takes too long.
683
        # TODO: Raise 499 (Client Disconnect) if a length is defined and we stop before getting this much data.
684
        data += d
685
        bytes = put_object_block(hashmap, data, offset)
686
        offset += bytes
687
        data = data[bytes:]
688
    if len(data) > 0:
689
        put_object_block(hashmap, data, offset)
690
    
691
    if offset > size:
692
        size = offset
693
    meta = {'hash': hashmap_hash(hashmap)} # Update ETag.
694
    try:
695
        backend.update_object_hashmap(request.user, v_account, v_container, v_object, size, hashmap, meta, False)
696
    except NameError:
697
        raise ItemNotFound('Container does not exist')
698
    except ValueError:
699
        raise BadRequest('Invalid sharing header')
700
    except AttributeError:
701
        raise Conflict('Sharing already set above or below this path in the hierarchy')
702
    
703
    response = HttpResponse(status=204)
704
    response['ETag'] = meta['hash']
705
    return response
706

    
707
@api_method('DELETE')
708
def object_delete(request, v_account, v_container, v_object):
709
    # Normal Response Codes: 204
710
    # Error Response Codes: serviceUnavailable (503),
711
    #                       itemNotFound (404),
712
    #                       unauthorized (401),
713
    #                       badRequest (400)
714
    
715
    try:
716
        backend.delete_object(request.user, v_account, v_container, v_object)
717
    except NameError:
718
        raise ItemNotFound('Object does not exist')
719
    return HttpResponse(status=204)
720

    
721
@api_method()
722
def method_not_allowed(request):
723
    raise BadRequest('Method not allowed')