__init__.py 49.8 KB
Newer Older
1
# Copyright 2011-2015 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
39
from StringIO import StringIO
Giorgos Verigakis's avatar
Giorgos Verigakis committed
40

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

43
from kamaki.clients import SilentEvent, sendlog
44
from kamaki.clients.pithos.rest_api import PithosRestClient
45
from kamaki.clients.storage import ClientError
46
from kamaki.clients.utils import path4url, filter_in, readall
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 60 61 62 63 64 65 66 67 68
def _range_up(start, end, max_value, a_range):
    """
    :param start: (int) the window bottom

    :param end: (int) the window top

    :param max_value: (int) maximum accepted value

    :param a_range: (str) a range string in the form X[,X'[,X''[...]]]
        where X: x|x-y|-x where x < y and x, y natural numbers

    :returns: (str) a range string cut-off for the start-end range
        an empty response means this window is out of range
    """
Stavros Sachtouris's avatar
Stavros Sachtouris committed
69 70 71 72 73
    assert start >= 0, '_range_up called w. start(%s) < 0' % start
    assert end >= start, '_range_up called w. end(%s) < start(%s)' % (
        end, start)
    assert end <= max_value, '_range_up called w. max_value(%s) < end(%s)' % (
        max_value, end)
74 75 76 77 78 79 80
    if not a_range:
        return '%s-%s' % (start, end)
    selected = []
    for some_range in a_range.split(','):
        v0, sep, v1 = some_range.partition('-')
        if v0:
            v0 = int(v0)
81
            if sep:
82 83 84 85 86 87 88 89
                v1 = int(v1)
                if v1 < start or v0 > end or v1 < v0:
                    continue
                v0 = v0 if v0 > start else start
                v1 = v1 if v1 < end else end
                selected.append('%s-%s' % (v0, v1))
            elif v0 < start:
                continue
90
            else:
91 92
                v1 = v0 if v0 <= end else end
                selected.append('%s-%s' % (start, v1))
93
        else:
94 95 96 97 98 99
            v1 = int(v1)
            if max_value - v1 > end:
                continue
            v0 = (max_value - v1) if max_value - v1 > start else start
            selected.append('%s-%s' % (v0, end))
    return ','.join(selected)
100

101

102
class PithosClient(PithosRestClient):
103
    """Synnefo Pithos+ API client"""
Giorgos Verigakis's avatar
Giorgos Verigakis committed
104

105 106 107
    def __init__(self, endpoint_url, token, account=None, container=None):
        super(PithosClient, self).__init__(
            endpoint_url, token, account, container)
108

109 110
    def create_container(
            self,
111
            container=None, sizelimit=None, versioning=None, metadata=None,
112
            project_id=None, **kwargs):
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
        """
        :param container: (str) if not given, self.container is used instead

        :param sizelimit: (int) container total size limit in bytes

        :param versioning: (str) can be auto or whatever supported by server

        :param metadata: (dict) Custom user-defined metadata of the form
            { 'name1': 'value1', 'name2': 'value2', ... }

        :returns: (dict) response headers
        """
        cnt_back_up = self.container
        try:
            self.container = container or cnt_back_up
            r = self.container_put(
129
                quota=sizelimit, versioning=versioning, metadata=metadata,
130
                project_id=project_id, **kwargs)
131 132 133 134
            return r.headers
        finally:
            self.container = cnt_back_up

135
    def purge_container(self, container=None):
Stavros Sachtouris's avatar
Stavros Sachtouris committed
136
        """Delete an empty container and destroy associated blocks"""
137 138 139
        cnt_back_up = self.container
        try:
            self.container = container or cnt_back_up
140
            r = self.container_delete(until=unicode(time()))
141 142
        finally:
            self.container = cnt_back_up
143
        return r.headers
144

145 146 147 148 149 150 151 152 153 154
    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):
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
        """
        :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)
176 177

        :returns: (dict) created object metadata
178
        """
179
        self._assert_container()
180 181 182 183 184 185 186

        if withHashFile:
            data = f.read()
            try:
                import json
                data = json.dumps(json.loads(data))
            except ValueError:
187
                raise ClientError('"%s" is not json-formated' % f.name, 1)
188
            except SyntaxError:
189 190
                msg = '"%s" is not a valid hashmap file' % f.name
                raise ClientError(msg, 1)
191
            f = StringIO(data)
192
        else:
193
            data = readall(f, size) if size else f.read()
194
        r = self.object_put(
195
            obj,
196 197 198 199 200 201 202 203
            data=data,
            etag=etag,
            content_encoding=content_encoding,
            content_disposition=content_disposition,
            content_type=content_type,
            permissions=sharing,
            public=public,
            success=201)
204
        return r.headers
205

206 207 208 209 210 211 212 213
    def create_object_by_manifestation(
            self, obj,
            etag=None,
            content_encoding=None,
            content_disposition=None,
            content_type=None,
            sharing=None,
            public=None):
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
        """
        :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)
229 230

        :returns: (dict) created object metadata
231
        """
232
        self._assert_container()
233
        r = self.object_put(
234
            obj,
235 236 237 238 239 240 241 242
            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))
243
        return r.headers
244

245
    # upload_* auxiliary methods
246
    def _put_block_async(self, data, hash):
247 248 249 250 251
        event = SilentEvent(method=self._put_block, data=data, hash=hash)
        event.start()
        return event

    def _put_block(self, data, hash):
252 253
        r = self.container_post(
            update=True,
254 255 256 257 258 259
            content_type='application/octet-stream',
            content_length=len(data),
            data=data,
            format='json')
        assert r.json[0] == hash, 'Local hash does not match server'

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    def _get_file_block_info(self, fileobj, size=None, cache=None):
        """
        :param fileobj: (file descriptor) source

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

        :param cache: (dict) if provided, cache container info response to
        avoid redundant calls
        """
        if isinstance(cache, dict):
            try:
                meta = cache[self.container]
            except KeyError:
                meta = self.get_container_info()
                cache[self.container] = meta
        else:
            meta = self.get_container_info()
277 278
        blocksize = int(meta['x-container-block-size'])
        blockhash = meta['x-container-block-hash']
279
        size = size if size is not None else fstat(fileobj.fileno()).st_size
280
        nblocks = 1 + (size - 1) // blocksize
281 282
        return (blocksize, blockhash, size, nblocks)

283
    def _create_object_or_get_missing_hashes(
284 285 286 287 288
            self, obj, json,
            size=None,
            format='json',
            hashmap=True,
            content_type=None,
289 290
            if_etag_match=None,
            if_etag_not_match=None,
291 292 293 294 295 296 297
            content_encoding=None,
            content_disposition=None,
            permissions=None,
            public=None,
            success=(201, 409)):
        r = self.object_put(
            obj,
298 299 300 301
            format='json',
            hashmap=True,
            content_type=content_type,
            json=json,
302 303
            if_etag_match=if_etag_match,
            if_etag_not_match=if_etag_not_match,
304 305 306 307
            content_encoding=content_encoding,
            content_disposition=content_disposition,
            permissions=permissions,
            public=public,
308
            success=success)
309
        return (None if r.status_code == 201 else r.json), r.headers
310

311
    def _calculate_blocks_for_upload(
312 313
            self, blocksize, blockhash, size, nblocks, hashes, hmap, fileobj,
            hash_cb=None):
314
        offset = 0
315 316 317 318
        if hash_cb:
            hash_gen = hash_cb(nblocks)
            hash_gen.next()

319
        for i in xrange(nblocks):
320
            block = readall(fileobj, min(blocksize, size - offset))
321
            bytes = len(block)
322 323
            if bytes <= 0:
                break
324
            hash = _pithos_hash(block, blockhash)
325
            hashes.append(hash)
326
            hmap[hash] = (offset, bytes)
327 328 329
            offset += bytes
            if hash_cb:
                hash_gen.next()
330 331
        msg = ('Failed to calculate uploading blocks: '
               'read bytes(%s) != requested size (%s)' % (offset, size))
Stavros Sachtouris's avatar
Stavros Sachtouris committed
332
        assert offset == size, msg
333

334 335
    def _upload_missing_blocks(self, missing, hmap, fileobj, upload_gen=None):
        """upload missing blocks asynchronously"""
336

337
        self._init_thread_limit()
338

339
        flying = []
340
        failures = []
341
        for hash in missing:
342
            offset, bytes = hmap[hash]
343
            fileobj.seek(offset)
344
            data = readall(fileobj, bytes)
345
            r = self._put_block_async(data, hash)
346
            flying.append(r)
347 348
            unfinished = self._watch_thread_limit(flying)
            for thread in set(flying).difference(unfinished):
349 350
                if thread.exception:
                    failures.append(thread)
351
                    if isinstance(
352 353 354
                            thread.exception,
                            ClientError) and thread.exception.status == 502:
                        self.POOLSIZE = self._thread_limit
355
                elif thread.isAlive():
356
                    flying.append(thread)
357 358 359 360 361
                elif upload_gen:
                    try:
                        upload_gen.next()
                    except:
                        pass
362 363 364 365
            flying = unfinished

        for thread in flying:
            thread.join()
366 367
            if thread.exception:
                failures.append(thread)
368 369 370 371 372
            elif upload_gen:
                try:
                    upload_gen.next()
                except:
                    pass
373

374
        return [failure.kwargs['hash'] for failure in failures]
375

376 377 378 379 380 381
    def upload_object(
            self, obj, f,
            size=None,
            hash_cb=None,
            upload_cb=None,
            etag=None,
382
            if_etag_match=None,
383
            if_not_exist=None,
384 385 386 387
            content_encoding=None,
            content_disposition=None,
            content_type=None,
            sharing=None,
388 389
            public=None,
            container_info_cache=None):
390 391 392 393 394 395 396 397 398 399 400 401
        """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)

402 403 404
        :param if_etag_match: (str) Push that value to if-match header at file
            creation

405 406 407 408 409
        :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.

410 411 412 413 414 415 416 417 418 419
        :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)
420 421

        :param container_info_cache: (dict) if given, avoid redundant calls to
422
            server for container info (block size and hash information)
423
        """
424
        self._assert_container()
425

426 427 428
        block_info = (
            blocksize, blockhash, size, nblocks) = self._get_file_block_info(
                f, size, container_info_cache)
429
        (hashes, hmap, offset) = ([], {}, 0)
430
        content_type = content_type or 'application/octet-stream'
431

432
        self._calculate_blocks_for_upload(
433
            *block_info,
434 435 436
            hashes=hashes,
            hmap=hmap,
            fileobj=f,
437 438 439
            hash_cb=hash_cb)

        hashmap = dict(bytes=size, hashes=hashes)
440
        missing, obj_headers = self._create_object_or_get_missing_hashes(
441
            obj, hashmap,
442 443
            content_type=content_type,
            size=size,
444 445
            if_etag_match=if_etag_match,
            if_etag_not_match='*' if if_not_exist else None,
446 447 448 449
            content_encoding=content_encoding,
            content_disposition=content_disposition,
            permissions=sharing,
            public=public)
450 451

        if missing is None:
452
            return obj_headers
453

454
        if upload_cb:
455 456
            upload_gen = upload_cb(len(hashmap['hashes']))
            for i in range(len(hashmap['hashes']) + 1 - len(missing)):
457 458 459
                try:
                    upload_gen.next()
                except:
460 461
                    sendlog.debug('Progress bar failure')
                    break
462 463 464
        else:
            upload_gen = None

465
        retries = 7
466 467 468 469 470
        while retries:
            sendlog.info('%s blocks missing' % len(missing))
            num_of_blocks = len(missing)
            missing = self._upload_missing_blocks(
                missing, hmap, f, upload_gen)
471
            if missing:
472 473 474 475 476 477 478 479 480 481 482 483 484 485
                if num_of_blocks == len(missing):
                    retries -= 1
                else:
                    num_of_blocks = len(missing)
            else:
                break
        if missing:
            try:
                details = ['%s' % thread.exception for thread in missing]
            except Exception:
                details = ['Also, failed to read thread exceptions']
            raise ClientError(
                '%s blocks failed to upload' % len(missing),
                details=details)
486 487 488 489 490 491

        r = self.object_put(
            obj,
            format='json',
            hashmap=True,
            content_type=content_type,
492
            content_encoding=content_encoding,
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
            if_etag_match=if_etag_match,
            if_etag_not_match='*' if if_not_exist else None,
            etag=etag,
            json=hashmap,
            permissions=sharing,
            public=public,
            success=201)
        return r.headers

    def upload_from_string(
            self, obj, input_str,
            hash_cb=None,
            upload_cb=None,
            etag=None,
            if_etag_match=None,
            if_not_exist=None,
            content_encoding=None,
            content_disposition=None,
            content_type=None,
            sharing=None,
            public=None,
            container_info_cache=None):
        """Upload an object using multiple connections (threads)

        :param obj: (str) remote object path

        :param input_str: (str) upload content

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

        :param upload_cb: optional progress.bar object for uploading

        :param etag: (str)

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

        :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.

        :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)

        :param container_info_cache: (dict) if given, avoid redundant calls to
547
            server for container info (block size and hash information)
548 549 550 551 552 553 554 555 556
        """
        self._assert_container()

        blocksize, blockhash, size, nblocks = self._get_file_block_info(
                fileobj=None, size=len(input_str), cache=container_info_cache)
        (hashes, hmap, offset) = ([], {}, 0)
        if not content_type:
            content_type = 'application/octet-stream'

557
        hashes = []
558
        hmap = {}
559
        for blockid in range(nblocks):
560 561
            start = blockid * blocksize
            block = input_str[start: (start + blocksize)]
562
            hashes.append(_pithos_hash(block, blockhash))
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
            hmap[hashes[blockid]] = (start, block)

        hashmap = dict(bytes=size, hashes=hashes)
        missing, obj_headers = self._create_object_or_get_missing_hashes(
            obj, hashmap,
            content_type=content_type,
            size=size,
            if_etag_match=if_etag_match,
            if_etag_not_match='*' if if_not_exist else None,
            content_encoding=content_encoding,
            content_disposition=content_disposition,
            permissions=sharing,
            public=public)
        if missing is None:
            return obj_headers
        num_of_missing = len(missing)

        if upload_cb:
581 582
            self.progress_bar_gen = upload_cb(nblocks)
            for i in range(nblocks + 1 - num_of_missing):
583 584
                self._cb_next()

585 586
        tries = 7
        old_failures = 0
587
        try:
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
            while tries and missing:
                flying = []
                failures = []
                for hash in missing:
                    offset, block = hmap[hash]
                    bird = self._put_block_async(block, hash)
                    flying.append(bird)
                    unfinished = self._watch_thread_limit(flying)
                    for thread in set(flying).difference(unfinished):
                        if thread.exception:
                            failures.append(thread.kwargs['hash'])
                        if thread.isAlive():
                            flying.append(thread)
                        else:
                            self._cb_next()
                    flying = unfinished
                for thread in flying:
                    thread.join()
606
                    if thread.exception:
607 608 609 610 611 612 613
                        failures.append(thread.kwargs['hash'])
                    self._cb_next()
                missing = failures
                if missing and len(missing) == old_failures:
                    tries -= 1
                old_failures = len(missing)
            if missing:
614
                raise ClientError('%s blocks failed to upload' % len(missing))
615
        except KeyboardInterrupt:
616
            sendlog.info('- - - wait for threads to finish')
617 618 619
            for thread in activethreads():
                thread.join()
            raise
620
        self._cb_next()
621

622
        r = self.object_put(
623
            obj,
624 625 626
            format='json',
            hashmap=True,
            content_type=content_type,
627
            content_encoding=content_encoding,
628
            if_etag_match=if_etag_match,
629 630
            if_etag_not_match='*' if if_not_exist else None,
            etag=etag,
631
            json=hashmap,
632 633
            permissions=sharing,
            public=public,
634
            success=201)
635
        return r.headers
636

637
    # download_* auxiliary methods
Stavros Sachtouris's avatar
Stavros Sachtouris committed
638
    def _get_remote_blocks_info(self, obj, **restargs):
639
        #retrieve object hashmap
640
        myrange = restargs.pop('data_range', None)
641
        hashmap = self.get_object_hashmap(obj, **restargs)
642
        restargs['data_range'] = myrange
643 644 645
        blocksize = int(hashmap['block_size'])
        blockhash = hashmap['block_hash']
        total_size = hashmap['bytes']
Stavros Sachtouris's avatar
Stavros Sachtouris committed
646
        #assert total_size/blocksize + 1 == len(hashmap['hashes'])
647
        map_dict = {}
Stavros Sachtouris's avatar
Stavros Sachtouris committed
648
        for i, h in enumerate(hashmap['hashes']):
649 650 651 652 653
            #  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
654
        return (blocksize, blockhash, total_size, hashmap['hashes'], map_dict)
655

656
    def _dump_blocks_sync(
657
            self, obj, remote_hashes, blocksize, total_size, dst, crange,
658
            **args):
659 660
        if not total_size:
            return
Stavros Sachtouris's avatar
Stavros Sachtouris committed
661
        for blockid, blockhash in enumerate(remote_hashes):
662 663 664 665
            if blockhash:
                start = blocksize * blockid
                is_last = start + blocksize > total_size
                end = (total_size - 1) if is_last else (start + blocksize - 1)
666 667 668 669 670
                data_range = _range_up(start, end, total_size, crange)
                if not data_range:
                    self._cb_next()
                    continue
                args['data_range'] = 'bytes=%s' % data_range
671 672 673 674
                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
675

676 677
    def _get_block_async(self, obj, **args):
        event = SilentEvent(self.object_get, obj, success=(200, 206), **args)
678 679
        event.start()
        return event
680

681 682
    def _hash_from_file(self, fp, start, size, blockhash):
        fp.seek(start)
683
        block = readall(fp, size)
684 685 686 687
        h = newhashlib(blockhash)
        h.update(block.strip('\x00'))
        return hexlify(h.digest())

688
    def _thread2file(self, flying, blockids, local_file, offset=0, **restargs):
689
        """write the results of a greenleted rest call to a file
690 691 692 693 694

        :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
        """
695
        for key, g in flying.items():
696 697 698 699 700 701 702
            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
703 704
                local_file.write(block)
                self._cb_next()
705 706
            flying.pop(key)
            blockids.pop(key)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
707 708
        local_file.flush()

709 710 711
    def _dump_blocks_async(
            self, obj, remote_hashes, blocksize, total_size, local_file,
            blockhash=None, resume=False, filerange=None, **restargs):
712
        file_size = fstat(local_file.fileno()).st_size if resume else 0
713 714
        flying = dict()
        blockid_dict = dict()
715
        offset = 0
716

717
        self._init_thread_limit()
718
        for block_hash, blockids in remote_hashes.items():
719 720 721 722 723 724 725
            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]
Stavros Sachtouris's avatar
Stavros Sachtouris committed
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
                self._watch_thread_limit(flying.values())
                self._thread2file(
                    flying, blockid_dict, local_file, offset,
                    **restargs)
                end = total_size - 1 if (
                    key + blocksize > total_size) else key + blocksize - 1
                if end < key:
                    self._cb_next()
                    continue
                data_range = _range_up(key, end, total_size, filerange)
                if not data_range:
                    self._cb_next()
                    continue
                restargs[
                    'async_headers'] = {'Range': 'bytes=%s' % data_range}
                flying[key] = self._get_block_async(obj, **restargs)
                blockid_dict[key] = unsaved
Stavros Sachtouris's avatar
Stavros Sachtouris committed
743

744 745
        for thread in flying.values():
            thread.join()
746
        self._thread2file(flying, blockid_dict, local_file, offset, **restargs)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
747

748 749 750 751 752 753 754 755 756
    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,
757 758
            if_unmodified_since=None,
            headers=dict()):
759
        """Download an object (multiple connections, random blocks)
760 761 762 763 764 765 766 767 768 769 770

        :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

771
        :param range_str: (str) from, to are file positions (int) in bytes
772 773 774 775 776 777 778

        :param if_match: (str)

        :param if_none_match: (str)

        :param if_modified_since: (str) formated date

779 780 781 782
        :param if_unmodified_since: (str) formated date

        :param headers: (dict) placeholder to gather object headers
        """
783 784 785
        restargs = dict(
            version=version,
            data_range=None if range_str is None else 'bytes=%s' % range_str,
Stavros Sachtouris's avatar
Stavros Sachtouris committed
786 787 788
            if_match=if_match,
            if_none_match=if_none_match,
            if_modified_since=if_modified_since,
789 790
            if_unmodified_since=if_unmodified_since,
            headers=dict())
Stavros Sachtouris's avatar
Stavros Sachtouris committed
791

792 793
        (
            blocksize,
Stavros Sachtouris's avatar
Stavros Sachtouris committed
794 795
            blockhash,
            total_size,
796
            hash_list,
Stavros Sachtouris's avatar
Stavros Sachtouris committed
797
            remote_hashes) = self._get_remote_blocks_info(obj, **restargs)
798
        headers.update(restargs.pop('headers'))
Stavros Sachtouris's avatar
Stavros Sachtouris committed
799 800 801
        assert total_size >= 0

        if download_cb:
802
            self.progress_bar_gen = download_cb(len(hash_list))
Stavros Sachtouris's avatar
Stavros Sachtouris committed
803 804 805
            self._cb_next()

        if dst.isatty():
806 807
            self._dump_blocks_sync(
                obj,
808 809 810 811
                hash_list,
                blocksize,
                total_size,
                dst,
812
                range_str,
813
                **restargs)
814
        else:
815 816
            self._dump_blocks_async(
                obj,
817 818 819 820 821 822
                remote_hashes,
                blocksize,
                total_size,
                dst,
                blockhash,
                resume,
823
                range_str,
824
                **restargs)
825
            if not range_str:
826
                dst.truncate(total_size)
827

Stavros Sachtouris's avatar
Stavros Sachtouris committed
828 829
        self._complete_cb()

830 831 832 833 834 835 836 837
    def download_to_string(
            self, obj,
            download_cb=None,
            version=None,
            range_str=None,
            if_match=None,
            if_none_match=None,
            if_modified_since=None,
838 839
            if_unmodified_since=None,
            headers=dict()):
840 841
        """Download an object to a string (multiple connections). This method
        uses threads for http requests, but stores all content in memory.
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858

        :param obj: (str) remote object path

        :param download_cb: optional progress.bar object for downloading

        :param version: (str) file version

        :param range_str: (str) from, to are file positions (int) in bytes

        :param if_match: (str)

        :param if_none_match: (str)

        :param if_modified_since: (str) formated date

        :param if_unmodified_since: (str) formated date

859 860
        :param headers: (dict) a placeholder dict to gather object headers

861 862 863 864 865 866 867 868
        :returns: (str) the whole object contents
        """
        restargs = dict(
            version=version,
            data_range=None if range_str is None else 'bytes=%s' % range_str,
            if_match=if_match,
            if_none_match=if_none_match,
            if_modified_since=if_modified_since,
869 870
            if_unmodified_since=if_unmodified_since,
            headers=dict())
871 872 873 874 875 876 877

        (
            blocksize,
            blockhash,
            total_size,
            hash_list,
            remote_hashes) = self._get_remote_blocks_info(obj, **restargs)
878
        headers.update(restargs.pop('headers'))
879 880 881 882 883 884
        assert total_size >= 0

        if download_cb:
            self.progress_bar_gen = download_cb(len(hash_list))
            self._cb_next()

885 886 887 888
        num_of_blocks = len(remote_hashes)
        ret = [''] * num_of_blocks
        self._init_thread_limit()
        flying = dict()
889 890 891 892 893
        try:
            for blockid, blockhash in enumerate(remote_hashes):
                start = blocksize * blockid
                is_last = start + blocksize > total_size
                end = (total_size - 1) if is_last else (start + blocksize - 1)
894 895
                data_range_str = _range_up(start, end, end, range_str)
                if data_range_str:
896
                    self._watch_thread_limit(flying.values())
897
                    restargs['data_range'] = 'bytes=%s' % data_range_str
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
                    flying[blockid] = self._get_block_async(obj, **restargs)
                for runid, thread in flying.items():
                    if (blockid + 1) == num_of_blocks:
                        thread.join()
                    elif thread.isAlive():
                        continue
                    if thread.exception:
                        raise thread.exception
                    ret[runid] = thread.value.content
                    self._cb_next()
                    flying.pop(runid)
            return ''.join(ret)
        except KeyboardInterrupt:
            sendlog.info('- - - wait for threads to finish')
            for thread in activethreads():
                thread.join()
914

915
    # Command Progress Bar method
916
    def _cb_next(self, step=1):
Stavros Sachtouris's avatar
Stavros Sachtouris committed
917 918
        if hasattr(self, 'progress_bar_gen'):
            try:
919 920
                for i in xrange(step):
                    self.progress_bar_gen.next()
Stavros Sachtouris's avatar
Stavros Sachtouris committed
921 922
            except:
                pass
923

Stavros Sachtouris's avatar
Stavros Sachtouris committed
924 925 926
    def _complete_cb(self):
        while True:
            try:
927
                self.progress_bar_gen.next()
Stavros Sachtouris's avatar
Stavros Sachtouris committed
928 929
            except:
                break
Stavros Sachtouris's avatar
Stavros Sachtouris committed
930

931 932 933 934 935 936
    def get_object_hashmap(
            self, obj,
            version=None,
            if_match=None,
            if_none_match=None,
            if_modified_since=None,
937 938
            if_unmodified_since=None,
            headers=dict()):
939 940 941 942 943 944 945 946 947 948 949 950 951
        """
        :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

        :returns: (list)
        """
952
        try:
953 954
            r = self.object_get(
                obj,
955 956 957 958 959
                hashmap=True,
                version=version,
                if_etag_match=if_match,
                if_etag_not_match=if_none_match,
                if_modified_since=if_modified_since,
960
                if_unmodified_since=if_unmodified_since)
961 962 963 964
        except ClientError as err:
            if err.status == 304 or err.status == 412:
                return {}
            raise
965
        headers.update(r.headers)
966
        return r.json
967

968
    def set_account_group(self, group, usernames):
969 970 971 972 973
        """
        :param group: (str)

        :param usernames: (list)
        """
974 975
        r = self.account_post(update=True, groups={group: usernames})
        return r
Stavros Sachtouris's avatar
Stavros Sachtouris committed
976

977
    def del_account_group(self, group):
978 979 980
        """
        :param group: (str)
        """
981
        self.account_post(update=True, groups={group: []})
982

Stavros Sachtouris's avatar
Stavros Sachtouris committed
983
    def get_account_info(self, until=None):
984 985 986 987 988
        """
        :param until: (str) formated date

        :returns: (dict)
        """
Stavros Sachtouris's avatar
Stavros Sachtouris committed
989
        r = self.account_head(until=until)
990
        if r.status_code == 401:
991
            raise ClientError("No authorization", status=401)
992
        return r.headers