__init__.py 35.6 KB
Newer Older
Stavros Sachtouris's avatar
Stavros Sachtouris committed
1
# Copyright 2011-2013 GRNET S.A. All rights reserved.
Giorgos Verigakis's avatar
Giorgos Verigakis committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

34
from threading import enumerate as activethreads
35

36
from os import fstat
37
from hashlib import new as newhashlib
38
from time import time
Giorgos Verigakis's avatar
Giorgos Verigakis committed
39

40
from binascii import hexlify
Giorgos Verigakis's avatar
Giorgos Verigakis committed
41

42
from kamaki.clients import SilentEvent, sendlog
43
from kamaki.clients.pithos.rest_api import PithosRestClient
44
45
from kamaki.clients.storage import ClientError
from kamaki.clients.utils import path4url, filter_in
46
from StringIO import StringIO
Giorgos Verigakis's avatar
Giorgos Verigakis committed
47

48

49
def _pithos_hash(block, blockhash):
50
    h = newhashlib(blockhash)
Giorgos Verigakis's avatar
Giorgos Verigakis committed
51
52
53
    h.update(block.rstrip('\x00'))
    return h.hexdigest()

54

55
56
57
58
59
def _range_up(start, end, a_range):
    if a_range:
        (rstart, rend) = a_range.split('-')
        (rstart, rend) = (int(rstart), int(rend))
        if rstart > end or rend < start:
60
            return (0, 0)
61
62
63
64
65
66
        if rstart > start:
            start = rstart
        if rend < end:
            end = rend
    return (start, end)

67

68
class PithosClient(PithosRestClient):
Giorgos Verigakis's avatar
Giorgos Verigakis committed
69
    """GRNet Pithos API client"""
Giorgos Verigakis's avatar
Giorgos Verigakis committed
70

71
72
    def __init__(self, base_url, token, account=None, container=None):
        super(PithosClient, self).__init__(base_url, token, account, container)
73

74
    def purge_container(self, container=None):
75
76
        """Delete an empty container and destroy associated blocks
        """
77
78
79
        cnt_back_up = self.container
        try:
            self.container = container or cnt_back_up
80
            self.container_delete(until=unicode(time()))
81
82
        finally:
            self.container = cnt_back_up
83

84
85
86
87
88
89
90
91
92
93
    def upload_object_unchunked(
            self, obj, f,
            withHashFile=False,
            size=None,
            etag=None,
            content_encoding=None,
            content_disposition=None,
            content_type=None,
            sharing=None,
            public=None):
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
        """
        :param obj: (str) remote object path

        :param f: open file descriptor

        :param withHashFile: (bool)

        :param size: (int) size of data to upload

        :param etag: (str)

        :param content_encoding: (str)

        :param content_disposition: (str)

        :param content_type: (str)

        :param sharing: {'read':[user and/or grp names],
            'write':[usr and/or grp names]}

        :param public: (bool)
        """
116
        self._assert_container()
117
118
119
120
121
122
123

        if withHashFile:
            data = f.read()
            try:
                import json
                data = json.dumps(json.loads(data))
            except ValueError:
124
                raise ClientError('"%s" is not json-formated' % f.name, 1)
125
            except SyntaxError:
126
127
                msg = '"%s" is not a valid hashmap file' % f.name
                raise ClientError(msg, 1)
128
            f = StringIO(data)
129
        else:
130
            data = f.read(size) if size else f.read()
131
        self.object_put(
132
            obj,
133
134
135
136
137
138
139
140
141
            data=data,
            etag=etag,
            content_encoding=content_encoding,
            content_disposition=content_disposition,
            content_type=content_type,
            permissions=sharing,
            public=public,
            success=201)

142
143
144
145
146
147
148
149
    def create_object_by_manifestation(
            self, obj,
            etag=None,
            content_encoding=None,
            content_disposition=None,
            content_type=None,
            sharing=None,
            public=None):
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
        """
        :param obj: (str) remote object path

        :param etag: (str)

        :param content_encoding: (str)

        :param content_disposition: (str)

        :param content_type: (str)

        :param sharing: {'read':[user and/or grp names],
            'write':[usr and/or grp names]}

        :param public: (bool)
        """
166
        self._assert_container()
167
        self.object_put(
168
            obj,
169
170
171
172
173
174
175
176
177
            content_length=0,
            etag=etag,
            content_encoding=content_encoding,
            content_disposition=content_disposition,
            content_type=content_type,
            permissions=sharing,
            public=public,
            manifest='%s/%s' % (self.container, obj))

178
    # upload_* auxiliary methods
179
    def _put_block_async(self, data, hash, upload_gen=None):
180
181
182
183
184
        event = SilentEvent(method=self._put_block, data=data, hash=hash)
        event.start()
        return event

    def _put_block(self, data, hash):
185
186
        r = self.container_post(
            update=True,
187
188
189
190
191
192
            content_type='application/octet-stream',
            content_length=len(data),
            data=data,
            format='json')
        assert r.json[0] == hash, 'Local hash does not match server'

193
    def _get_file_block_info(self, fileobj, size=None):
194
        meta = self.get_container_info()
195
196
        blocksize = int(meta['x-container-block-size'])
        blockhash = meta['x-container-block-hash']
197
        size = size if size is not None else fstat(fileobj.fileno()).st_size
198
        nblocks = 1 + (size - 1) // blocksize
199
200
        return (blocksize, blockhash, size, nblocks)

201
202
203
204
205
206
207
208
209
210
211
212
213
214
    def _get_missing_hashes(
            self, obj, json,
            size=None,
            format='json',
            hashmap=True,
            content_type=None,
            etag=None,
            content_encoding=None,
            content_disposition=None,
            permissions=None,
            public=None,
            success=(201, 409)):
        r = self.object_put(
            obj,
215
216
217
218
219
220
221
222
223
            format='json',
            hashmap=True,
            content_type=content_type,
            json=json,
            etag=etag,
            content_encoding=content_encoding,
            content_disposition=content_disposition,
            permissions=permissions,
            public=public,
224
            success=success)
225
        return None if r.status_code == 201 else r.json
226

227
    def _culculate_blocks_for_upload(
228
229
            self, blocksize, blockhash, size, nblocks, hashes, hmap, fileobj,
            hash_cb=None):
230
        offset = 0
231
232
233
234
235
        if hash_cb:
            hash_gen = hash_cb(nblocks)
            hash_gen.next()

        for i in range(nblocks):
236
            block = fileobj.read(min(blocksize, size - offset))
237
            bytes = len(block)
238
            hash = _pithos_hash(block, blockhash)
239
            hashes.append(hash)
240
            hmap[hash] = (offset, bytes)
241
242
243
            offset += bytes
            if hash_cb:
                hash_gen.next()
Stavros Sachtouris's avatar
Stavros Sachtouris committed
244
        msg = 'Failed to calculate uploaded blocks:'
245
        ' Offset and object size do not match'
Stavros Sachtouris's avatar
Stavros Sachtouris committed
246
        assert offset == size, msg
247

248
249
    def _upload_missing_blocks(self, missing, hmap, fileobj, upload_gen=None):
        """upload missing blocks asynchronously"""
250

251
        self._init_thread_limit()
252

253
        flying = []
254
        failures = []
255
        for hash in missing:
256
            offset, bytes = hmap[hash]
257
258
            fileobj.seek(offset)
            data = fileobj.read(bytes)
259
            r = self._put_block_async(data, hash, upload_gen)
260
            flying.append(r)
261
262
            unfinished = self._watch_thread_limit(flying)
            for thread in set(flying).difference(unfinished):
263
264
                if thread.exception:
                    failures.append(thread)
265
                    if isinstance(
266
267
268
                            thread.exception,
                            ClientError) and thread.exception.status == 502:
                        self.POOLSIZE = self._thread_limit
269
                elif thread.isAlive():
270
                    flying.append(thread)
271
272
273
274
275
                elif upload_gen:
                    try:
                        upload_gen.next()
                    except:
                        pass
276
277
278
279
            flying = unfinished

        for thread in flying:
            thread.join()
280
281
            if thread.exception:
                failures.append(thread)
282
283
284
285
286
            elif upload_gen:
                try:
                    upload_gen.next()
                except:
                    pass
287

288
        return [failure.kwargs['hash'] for failure in failures]
289

290
291
292
293
294
295
296
297
298
299
300
    def upload_object(
            self, obj, f,
            size=None,
            hash_cb=None,
            upload_cb=None,
            etag=None,
            content_encoding=None,
            content_disposition=None,
            content_type=None,
            sharing=None,
            public=None):
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
        """Upload an object using multiple connections (threads)

        :param obj: (str) remote object path

        :param f: open file descriptor (rb)

        :param hash_cb: optional progress.bar object for calculating hashes

        :param upload_cb: optional progress.bar object for uploading

        :param etag: (str)

        :param content_encoding: (str)

        :param content_disposition: (str)

        :param content_type: (str)

        :param sharing: {'read':[user and/or grp names],
            'write':[usr and/or grp names]}

        :param public: (bool)
        """
324
        self._assert_container()
325

326
        #init
327
328
        block_info = (blocksize, blockhash, size, nblocks) =\
            self._get_file_block_info(f, size)
329
        (hashes, hmap, offset) = ([], {}, 0)
330
        if not content_type:
331
            content_type = 'application/octet-stream'
332

333
        self._culculate_blocks_for_upload(
334
            *block_info,
335
336
337
            hashes=hashes,
            hmap=hmap,
            fileobj=f,
338
339
340
            hash_cb=hash_cb)

        hashmap = dict(bytes=size, hashes=hashes)
341
342
        missing = self._get_missing_hashes(
            obj, hashmap,
343
344
345
346
347
348
349
            content_type=content_type,
            size=size,
            etag=etag,
            content_encoding=content_encoding,
            content_disposition=content_disposition,
            permissions=sharing,
            public=public)
350
351
352

        if missing is None:
            return
353

354
355
        if upload_cb:
            upload_gen = upload_cb(len(missing))
356
357
358
359
360
            for i in range(len(missing), len(hashmap['hashes']) + 1):
                try:
                    upload_gen.next()
                except:
                    upload_gen = None
361
362
363
        else:
            upload_gen = None

364
        retries = 7
365
        try:
366
            while retries:
367
                sendlog.info('%s blocks missing' % len(missing))
368
369
370
371
372
                num_of_blocks = len(missing)
                missing = self._upload_missing_blocks(
                    missing,
                    hmap,
                    f,
373
                    upload_gen)
374
375
376
377
378
                if missing:
                    if num_of_blocks == len(missing):
                        retries -= 1
                    else:
                        num_of_blocks = len(missing)
379
380
381
382
383
384
                else:
                    break
            if missing:
                raise ClientError(
                    '%s blocks failed to upload' % len(missing),
                    status=800)
385
        except KeyboardInterrupt:
386
            sendlog.info('- - - wait for threads to finish')
387
388
389
390
            for thread in activethreads():
                thread.join()
            raise

391
        self.object_put(
392
            obj,
393
394
395
396
397
398
            format='json',
            hashmap=True,
            content_type=content_type,
            json=hashmap,
            success=201)

399
    # download_* auxiliary methods
Stavros Sachtouris's avatar
Stavros Sachtouris committed
400
    def _get_remote_blocks_info(self, obj, **restargs):
401
        #retrieve object hashmap
402
        myrange = restargs.pop('data_range', None)
403
        hashmap = self.get_object_hashmap(obj, **restargs)
404
        restargs['data_range'] = myrange
405
406
407
        blocksize = int(hashmap['block_size'])
        blockhash = hashmap['block_hash']
        total_size = hashmap['bytes']
Stavros Sachtouris's avatar
Stavros Sachtouris committed
408
        #assert total_size/blocksize + 1 == len(hashmap['hashes'])
409
        map_dict = {}
Stavros Sachtouris's avatar
Stavros Sachtouris committed
410
        for i, h in enumerate(hashmap['hashes']):
411
412
413
414
415
            #  map_dict[h] = i   CHAGE
            if h in map_dict:
                map_dict[h].append(i)
            else:
                map_dict[h] = [i]
Stavros Sachtouris's avatar
Stavros Sachtouris committed
416
        return (blocksize, blockhash, total_size, hashmap['hashes'], map_dict)
417

418
419
420
    def _dump_blocks_sync(
            self, obj, remote_hashes, blocksize, total_size, dst, range,
            **args):
Stavros Sachtouris's avatar
Stavros Sachtouris committed
421
        for blockid, blockhash in enumerate(remote_hashes):
422
423
424
425
426
427
428
429
430
431
            if blockhash:
                start = blocksize * blockid
                is_last = start + blocksize > total_size
                end = (total_size - 1) if is_last else (start + blocksize - 1)
                (start, end) = _range_up(start, end, range)
                args['data_range'] = 'bytes=%s-%s' % (start, end)
                r = self.object_get(obj, success=(200, 206), **args)
                self._cb_next()
                dst.write(r.content)
                dst.flush()
Stavros Sachtouris's avatar
Stavros Sachtouris committed
432

433
434
    def _get_block_async(self, obj, **args):
        event = SilentEvent(self.object_get, obj, success=(200, 206), **args)
435
436
        event.start()
        return event
437

438
439
440
441
442
443
444
    def _hash_from_file(self, fp, start, size, blockhash):
        fp.seek(start)
        block = fp.read(size)
        h = newhashlib(blockhash)
        h.update(block.strip('\x00'))
        return hexlify(h.digest())

445
    def _thread2file(self, flying, blockids, local_file, offset=0, **restargs):
446
        """write the results of a greenleted rest call to a file
447
448
449
450
451

        :param offset: the offset of the file up to blocksize
        - e.g. if the range is 10-100, all blocks will be written to
        normal_position - 10
        """
452
453
454
455
456
457
458
459
        for i, (key, g) in enumerate(flying.items()):
            if g.isAlive():
                continue
            if g.exception:
                raise g.exception
            block = g.value.content
            for block_start in blockids[key]:
                local_file.seek(block_start + offset)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
460
461
                local_file.write(block)
                self._cb_next()
462
463
            flying.pop(key)
            blockids.pop(key)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
464
465
        local_file.flush()

466
467
468
    def _dump_blocks_async(
            self, obj, remote_hashes, blocksize, total_size, local_file,
            blockhash=None, resume=False, filerange=None, **restargs):
469
        file_size = fstat(local_file.fileno()).st_size if resume else 0
470
471
        flying = dict()
        blockid_dict = dict()
472
473
474
        offset = 0
        if filerange is not None:
            rstart = int(filerange.split('-')[0])
475
            offset = rstart if blocksize > rstart else rstart % blocksize
476

477
        self._init_thread_limit()
478
        for block_hash, blockids in remote_hashes.items():
479
480
481
482
483
484
485
            blockids = [blk * blocksize for blk in blockids]
            unsaved = [blk for blk in blockids if not (
                blk < file_size and block_hash == self._hash_from_file(
                        local_file, blk, blocksize, blockhash))]
            self._cb_next(len(blockids) - len(unsaved))
            if unsaved:
                key = unsaved[0]
486
                self._watch_thread_limit(flying.values())
487
488
                self._thread2file(
                    flying, blockid_dict, local_file, offset,
489
                    **restargs)
490
491
492
                end = total_size - 1 if key + blocksize > total_size\
                    else key + blocksize - 1
                start, end = _range_up(key, end, filerange)
493
494
495
496
497
                if start == end:
                    self._cb_next()
                    continue
                restargs['async_headers'] = {
                    'Range': 'bytes=%s-%s' % (start, end)}
498
499
                flying[key] = self._get_block_async(obj, **restargs)
                blockid_dict[key] = unsaved
Stavros Sachtouris's avatar
Stavros Sachtouris committed
500

501
502
        for thread in flying.values():
            thread.join()
503
        self._thread2file(flying, blockid_dict, local_file, offset, **restargs)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
504

505
506
507
508
509
510
511
512
513
514
    def download_object(
            self, obj, dst,
            download_cb=None,
            version=None,
            resume=False,
            range_str=None,
            if_match=None,
            if_none_match=None,
            if_modified_since=None,
            if_unmodified_since=None):
515
        """Download an object (multiple connections, random blocks)
516
517
518
519
520
521
522
523
524
525
526

        :param obj: (str) remote object path

        :param dst: open file descriptor (wb+)

        :param download_cb: optional progress.bar object for downloading

        :param version: (str) file version

        :param resume: (bool) if set, preserve already downloaded file parts

527
        :param range_str: (str) from, to are file positions (int) in bytes
528
529
530
531
532
533
534

        :param if_match: (str)

        :param if_none_match: (str)

        :param if_modified_since: (str) formated date

535
        :param if_unmodified_since: (str) formated date"""
536
537
538
        restargs = dict(
            version=version,
            data_range=None if range_str is None else 'bytes=%s' % range_str,
Stavros Sachtouris's avatar
Stavros Sachtouris committed
539
540
541
542
543
            if_match=if_match,
            if_none_match=if_none_match,
            if_modified_since=if_modified_since,
            if_unmodified_since=if_unmodified_since)

544
545
        (
            blocksize,
Stavros Sachtouris's avatar
Stavros Sachtouris committed
546
547
            blockhash,
            total_size,
548
            hash_list,
Stavros Sachtouris's avatar
Stavros Sachtouris committed
549
550
551
552
            remote_hashes) = self._get_remote_blocks_info(obj, **restargs)
        assert total_size >= 0

        if download_cb:
553
            self.progress_bar_gen = download_cb(len(hash_list))
Stavros Sachtouris's avatar
Stavros Sachtouris committed
554
555
556
            self._cb_next()

        if dst.isatty():
557
558
            self._dump_blocks_sync(
                obj,
559
560
561
562
                hash_list,
                blocksize,
                total_size,
                dst,
563
                range_str,
564
                **restargs)
565
        else:
566
567
            self._dump_blocks_async(
                obj,
568
569
570
571
572
573
                remote_hashes,
                blocksize,
                total_size,
                dst,
                blockhash,
                resume,
574
                range_str,
575
                **restargs)
576
            if not range_str:
577
                dst.truncate(total_size)
578

Stavros Sachtouris's avatar
Stavros Sachtouris committed
579
580
581
        self._complete_cb()

    #Command Progress Bar method
582
    def _cb_next(self, step=1):
Stavros Sachtouris's avatar
Stavros Sachtouris committed
583
584
        if hasattr(self, 'progress_bar_gen'):
            try:
585
                self.progress_bar_gen.next(step)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
586
587
            except:
                pass
588

Stavros Sachtouris's avatar
Stavros Sachtouris committed
589
590
591
    def _complete_cb(self):
        while True:
            try:
592
                self.progress_bar_gen.next(step)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
593
594
            except:
                break
Stavros Sachtouris's avatar
Stavros Sachtouris committed
595

596
597
598
599
600
601
602
603
    def get_object_hashmap(
            self, obj,
            version=None,
            if_match=None,
            if_none_match=None,
            if_modified_since=None,
            if_unmodified_since=None,
            data_range=None):
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
        """
        :param obj: (str) remote object path

        :param if_match: (str)

        :param if_none_match: (str)

        :param if_modified_since: (str) formated date

        :param if_unmodified_since: (str) formated date

        :param data_range: (str) from-to where from and to are integers
            denoting file positions in bytes

        :returns: (list)
        """
620
        try:
621
622
            r = self.object_get(
                obj,
623
624
625
626
627
628
629
                hashmap=True,
                version=version,
                if_etag_match=if_match,
                if_etag_not_match=if_none_match,
                if_modified_since=if_modified_since,
                if_unmodified_since=if_unmodified_since,
                data_range=data_range)
630
631
632
633
        except ClientError as err:
            if err.status == 304 or err.status == 412:
                return {}
            raise
634
        return r.json
635

636
    def set_account_group(self, group, usernames):
637
638
639
640
641
        """
        :param group: (str)

        :param usernames: (list)
        """
642
        self.account_post(update=True, groups={group: usernames})
Stavros Sachtouris's avatar
Stavros Sachtouris committed
643

644
    def del_account_group(self, group):
645
646
647
        """
        :param group: (str)
        """
648
        self.account_post(update=True, groups={group: []})
649

Stavros Sachtouris's avatar
Stavros Sachtouris committed
650
    def get_account_info(self, until=None):
651
652
653
654
655
        """
        :param until: (str) formated date

        :returns: (dict)
        """
Stavros Sachtouris's avatar
Stavros Sachtouris committed
656
        r = self.account_head(until=until)
657
        if r.status_code == 401:
658
            raise ClientError("No authorization", status=401)
659
        return r.headers
660

Stavros Sachtouris's avatar
Stavros Sachtouris committed
661
    def get_account_quota(self):
662
663
664
        """
        :returns: (dict)
        """
665
666
        return filter_in(
            self.get_account_info(),
667
668
            'X-Account-Policy-Quota',
            exactMatch=True)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
669
670

    def get_account_versioning(self):
671
672
673
        """
        :returns: (dict)
        """
674
675
        return filter_in(
            self.get_account_info(),
676
677
            'X-Account-Policy-Versioning',
            exactMatch=True)
678

Stavros Sachtouris's avatar
Stavros Sachtouris committed
679
    def get_account_meta(self, until=None):
680
681
682
683
684
        """
        :meta until: (str) formated date

        :returns: (dict)
        """
685
        return filter_in(self.get_account_info(until=until), 'X-Account-Meta-')
686

687
    def get_account_group(self):
688
689
690
        """
        :returns: (dict)
        """
691
692
        return filter_in(self.get_account_info(), 'X-Account-Group-')

693
    def set_account_meta(self, metapairs):
694
695
696
        """
        :param metapairs: (dict) {key1:val1, key2:val2, ...}
        """
697
        assert(type(metapairs) is dict)
698
        self.account_post(update=True, metadata=metapairs)
699

700
    def del_account_meta(self, metakey):
701
702
703
        """
        :param metakey: (str) metadatum key
        """
704
        self.account_post(update=True, metadata={metakey: ''})
705

Stavros Sachtouris's avatar
Stavros Sachtouris committed
706
    def set_account_quota(self, quota):
707
708
709
        """
        :param quota: (int)
        """
710
        self.account_post(update=True, quota=quota)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
711
712

    def set_account_versioning(self, versioning):
713
714
715
        """
        "param versioning: (str)
        """
716
        self.account_post(update=True, versioning=versioning)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
717

718
    def list_containers(self):
719
720
721
        """
        :returns: (dict)
        """
722
        r = self.account_get()
723
        return r.json
724

725
    def del_container(self, until=None, delimiter=None):
726
727
728
        """
        :param until: (str) formated date

729
        :param delimiter: (str) with / empty container
730
731
732
733
734

        :raises ClientError: 404 Container does not exist

        :raises ClientError: 409 Container is not empty
        """
735
        self._assert_container()
736
737
        r = self.container_delete(
            until=until,
738
739
            delimiter=delimiter,
            success=(204, 404, 409))
740
        if r.status_code == 404:
741
742
            raise ClientError(
                'Container "%s" does not exist' % self.container,
743
                r.status_code)
744
        elif r.status_code == 409:
745
746
            raise ClientError(
                'Container "%s" is not empty' % self.container,
747
                r.status_code)
748

749
    def get_container_versioning(self, container=None):
750
751
752
753
754
        """
        :param container: (str)

        :returns: (dict)
        """
755
756
757
758
759
760
761
762
        cnt_back_up = self.container
        try:
            self.container = container or cnt_back_up
            return filter_in(
                self.get_container_info(),
                'X-Container-Policy-Versioning')
        finally:
            self.container = cnt_back_up
Stavros Sachtouris's avatar
Stavros Sachtouris committed
763

764
    def get_container_quota(self, container=None):
765
766
767
768
769
        """
        :param container: (str)

        :returns: (dict)
        """
770
771
772
773
774
775
776
777
        cnt_back_up = self.container
        try:
            self.container = container or cnt_back_up
            return filter_in(
                self.get_container_info(),
                'X-Container-Policy-Quota')
        finally:
            self.container = cnt_back_up
778

779
    def get_container_info(self, until=None):
780
781
782
783
        """
        :param until: (str) formated date

        :returns: (dict)
784
785

        :raises ClientError: 404 Container not found
786
        """
787
788
789
790
791
        try:
            r = self.container_head(until=until)
        except ClientError as err:
            err.details.append('for container %s' % self.container)
            raise err
Stavros Sachtouris's avatar
Stavros Sachtouris committed
792
793
        return r.headers

794
    def get_container_meta(self, until=None):
795
796
797
798
799
        """
        :param until: (str) formated date

        :returns: (dict)
        """
800
801
        return filter_in(
            self.get_container_info(until=until),
802
            'X-Container-Meta')
803

804
    def get_container_object_meta(self, until=None):
805
806
807
808
809
        """
        :param until: (str) formated date

        :returns: (dict)
        """
810
811
        return filter_in(
            self.get_container_info(until=until),
812
            'X-Container-Object-Meta')
813

814
    def set_container_meta(self, metapairs):
815
816
817
        """
        :param metapairs: (dict) {key1:val1, key2:val2, ...}
        """
818
        assert(type(metapairs) is dict)
819
        self.container_post(update=True, metadata=metapairs)
820

Stavros Sachtouris's avatar
Stavros Sachtouris committed
821
    def del_container_meta(self, metakey):
822
823
824
        """
        :param metakey: (str) metadatum key
        """
825
        self.container_post(update=True, metadata={metakey: ''})
826

Stavros Sachtouris's avatar
Stavros Sachtouris committed
827
    def set_container_quota(self, quota):
828
829
830
        """
        :param quota: (int)
        """
831
        self.container_post(update=True, quota=quota)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
832
833

    def set_container_versioning(self, versioning):
834
835
836
        """
        :param versioning: (str)
        """
837
        self.container_post(update=True, versioning=versioning)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
838

839
    def del_object(self, obj, until=None, delimiter=None):
840
841
842
843
844
845
846
        """
        :param obj: (str) remote object path

        :param until: (str) formated date

        :param delimiter: (str)
        """
847
        self._assert_container()
848
        self.object_delete(obj, until=until, delimiter=delimiter)
849

850
851
852
853
854
855
    def set_object_meta(self, obj, metapairs):
        """
        :param obj: (str) remote object path

        :param metapairs: (dict) {key1:val1, key2:val2, ...}
        """
856
        assert(type(metapairs) is dict)
857
        self.object_post(obj, update=True, metadata=metapairs)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
858

859
    def del_object_meta(self, obj, metakey):
860
861
        """
        :param obj: (str) remote object path
862
863

        :param metakey: (str) metadatum key
864
        """
865
        self.object_post(obj, update=True, metadata={metakey: ''})
866

867
868
869
    def publish_object(self, obj):
        """
        :param obj: (str) remote object path
870
871

        :returns: (str) access url
872
        """
873
        self.object_post(obj, update=True, public=True)
874
        info = self.get_object_info(obj)
875
876
        pref, sep, rest = self.base_url.partition('//')
        base = rest.split('/')[0]
877
        return '%s%s%s/%s' % (pref, sep, base, info['x-object-public'])
Stavros Sachtouris's avatar
Stavros Sachtouris committed
878

879
880
881
882
    def unpublish_object(self, obj):
        """
        :param obj: (str) remote object path
        """
883
        self.object_post(obj, update=True, public=False)
884

Stavros Sachtouris's avatar
Stavros Sachtouris committed
885
    def get_object_info(self, obj, version=None):
886
887
888
889
890
891
892
        """
        :param obj: (str) remote object path

        :param version: (str)

        :returns: (dict)
        """
893
894
895
896
897
        try:
            r = self.object_head(obj, version=version)
            return r.headers
        except ClientError as ce:
            if ce.status == 404:
898
                raise ClientError('Object %s not found' % obj, status=404)
899
            raise
Stavros Sachtouris's avatar
Stavros Sachtouris committed
900
901

    def get_object_meta(self, obj, version=None):
902
903
904
905
906
907
908
        """
        :param obj: (str) remote object path

        :param version: (str)

        :returns: (dict)
        """
909
910
        return filter_in(
            self.get_object_info(obj, version=version),
911
            'X-Object-Meta')
Stavros Sachtouris's avatar
Stavros Sachtouris committed
912

913
914
915
916
917
918
    def get_object_sharing(self, obj):
        """
        :param obj: (str) remote object path

        :returns: (dict)
        """
919
920
        r = filter_in(
            self.get_object_info(obj),
921
922
            'X-Object-Sharing',
            exactMatch=True)
923
924
925
926
927
928
929
930
931
932
933
        reply = {}
        if len(r) > 0:
            perms = r['x-object-sharing'].split(';')
            for perm in perms:
                try:
                    perm.index('=')
                except ValueError:
                    raise ClientError('Incorrect reply format')
                (key, val) = perm.strip().split('=')
                reply[key] = val
        return reply
934

935
    def set_object_sharing(
936
937
            self, obj,
            read_permition=False, write_permition=False):
938
        """Give read/write permisions to an object.
939
940
941
942
943
944
945
946
947

        :param obj: (str) remote object path

        :param read_permition: (list - bool) users and user groups that get
            read permition for this object - False means all previous read
            permissions will be removed

        :param write_perimition: (list - bool) of users and user groups to get
           write permition for this object - False means all previous write
948
           permissions will be removed
949
        """
950

951
        perms = dict(read=read_permition or '', write=write_permition or '')
952
        self.object_post(obj, update=True, permissions=perms)
953

954
955
956
957
958
959
960
961
962
963
964
    def del_object_sharing(self, obj):
        """
        :param obj: (str) remote object path
        """
        self.set_object_sharing(obj)

    def append_object(self, obj, source_file, upload_cb=None):
        """
        :param obj: (str) remote object path

        :param source_file: open file descriptor
965

966
        :param upload_db: progress.bar for uploading
Stavros Sachtouris's avatar
Stavros Sachtouris committed
967
        """
968

969
        self._assert_container()
970
        meta = self.get_container_info()
Stavros Sachtouris's avatar
Stavros Sachtouris committed
971
        blocksize = int(meta['x-container-block-size'])
972
        filesize = fstat(source_file.fileno()).st_size
973
        nblocks = 1 + (filesize - 1) // blocksize
Stavros Sachtouris's avatar
Stavros Sachtouris committed
974
        offset = 0
975
        if upload_cb:
Stavros Sachtouris's avatar
Stavros Sachtouris committed
976
            upload_gen = upload_cb(nblocks)
977
            upload_gen.next()
Stavros Sachtouris's avatar
Stavros Sachtouris committed
978
979
980
        for i in range(nblocks):
            block = source_file.read(min(blocksize, filesize - offset))
            offset += len(block)
981
            self.object_post(
982
                obj,
983
984
985
986
987
988
                update=True,
                content_range='bytes */*',
                content_type='application/octet-stream',
                content_length=len(block),
                data=block)

989
            if upload_cb:
Stavros Sachtouris's avatar
Stavros Sachtouris committed
990
                upload_gen.next()
Stavros Sachtouris's avatar
Stavros Sachtouris committed
991

992
993
994
995
996
997
    def truncate_object(self, obj, upto_bytes):
        """
        :param obj: (str) remote object path

        :param upto_bytes: max number of bytes to leave on file
        """
998
        self.object_post(
999
            obj,
1000
1001
1002
1003
            update=True,
            content_range='bytes 0-%s/*' % upto_bytes,
            content_type='application/octet-stream',
            object_bytes=upto_bytes,
1004
            source_object=path4url(self.container, obj))
Stavros Sachtouris's avatar
Stavros Sachtouris committed
1005

1006
    def overwrite_object(self, obj, start, end, source_file, upload_cb=None):
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
        """Overwrite a part of an object from local source file

        :param obj: (str) remote object path

        :param start: (int) position in bytes to start overwriting from

        :param end: (int) position in bytes to stop overwriting at

        :param source_file: open file descriptor

        :param upload_db: progress.bar for uploading
Stavros Sachtouris's avatar
Stavros Sachtouris committed
1018
        """
1019

1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
        r = self.get_object_info(obj)
        rf_size = int(r['content-length'])
        if rf_size < int(start):
            raise ClientError(
                'Range start exceeds file size',
                status=416)
        elif rf_size < int(end):
            raise ClientError(
                'Range end exceeds file size',
                status=416)
1030
        self._assert_container()