__init__.py 36.7 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):
69
    """Synnefo 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
        """
        :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)
115
116

        :returns: (dict) created object metadata
117
        """
118
        self._assert_container()
119
120
121
122
123
124
125

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

145
146
147
148
149
150
151
152
    def create_object_by_manifestation(
            self, obj,
            etag=None,
            content_encoding=None,
            content_disposition=None,
            content_type=None,
            sharing=None,
            public=None):
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
        """
        :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)
168
169

        :returns: (dict) created object metadata
170
        """
171
        self._assert_container()
172
        r = self.object_put(
173
            obj,
174
175
176
177
178
179
180
181
            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))
182
        return r.headers
183

184
    # upload_* auxiliary methods
185
    def _put_block_async(self, data, hash, upload_gen=None):
186
187
188
189
190
        event = SilentEvent(method=self._put_block, data=data, hash=hash)
        event.start()
        return event

    def _put_block(self, data, hash):
191
192
        r = self.container_post(
            update=True,
193
194
195
196
197
198
            content_type='application/octet-stream',
            content_length=len(data),
            data=data,
            format='json')
        assert r.json[0] == hash, 'Local hash does not match server'

199
    def _get_file_block_info(self, fileobj, size=None):
200
        meta = self.get_container_info()
201
202
        blocksize = int(meta['x-container-block-size'])
        blockhash = meta['x-container-block-hash']
203
        size = size if size is not None else fstat(fileobj.fileno()).st_size
204
        nblocks = 1 + (size - 1) // blocksize
205
206
        return (blocksize, blockhash, size, nblocks)

207
    def _create_or_get_missing_hashes(
208
209
210
211
212
            self, obj, json,
            size=None,
            format='json',
            hashmap=True,
            content_type=None,
213
214
            if_etag_match=None,
            if_etag_not_match=None,
215
216
217
218
219
220
221
            content_encoding=None,
            content_disposition=None,
            permissions=None,
            public=None,
            success=(201, 409)):
        r = self.object_put(
            obj,
222
223
224
225
            format='json',
            hashmap=True,
            content_type=content_type,
            json=json,
226
227
            if_etag_match=if_etag_match,
            if_etag_not_match=if_etag_not_match,
228
229
230
231
            content_encoding=content_encoding,
            content_disposition=content_disposition,
            permissions=permissions,
            public=public,
232
            success=success)
233
        return (None if r.status_code == 201 else r.json), r.headers
234

235
    def _calculate_blocks_for_upload(
236
237
            self, blocksize, blockhash, size, nblocks, hashes, hmap, fileobj,
            hash_cb=None):
238
        offset = 0
239
240
241
242
243
        if hash_cb:
            hash_gen = hash_cb(nblocks)
            hash_gen.next()

        for i in range(nblocks):
244
            block = fileobj.read(min(blocksize, size - offset))
245
            bytes = len(block)
246
            hash = _pithos_hash(block, blockhash)
247
            hashes.append(hash)
248
            hmap[hash] = (offset, bytes)
249
250
251
            offset += bytes
            if hash_cb:
                hash_gen.next()
Stavros Sachtouris's avatar
Stavros Sachtouris committed
252
        msg = 'Failed to calculate uploaded blocks:'
253
        ' Offset and object size do not match'
Stavros Sachtouris's avatar
Stavros Sachtouris committed
254
        assert offset == size, msg
255

256
257
    def _upload_missing_blocks(self, missing, hmap, fileobj, upload_gen=None):
        """upload missing blocks asynchronously"""
258

259
        self._init_thread_limit()
260

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

        for thread in flying:
            thread.join()
288
289
            if thread.exception:
                failures.append(thread)
290
291
292
293
294
            elif upload_gen:
                try:
                    upload_gen.next()
                except:
                    pass
295

296
        return [failure.kwargs['hash'] for failure in failures]
297

298
299
300
301
302
303
    def upload_object(
            self, obj, f,
            size=None,
            hash_cb=None,
            upload_cb=None,
            etag=None,
304
            if_etag_match=None,
305
            if_not_exist=None,
306
307
308
309
310
            content_encoding=None,
            content_disposition=None,
            content_type=None,
            sharing=None,
            public=None):
311
312
313
314
315
316
317
318
319
320
321
322
        """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)

323
324
325
        :param if_etag_match: (str) Push that value to if-match header at file
            creation

326
327
328
329
330
        :param if_not_exist: (bool) If true, the file will be uploaded ONLY if
            it does not exist remotely, otherwise the operation will fail.
            Involves the case of an object with the same path is created while
            the object is being uploaded.

331
332
333
334
335
336
337
338
339
340
341
        :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)
        """
342
        self._assert_container()
343

344
        #init
345
346
        block_info = (blocksize, blockhash, size, nblocks) =\
            self._get_file_block_info(f, size)
347
        (hashes, hmap, offset) = ([], {}, 0)
348
        if not content_type:
349
            content_type = 'application/octet-stream'
350

351
        self._calculate_blocks_for_upload(
352
            *block_info,
353
354
355
            hashes=hashes,
            hmap=hmap,
            fileobj=f,
356
357
358
            hash_cb=hash_cb)

        hashmap = dict(bytes=size, hashes=hashes)
359
        missing, obj_headers = self._create_or_get_missing_hashes(
360
            obj, hashmap,
361
362
            content_type=content_type,
            size=size,
363
364
            if_etag_match=if_etag_match,
            if_etag_not_match='*' if if_not_exist else None,
365
366
367
368
            content_encoding=content_encoding,
            content_disposition=content_disposition,
            permissions=sharing,
            public=public)
369
370

        if missing is None:
371
            return obj_headers
372

373
374
        if upload_cb:
            upload_gen = upload_cb(len(missing))
375
376
377
378
379
            for i in range(len(missing), len(hashmap['hashes']) + 1):
                try:
                    upload_gen.next()
                except:
                    upload_gen = None
380
381
382
        else:
            upload_gen = None

383
        retries = 7
384
        try:
385
            while retries:
386
                sendlog.info('%s blocks missing' % len(missing))
387
388
389
390
391
                num_of_blocks = len(missing)
                missing = self._upload_missing_blocks(
                    missing,
                    hmap,
                    f,
392
                    upload_gen)
393
394
395
396
397
                if missing:
                    if num_of_blocks == len(missing):
                        retries -= 1
                    else:
                        num_of_blocks = len(missing)
398
399
400
401
402
403
                else:
                    break
            if missing:
                raise ClientError(
                    '%s blocks failed to upload' % len(missing),
                    status=800)
404
        except KeyboardInterrupt:
405
            sendlog.info('- - - wait for threads to finish')
406
407
408
409
            for thread in activethreads():
                thread.join()
            raise

410
        r = self.object_put(
411
            obj,
412
413
414
            format='json',
            hashmap=True,
            content_type=content_type,
415
            if_etag_match=if_etag_match,
416
417
            if_etag_not_match='*' if if_not_exist else None,
            etag=etag,
418
            json=hashmap,
419
420
            permissions=sharing,
            public=public,
421
            success=201)
422
        return r.headers
423

424
    # download_* auxiliary methods
Stavros Sachtouris's avatar
Stavros Sachtouris committed
425
    def _get_remote_blocks_info(self, obj, **restargs):
426
        #retrieve object hashmap
427
        myrange = restargs.pop('data_range', None)
428
        hashmap = self.get_object_hashmap(obj, **restargs)
429
        restargs['data_range'] = myrange
430
431
432
        blocksize = int(hashmap['block_size'])
        blockhash = hashmap['block_hash']
        total_size = hashmap['bytes']
Stavros Sachtouris's avatar
Stavros Sachtouris committed
433
        #assert total_size/blocksize + 1 == len(hashmap['hashes'])
434
        map_dict = {}
Stavros Sachtouris's avatar
Stavros Sachtouris committed
435
        for i, h in enumerate(hashmap['hashes']):
436
437
438
439
440
            #  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
441
        return (blocksize, blockhash, total_size, hashmap['hashes'], map_dict)
442

443
444
445
    def _dump_blocks_sync(
            self, obj, remote_hashes, blocksize, total_size, dst, range,
            **args):
Stavros Sachtouris's avatar
Stavros Sachtouris committed
446
        for blockid, blockhash in enumerate(remote_hashes):
447
448
449
450
451
452
453
454
455
456
            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
457

458
459
    def _get_block_async(self, obj, **args):
        event = SilentEvent(self.object_get, obj, success=(200, 206), **args)
460
461
        event.start()
        return event
462

463
464
465
466
467
468
469
    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())

470
    def _thread2file(self, flying, blockids, local_file, offset=0, **restargs):
471
        """write the results of a greenleted rest call to a file
472
473
474
475
476

        :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
        """
477
478
479
480
481
482
483
484
        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
485
486
                local_file.write(block)
                self._cb_next()
487
488
            flying.pop(key)
            blockids.pop(key)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
489
490
        local_file.flush()

491
492
493
    def _dump_blocks_async(
            self, obj, remote_hashes, blocksize, total_size, local_file,
            blockhash=None, resume=False, filerange=None, **restargs):
494
        file_size = fstat(local_file.fileno()).st_size if resume else 0
495
496
        flying = dict()
        blockid_dict = dict()
497
498
499
        offset = 0
        if filerange is not None:
            rstart = int(filerange.split('-')[0])
500
            offset = rstart if blocksize > rstart else rstart % blocksize
501

502
        self._init_thread_limit()
503
        for block_hash, blockids in remote_hashes.items():
504
505
506
507
508
509
510
            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]
511
                self._watch_thread_limit(flying.values())
512
513
                self._thread2file(
                    flying, blockid_dict, local_file, offset,
514
                    **restargs)
515
516
517
                end = total_size - 1 if key + blocksize > total_size\
                    else key + blocksize - 1
                start, end = _range_up(key, end, filerange)
518
519
520
521
522
                if start == end:
                    self._cb_next()
                    continue
                restargs['async_headers'] = {
                    'Range': 'bytes=%s-%s' % (start, end)}
523
524
                flying[key] = self._get_block_async(obj, **restargs)
                blockid_dict[key] = unsaved
Stavros Sachtouris's avatar
Stavros Sachtouris committed
525

526
527
        for thread in flying.values():
            thread.join()
528
        self._thread2file(flying, blockid_dict, local_file, offset, **restargs)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
529

530
531
532
533
534
535
536
537
538
539
    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):
540
        """Download an object (multiple connections, random blocks)
541
542
543
544
545
546
547
548
549
550
551

        :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

552
        :param range_str: (str) from, to are file positions (int) in bytes
553
554
555
556
557
558
559

        :param if_match: (str)

        :param if_none_match: (str)

        :param if_modified_since: (str) formated date

560
        :param if_unmodified_since: (str) formated date"""
561
562
563
        restargs = dict(
            version=version,
            data_range=None if range_str is None else 'bytes=%s' % range_str,
Stavros Sachtouris's avatar
Stavros Sachtouris committed
564
565
566
567
568
            if_match=if_match,
            if_none_match=if_none_match,
            if_modified_since=if_modified_since,
            if_unmodified_since=if_unmodified_since)

569
570
        (
            blocksize,
Stavros Sachtouris's avatar
Stavros Sachtouris committed
571
572
            blockhash,
            total_size,
573
            hash_list,
Stavros Sachtouris's avatar
Stavros Sachtouris committed
574
575
576
577
            remote_hashes) = self._get_remote_blocks_info(obj, **restargs)
        assert total_size >= 0

        if download_cb:
578
            self.progress_bar_gen = download_cb(len(hash_list))
Stavros Sachtouris's avatar
Stavros Sachtouris committed
579
580
581
            self._cb_next()

        if dst.isatty():
582
583
            self._dump_blocks_sync(
                obj,
584
585
586
587
                hash_list,
                blocksize,
                total_size,
                dst,
588
                range_str,
589
                **restargs)
590
        else:
591
592
            self._dump_blocks_async(
                obj,
593
594
595
596
597
598
                remote_hashes,
                blocksize,
                total_size,
                dst,
                blockhash,
                resume,
599
                range_str,
600
                **restargs)
601
            if not range_str:
602
                dst.truncate(total_size)
603

Stavros Sachtouris's avatar
Stavros Sachtouris committed
604
605
606
        self._complete_cb()

    #Command Progress Bar method
607
    def _cb_next(self, step=1):
Stavros Sachtouris's avatar
Stavros Sachtouris committed
608
609
        if hasattr(self, 'progress_bar_gen'):
            try:
610
611
                for i in xrange(step):
                    self.progress_bar_gen.next()
Stavros Sachtouris's avatar
Stavros Sachtouris committed
612
613
            except:
                pass
614

Stavros Sachtouris's avatar
Stavros Sachtouris committed
615
616
617
    def _complete_cb(self):
        while True:
            try:
618
                self.progress_bar_gen.next()
Stavros Sachtouris's avatar
Stavros Sachtouris committed
619
620
            except:
                break
Stavros Sachtouris's avatar
Stavros Sachtouris committed
621

622
623
624
625
626
627
628
629
    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):
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
        """
        :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)
        """
646
        try:
647
648
            r = self.object_get(
                obj,
649
650
651
652
653
654
655
                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)
656
657
658
659
        except ClientError as err:
            if err.status == 304 or err.status == 412:
                return {}
            raise
660
        return r.json
661

662
    def set_account_group(self, group, usernames):
663
664
665
666
667
        """
        :param group: (str)

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

670
    def del_account_group(self, group):
671
672
673
        """
        :param group: (str)
        """
674
        self.account_post(update=True, groups={group: []})
675

Stavros Sachtouris's avatar
Stavros Sachtouris committed
676
    def get_account_info(self, until=None):
677
678
679
680
681
        """
        :param until: (str) formated date

        :returns: (dict)
        """
Stavros Sachtouris's avatar
Stavros Sachtouris committed
682
        r = self.account_head(until=until)
683
        if r.status_code == 401:
684
            raise ClientError("No authorization", status=401)
685
        return r.headers
686

Stavros Sachtouris's avatar
Stavros Sachtouris committed
687
    def get_account_quota(self):
688
689
690
        """
        :returns: (dict)
        """
691
692
        return filter_in(
            self.get_account_info(),
693
694
            'X-Account-Policy-Quota',
            exactMatch=True)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
695
696

    def get_account_versioning(self):
697
698
699
        """
        :returns: (dict)
        """
700
701
        return filter_in(
            self.get_account_info(),
702
703
            'X-Account-Policy-Versioning',
            exactMatch=True)
704

Stavros Sachtouris's avatar
Stavros Sachtouris committed
705
    def get_account_meta(self, until=None):
706
707
708
709
710
        """
        :meta until: (str) formated date

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

713
    def get_account_group(self):
714
715
716
        """
        :returns: (dict)
        """
717
718
        return filter_in(self.get_account_info(), 'X-Account-Group-')

719
    def set_account_meta(self, metapairs):
720
721
722
        """
        :param metapairs: (dict) {key1:val1, key2:val2, ...}
        """
723
        assert(type(metapairs) is dict)
724
        self.account_post(update=True, metadata=metapairs)
725

726
    def del_account_meta(self, metakey):
727
728
729
        """
        :param metakey: (str) metadatum key
        """
730
        self.account_post(update=True, metadata={metakey: ''})
731

732
    """
Stavros Sachtouris's avatar
Stavros Sachtouris committed
733
    def set_account_quota(self, quota):
734
        ""
735
        :param quota: (int)
736
        ""
737
        self.account_post(update=True, quota=quota)
738
    """
Stavros Sachtouris's avatar
Stavros Sachtouris committed
739
740

    def set_account_versioning(self, versioning):
741
742
743
        """
        "param versioning: (str)
        """
744
        self.account_post(update=True, versioning=versioning)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
745

746
    def list_containers(self):
747
748
749
        """
        :returns: (dict)
        """
750
        r = self.account_get()
751
        return r.json
752

753
    def del_container(self, until=None, delimiter=None):
754
755
756
        """
        :param until: (str) formated date

757
        :param delimiter: (str) with / empty container
758
759
760
761
762

        :raises ClientError: 404 Container does not exist

        :raises ClientError: 409 Container is not empty
        """
763
        self._assert_container()
764
765
        r = self.container_delete(
            until=until,
766
767
            delimiter=delimiter,
            success=(204, 404, 409))
768
        if r.status_code == 404:
769
770
            raise ClientError(
                'Container "%s" does not exist' % self.container,
771
                r.status_code)
772
        elif r.status_code == 409:
773
774
            raise ClientError(
                'Container "%s" is not empty' % self.container,
775
                r.status_code)
776

777
    def get_container_versioning(self, container=None):
778
779
780
781
782
        """
        :param container: (str)

        :returns: (dict)
        """
783
784
785
786
787
788
789
790
        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
791

792
    def get_container_limit(self, container=None):
793
794
795
796
797
        """
        :param container: (str)

        :returns: (dict)
        """
798
799
800
801
802
803
804
805
        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
806

807
    def get_container_info(self, until=None):
808
809
810
811
        """
        :param until: (str) formated date

        :returns: (dict)
812
813

        :raises ClientError: 404 Container not found
814
        """
815
816
817
818
819
        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
820
821
        return r.headers

822
    def get_container_meta(self, until=None):
823
824
825
826
827
        """
        :param until: (str) formated date

        :returns: (dict)
        """
828
829
        return filter_in(
            self.get_container_info(until=until),
830
            'X-Container-Meta')
831

832
    def get_container_object_meta(self, until=None):
833
834
835
836
837
        """
        :param until: (str) formated date

        :returns: (dict)
        """
838
839
        return filter_in(
            self.get_container_info(until=until),
840
            'X-Container-Object-Meta')
841

842
    def set_container_meta(self, metapairs):
843
844
845
        """
        :param metapairs: (dict) {key1:val1, key2:val2, ...}
        """
846
        assert(type(metapairs) is dict)
847
        self.container_post(update=True, metadata=metapairs)
848

Stavros Sachtouris's avatar
Stavros Sachtouris committed
849
    def del_container_meta(self, metakey):
850
851
852
        """
        :param metakey: (str) metadatum key
        """
853
        self.container_post(update=True, metadata={metakey: ''})
854

855
    def set_container_limit(self, limit):
856
        """
857
        :param limit: (int)
858
        """
859
        self.container_post(update=True, quota=limit)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
860
861

    def set_container_versioning(self, versioning):
862
863
864
        """
        :param versioning: (str)
        """
865
        self.container_post(update=True, versioning=versioning)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
866

867
    def del_object(self, obj, until=None, delimiter=None):
868
869
870
871
872
873
874
        """
        :param obj: (str) remote object path

        :param until: (str) formated date

        :param delimiter: (str)
        """
875
        self._assert_container()
876
        self.object_delete(obj, until=until, delimiter=delimiter)
877

878
879
880
881
882
883
    def set_object_meta(self, obj, metapairs):
        """
        :param obj: (str) remote object path

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

887
    def del_object_meta(self, obj, metakey):
888
889
        """
        :param obj: (str) remote object path
890
891

        :param metakey: (str) metadatum key
892
        """
893
        self.object_post(obj, update=True, metadata={metakey: ''})
894

895
896
897
    def publish_object(self, obj):
        """
        :param obj: (str) remote object path
898
899

        :returns: (str) access url
900
        """
901
        self.object_post(obj, update=True, public=True)
902
        info = self.get_object_info(obj)
903
904
        pref, sep, rest = self.base_url.partition('//')
        base = rest.split('/')[0]
905
        return '%s%s%s/%s' % (pref, sep, base, info['x-object-public'])
Stavros Sachtouris's avatar
Stavros Sachtouris committed
906

907
908
909
910
    def unpublish_object(self, obj):
        """
        :param obj: (str) remote object path
        """
911
        self.object_post(obj, update=True, public=False)
912

Stavros Sachtouris's avatar
Stavros Sachtouris committed
913
    def get_object_info(self, obj, version=None):
914
915
916
917
918
919
920
        """
        :param obj: (str) remote object path

        :param version: (str)

        :returns: (dict)
        """
921
922
923
924
925
        try:
            r = self.object_head(obj, version=version)
            return r.headers
        except ClientError as ce:
            if ce.status == 404:
926
                raise ClientError('Object %s not found' % obj, status=404)
927
            raise
Stavros Sachtouris's avatar
Stavros Sachtouris committed
928
929

    def get_object_meta(self, obj, version=None):
930
931
932
933
934
935
936
        """
        :param obj: (str) remote object path

        :param version: (str)

        :returns: (dict)
        """
937
938
        return filter_in(
            self.get_object_info(obj, version=version),
939
            'X-Object-Meta')
Stavros Sachtouris's avatar
Stavros Sachtouris committed
940

941
942
943
944
945
946
    def get_object_sharing(self, obj):
        """
        :param obj: (str) remote object path

        :returns: (dict)
        """
947
948
        r = filter_in(
            self.get_object_info(obj),
949
950
            'X-Object-Sharing',
            exactMatch=True)
951
952
953
954
955
956
957
958
959
960
961
        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
962

963
    def set_object_sharing(
964
965
            self, obj,
            read_permition=False, write_permition=False):
966
        """Give read/write permisions to an object.
967
968
969
970
971
972
973
974
975

        :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
976
           permissions will be removed
977
        """
978

979
        perms = dict(read=read_permition or '', write=write_permition or '')
980
        self.object_post(obj, update=True, permissions=perms)
981

982
983
984
985
986
987
988
989
990
991
992
    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
993

994
        :param upload_db: progress.bar for uploading
Stavros Sachtouris's avatar
Stavros Sachtouris committed
995
        """