@glacier_connect
    @sdb_connect
    @log_class_call("Requesting inventory overview.",
                    "Inventory response received.")
    def inventory(self, vault_name, refresh):
        """
        Retrieves inventory and returns retrieval job, or if it's already retrieved
        returns overview of the inventoy. If force=True it will force start a new
        inventory taking job.

        :param vault_name: Vault name
        :type vault_name: str
        :param refresh: Force new inventory retrieval.
        :type refresh: boolean

        :returns: Tuple of retrieval job and inventory data (as list) if available.

            .. code-block:: python

                ({u'CompletionDate': None,
                  u'VaultARN':
                  u'arn:aws:glacier:us-east-1:012345678901:vaults/your_vault_name',
                  u'SNSTopic': None,
                  u'SHA256TreeHash': None,
                  u'Completed': False,
                  u'InventorySizeInBytes': None,
                  u'JobId': u'Example_d3tgAbCuQ9vPRqRJkD2vjNQ6wBgga7Xaw9ifwACvhjhIeKtNnZqeSIuMYRo3JUKsK_0M-VNYvb0-_Example',
                  u'ArchiveId': None,
                  u'JobDescription': None,
                  u'StatusCode': u'InProgress',
                  u'Action': u'InventoryRetrieval',
                  u'CreationDate': u'2012-10-01T14:54:51.919Z',
                  u'StatusMessage': None,
                  u'ArchiveSizeInBytes': None},
                  None
                )
        :rtype: (list, list)

        :raises: :py:exc:`glacier.glacierexception.CommunicationException`,
                 :py:exc:`glacier.glacierexception.ResponseException`
        """

        self._check_vault_name(vault_name)
        inventory = None
        inventory_job = None
        if not refresh:

            # List active jobs and check whether any inventory retrieval
            # has been completed, and whether any is in progress. We want
            # to find the latest finished job, or that failing the latest
            # in progress job.
            job_list = self.list_jobs(vault_name)
            inventory_done = False
            for job in job_list:
                if job['Action'] == "InventoryRetrieval":

                    # As soon as a finished inventory job is found, we're done.
                    if job['Completed']:
                        self.logger.debug('Found finished inventory job %s.'% job)
                        d = dtparse(job['CompletionDate']).replace(tzinfo=pytz.utc)
                        job['inventory_date'] = d
                        inventory_done = True
                        inventory_job = job
                        break

                    self.logger.debug('Found running inventory job %s.'% job)
                    inventory_job = job

            # If inventory retrieval is complete, process it.
            if inventory_done:
                self.logger.debug('Fetching results of finished inventory retrieval.')
                response = self.glacierconn.get_job_output(vault_name, inventory_job['JobId'])
                inventory = response.copy()
                archives = []

                # If bookkeeping is enabled, update cache.
                # Add all inventory information to the database, then check
                # for any archives listed in the database for that vault and
                # remove those.
                if self.bookkeeping and len(inventory['ArchiveList']) > 0:
                    self.logger.debug('Updating the bookkeeping with the latest inventory.')
                    items = {}

                    # Add items to the inventory, 25 at a time (maximum batch).
                    for item in inventory['ArchiveList']:
                        items[item['ArchiveId']] = {
                            'vault': vault_name,
                            'archive_id': item['ArchiveId'],
                            'description': item['ArchiveDescription'],
                            'date':'%s' % dtparse(item['CreationDate']).replace(tzinfo=pytz.utc),
                            'hash': item['SHA256TreeHash'],
                            'size': item['Size'],
                            'region': self.region
                            }
                        archives.append(item['ArchiveId'])
                        if len(items) == 25:
                            self.logger.debug('Writing batch of 25 inventory items to the bookkeeping db.')
                            try:
                                self.sdb_domain.batch_put_attributes(items)
                            except boto.exception.SDBResponseError as e:
                                raise CommunicationException(
                                    "Cannot update inventory cache, Amazon SimpleDB is not happy.",
                                    cause=e,
                                    code="SdbWriteError")
                            items = {}

                    # Add the remaining batch of items, if any, to the
                    # database.
                    if items:
                        self.logger.debug('Writing final batch of %s inventory items to the bookkeeping db.'% len(items))
                        try:
                            self.sdb_domain.batch_put_attributes(items)
                        except boto.exception.SDBResponseError as e:
                            raise CommunicationException(
                                "Cannot update inventory cache, Amazon SimpleDB is not happy.",
                                cause=e,
                                code="SdbWriteError")

                    # Get the inventory from the database for this vault,
                    # and delete any orphaned items.
                    query = "select * from `%s` where vault='%s'" % (self.bookkeeping_domain_name, vault_name)
                    result = self.sdb_domain.select(query)
                    try:
                        for item in result:
                            if not item.name in archives:
                                self.sdb_domain.delete_item(item)
                                self.logger.debug('Deleted orphaned archive from the database: %s.'% item.name)

                    except boto.exception.SDBResponseError as e:
                        raise ResponseException(
                                'SimpleDB did not respond correctly to our inventory check.',
                                cause=self._decode_error_message(e.body),
                                code=e.code)

        # If refresh == True or no current inventory jobs either finished or
        # in progress, we have to start a new job. Then request the job details
        # through describejob to return.
        if refresh or not inventory_job:
            self.logger.debug('No inventory jobs finished or running; starting a new job.')
            job_data = {'Type': 'inventory-retrieval'}
            try:
                new_job = self.glacierconn.initiate_job(vault_name, job_data)
            except boto.glacier.exceptions.UnexpectedHTTPResponseError as e:
                raise ResponseException(
                    'Failed to create a new inventory retrieval job for vault %s.'% vault_name,
                    cause=self._decode_error_message(e.body),
                    code=e.code)

            inventory_job = self.describejob(vault_name, new_job['JobId'])

        return (inventory_job, inventory)
dataset/ETHPy150Open uskudnik/amazon-glacier-cmd-interface/glacier/GlacierWrapper.py/GlacierWrapper.inventory/original