Remove old versions of a backup.

 @param [String] bucket the bucket where the archive is stored in.
 @param [String] prefix the prefix where to look for outdated versions.
 @param [Integer] versions number of versions to keep.

 @return [nil]
169642
def cleanup(bucket, prefix, versions)
      objects = @con.get_bucket(bucket, :prefix => prefix).body['Contents']

      return if objects.size <= versions

      objects[0...(objects.size - versions)].each do |o|
       Mongolicious.logger.info("Removing outdated version #{o['Key']}")
       @con.delete_object(bucket, o['Key'])
      end
    end
669087
def clean_all_buckets(self):
        
        bucket_keys = self.redis_object.keys(pattern='nearpy_*')
        if len(bucket_keys) > 0:
            self.redis_object.delete(*bucket_keys)
518076
def clear_bucket_props(self, bucket):
        
        bucket_type = self._get_bucket_type(bucket.bucket_type)
        url = self.bucket_properties_path(bucket.name,
                                          bucket_type=bucket_type)
        url = self.bucket_properties_path(bucket.name)
        headers = {'Content-Type': 'application/json'}

        # Run the request...
        status, _, _ = self._request('DELETE', url, headers, None)

        if status == 204:
            return True
        elif status == 405:
            return False
        else:
            raise RiakError('Error %s clearing bucket properties.'
                            % status)
333127
public void removeSnapshots() {
        VersionList versionToRemove = new VersionList();

        // collect Versions to be removed
        for (Version ver : this) {
            if (ver.isSnapshot()) {
                versionToRemove.add(ver);
            }
        }

        // remove them
        this.removeAll(versionToRemove);
    }
299678
def purge_archives(self):
        

        klass = self.get_version_class()
        qs = klass.normal.filter(object_id=self.object_id,
                                 state=self.ARCHIVED).order_by('-last_save')[self.NUM_KEEP_ARCHIVED:]

        for obj in qs:
            obj._delete_reverses()
            klass.normal.filter(vid=obj.vid).delete()
768507
def purge_bucket(context, provider, **kwargs):
    """"""
    session = get_session(provider.region)

    if kwargs.get('bucket_name'):
        bucket_name = kwargs['bucket_name']
    else:
        if kwargs.get('bucket_output_lookup'):
            value = kwargs['bucket_output_lookup']
            handler = OutputLookup.handle
        elif kwargs.get('bucket_rxref_lookup'):
            value = kwargs['bucket_rxref_lookup']
            handler = RxrefLookup.handle
        elif kwargs.get('bucket_xref_lookup'):
            value = kwargs['bucket_xref_lookup']
            handler = XrefLookup.handle
        else:
            LOGGER.fatal('No bucket name/source provided.')
            return False

        try:  # Exit early if the bucket's stack is already deleted
            session.client('cloudformation').describe_stacks(
                StackName=context.get_fqn(value.split('::')[0])
            )
        except ClientError as exc:
            if 'does not exist' in exc.response['Error']['Message']:
                LOGGER.info('S3 bucket stack appears to have already been '
                            'deleted...')
                return True
            raise

        bucket_name = handler(
            value,
            provider=provider,
            context=context
        )

    s3_resource = session.resource('s3')
    try:
        s3_resource.meta.client.head_bucket(Bucket=bucket_name)
    except ClientError as exc:
        if exc.response['Error']['Code'] == '404':
            LOGGER.info("%s S3 bucket appears to have already been deleted...",
                        bucket_name)
            return True
        raise

    bucket = s3_resource.Bucket(bucket_name)
    bucket.object_versions.delete()
    return True
545752
def _cleanup_orphaned_versions(self, dry_run):
        
        lib = self
        versions_coll = lib._collection.versions
        snapshots_coll = lib._collection.snapshots

        logger.info("ORPHANED SNAPSHOT CHECK: %s" % self._arctic_lib.get_name())

        # Be liberal with the generation time.
        gen_time = dt.now() - timedelta(days=1)
        parent_id_constraint = {'$lt': bson.ObjectId.from_datetime(gen_time)}

        # For each symbol, grab all 'real' snapshots and audit entries
        snapshots = set(snapshots_coll.distinct('_id'))
        snapshots |= set(lib._audit.distinct('_id'))
        # Using aggregate so we can unwind, and pull out 'parent', where 'parent' is older than a day.
        parents = versions_coll.aggregate([{'$project': {'parent': True}},
                                           {'$unwind': '$parent'},
                                           {'$match': {'parent': parent_id_constraint}},
                                           {'$group': {'_id': '$parent'}},
                                           ])
        parent_ids = set([x['_id'] for x in parents])

        leaked_snaps = sorted(parent_ids - snapshots)
        if len(leaked_snaps):
            logger.info("leaked %d snapshots" % (len(leaked_snaps)))
        for x in leaked_snaps:
            ver_count = mongo_count(versions_coll, filter={'parent': x})
            logger.info("Missing Snapshot %s (%s) ; %s versions ref'd" % (x.generation_time,
                                                                          x,
                                                                          ver_count
                                                                          ))
            if snapshots_coll.find_one({'_id': x}) is not None:
                raise Exception("Error: snapshot (%s) is found, but shouldn't be!" %
                                (x))
            # Now cleanup the leaked snapshots
            if not dry_run:
                versions_coll.update_many({'parent': x},
                                          {'$pull': {'parent': x}})
656870
def at_version(version)
      return self if log_data.version == version

      log_entry = log_data.find_by_version(version)
      return nil unless log_entry

      build_dup(log_entry)
    end
466973
def delete(self):
        
        return self.bucket.delete_key(self.name, version_id=self.version_id)
867385
def yank_version(name, version, options = {})
      ensure_ready!(:authorization)
      url = "gems/#{escape(name)}/versions/#{escape(version)}"
      response = connection.delete(url, options)
      checked_response_body(response)
    end
1016552
private void deleteBackups() {
        File[] storeDirList = ReadOnlyUtils.getVersionDirs(storeDir, 0L, getCurrentVersionId());
        if(storeDirList != null && storeDirList.length > (numBackups + 1)) {
            // delete ALL old directories asynchronously
            File[] extraBackups = ReadOnlyUtils.findKthVersionedDir(storeDirList,
                                                                    0,
                                                                    storeDirList.length
                                                                            - (numBackups + 1) - 1);
            if(extraBackups != null) {
                for(File backUpFile: extraBackups) {
                    deleteAsync(backUpFile);
                }
            }
        }
    }
1227382
def remove_bucket(self, bucket_name):
        
        is_valid_bucket_name(bucket_name)
        self._url_open('DELETE', bucket_name=bucket_name)

        # Make sure to purge bucket_name from region cache.
        self._delete_bucket_region(bucket_name)
706006
def delete_old_branches
      return unless extra_branches.any?
      should_delete = should_delete_old_branches || cli.ask_boolean("Do you want to delete the old #{branch_type} branch(es)? (#{extra_branches.join(", ")})")

      if should_delete
        extra_branches.each do |extra|
          Git.delete_branch(extra)
        end
      end
    end
1083182
def delete(bucket, path=None, action=None, key=None, keyid=None,
           service_url=None, verify_ssl=None, kms_keyid=None, location=None,
           role_arn=None, path_style=None, https_enable=None):
    '''
    
    '''
    key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable = _get_key(
        key,
        keyid,
        service_url,
        verify_ssl,
        kms_keyid,
        location,
        role_arn,
        path_style,
        https_enable,
    )

    return __utils__['s3.query'](method='DELETE',
                                 bucket=bucket,
                                 path=path,
                                 action=action,
                                 key=key,
                                 keyid=keyid,
                                 kms_keyid=kms_keyid,
                                 service_url=service_url,
                                 verify_ssl=verify_ssl,
                                 location=location,
                                 role_arn=role_arn,
                                 path_style=path_style,
                                 https_enable=https_enable)
564248
def delete_with_retention(self, num_to_retain):
        
        base_backup_sentinel_depth = self.layout.basebackups().count('/') + 1

        # Sweep over base backup files, collecting sentinel files from
        # completed backups.
        completed_basebackups = []
        for key in self._backup_list(prefix=self.layout.basebackups()):

            key_name = self.layout.key_name(key)
            key_parts = key_name.split('/')
            key_depth = len(key_parts)
            url = '{scheme}://{bucket}/{name}'.format(
                scheme=self.layout.scheme,
                bucket=self._container_name(key),
                name=key_name)

            if key_depth == base_backup_sentinel_depth:
                # This is a key at the depth of a base-backup-sentinel file.
                # Check to see if it matches the known form.
                match = re.match(storage.COMPLETE_BASE_BACKUP_REGEXP,
                                 key_parts[-1])

                # If this isn't a base-backup-sentinel file, just ignore it.
                if match is None:
                    continue

                # This key corresponds to a base-backup-sentinel file and
                # represents a completed backup. Grab its segment number.
                scanned_sn = \
                    self._groupdict_to_segment_number(match.groupdict())
                completed_basebackups.append(dict(
                    scanned_sn=scanned_sn,
                    url=url))

        # Sort the base backups from newest to oldest.
        basebackups = sorted(
                        completed_basebackups,
                        key=lambda backup: backup['scanned_sn'].as_an_integer,
                        reverse=True)
        last_retained = None
        if len(basebackups) <= num_to_retain:
            detail = None
            if len(basebackups) == 0:
                msg = 'Not deleting any data.'
                detail = 'No existing base backups.'
            elif len(basebackups) == 1:
                last_retained = basebackups[-1]
                msg = 'Retaining existing base backup.'
            else:
                last_retained = basebackups[-1]
                msg = "Retaining all %d base backups." % len(basebackups)
        else:
            last_retained = basebackups[num_to_retain - 1]
            num_deleting = len(basebackups) - num_to_retain
            msg = "Deleting %d oldest base backups." % num_deleting
            detail = "Found %d total base backups." % len(basebackups)
        log_message = dict(msg=msg)
        if detail is not None:
            log_message['detail'] = detail
        if last_retained is not None:
            log_message['hint'] = \
                "Deleting keys older than %s." % last_retained['url']
        logger.info(**log_message)

        # This will delete all base backup and WAL data before
        # last_retained['scanned_sn'].
        if last_retained is not None:
            self._delete_base_backups_before(last_retained['scanned_sn'])
            self._delete_wals_before(last_retained['scanned_sn'])

        if self.deleter:
            self.deleter.close()
608424
def remove_bucket(self, instance, bucket_name):
        
        url = '/buckets/{}/{}'.format(instance, bucket_name)
        self._client.delete_proto(url)
163757
def delete(key)
      deleted = @store.delete(key)
      @on_write_failure.call(key) if !deleted && @on_write_failure
      RecordCache::Base.logger.debug{ "Version Store: deleted #{key}" }
      deleted
    end