create a backup of a volume
484948
def create(self, volume_id, backup_id=None, timestamp=None):
        
        backup_id = backup_id or str(uuid.uuid4())
        timestamp = timestamp or int(time())
        return self.http_put('/volumes/%s/backups/%s' % (volume_id, backup_id),
                             params={'timestamp': timestamp})
727950
def backup(self):
        

        LOGGER.debug("> Storing '{0}' file backup.".format(self.__source))

        foundations.common.path_exists(self.__destination) or foundations.io.set_directory(self.__destination)
        destination = os.path.join(self.__destination, os.path.basename(self.__source))
        for i in range(self.__count - 1, 0, -1):
            sfn = "{0}.{1}".format(destination, i)
            dfn = "{0}.{1}".format(destination, i + 1)
            if foundations.common.path_exists(sfn):
                if foundations.common.path_exists(dfn):
                    foundations.io.remove(dfn)
                os.renames(sfn, dfn)
        foundations.common.path_exists(destination) and os.rename(destination, destination + ".1")
        foundations.io.copy(self.__source, destination)
        return True
454763
def backup(path, password_file=None):
    
    vault = VaultLib(get_vault_password(password_file))
    with open(path, 'r') as f:
        encrypted_data = f.read()

        # Normally we'd just try and catch the exception, but the
        # exception raised here is not very specific (just
        # `AnsibleError`), so this feels safer to avoid suppressing
        # other things that might go wrong.
        if vault.is_encrypted(encrypted_data):
            decrypted_data = vault.decrypt(encrypted_data)

            # Create atk vault files
            atk_path = os.path.join(ATK_VAULT, path)
            mkdir_p(atk_path)
            # ... encrypted
            with open(os.path.join(atk_path, 'encrypted'), 'wb') as f:
                f.write(encrypted_data)
            # ... hash
            with open(os.path.join(atk_path, 'hash'), 'wb') as f:
                f.write(hashlib.sha1(decrypted_data).hexdigest())

            # Replace encrypted file with decrypted one
            with open(path, 'wb') as f:
                f.write(decrypted_data)
197367
def setup(self):
        
        if self.backup:
            shutil.copy(self.input_file, "{}.orig".format(self.input_file))
656548
def create_backup(self):
        

        js = json.dumps({'cmd': 'backup'})
        params = urllib.urlencode({'json': js})
        answer = self._read(self.api_url + 'cmd/system', params)

        return answer[0].get('url')
805497
def cli(env, volume_id, replicant_id, immediate):
    """"""
    block_storage_manager = SoftLayer.BlockStorageManager(env.client)

    success = block_storage_manager.failover_to_replicant(
        volume_id,
        replicant_id,
        immediate
    )

    if success:
        click.echo("Failover to replicant is now in progress.")
    else:
        click.echo("Failover operation could not be initiated.")
263739
def restore_backup(self, backup, name, flavor, volume):
        
        return self._manager.restore_backup(backup, name, flavor, volume)
134606
def backup(self, filename='backup.zip', attachments=False):
        """"""
        if self.deploymentType == 'Cloud':
            url = self._options['server'] + '/rest/backup/1/export/runbackup'
            payload = json.dumps({"cbAttachments": attachments})
            self._options['headers']['X-Requested-With'] = 'XMLHttpRequest'
        else:
            url = self._options['server'] + '/secure/admin/XmlBackup.jspa'
            payload = {'filename': filename}
        try:
            r = self._session.post(url, headers=self._options['headers'], data=payload)
            if r.status_code == 200:
                return True
            else:
                logging.warning(
                    'Got %s response from calling backup.' % r.status_code)
                return r.status_code
        except Exception as e:
            logging.error("I see %s", e)
502275
def mount(self, volume):
        

        volume._find_loopback()

        raid_status = None
        try:
            # use mdadm to mount the loopback to a md device
            # incremental and run as soon as available
            output = _util.check_output_(['mdadm', '-IR', volume.loopback], stderr=subprocess.STDOUT)

            match = re.findall(r"attached to ([^ ,]+)", output)
            if match:
                volume._paths['md'] = os.path.realpath(match[0])
                if 'which is already active' in output:
                    logger.info("RAID is already active in other volume, using %s", volume._paths['md'])
                    raid_status = 'active'
                elif 'not enough to start' in output:
                    volume._paths['md'] = volume._paths['md'].replace("/dev/md/", "/dev/md")
                    logger.info("RAID volume added, but not enough to start %s", volume._paths['md'])
                    raid_status = 'waiting'
                else:
                    logger.info("RAID started at {0}".format(volume._paths['md']))
                    raid_status = 'active'
        except Exception as e:
            logger.exception("Failed mounting RAID.")
            volume._free_loopback()
            raise SubsystemError(e)

        # search for the RAID volume
        for v in volume.disk.parser.get_volumes():
            if v._paths.get("md") == volume._paths['md'] and v.volumes:
                logger.debug("Adding existing volume %s to volume %s", v.volumes[0], volume)
                v.volumes[0].info['raid_status'] = raid_status
                volume.volumes.volumes.append(v.volumes[0])
                return v.volumes[0]
        else:
            logger.debug("Creating RAID volume for %s", self)
            container = volume.volumes._make_single_subvolume(flag='alloc', offset=0, size=volume.size)
            container.info['fsdescription'] = 'RAID Volume'
            container.info['raid_status'] = raid_status
            return container
258633
def add_volume(self, hostpath, contpath, options=None):
        '''
        '''
        if options is None:
            options = []
        self.volumes.append((hostpath, contpath, options))
663184
def create_flac (archive, compression, cmd, verbosity, interactive, filenames):
    """"""
    cmdlist = [cmd, filenames[0], '--best', '--output-name', archive]
    return cmdlist
405379
def attach_volume(self, volume_id, instance_id, device):
        """"""
        query = self.query_factory(
            action="AttachVolume", creds=self.creds, endpoint=self.endpoint,
            other_params={"VolumeId": volume_id, "InstanceId": instance_id,
                          "Device": device})
        d = query.submit()
        return d.addCallback(self.parser.attach_volume)
398304
def setup(self):
        
        decompress_dir('.')

        if self.backup:
            for f in FEFF_INPUT_FILES:
                shutil.copy(f, "{}.orig".format(f))

            for f in FEFF_BACKUP_FILES:
                if os.path.isfile(f):
                    shutil.copy(f, "{}.orig".format(f))
19210
def backup(self, paths=None):
        """"""
        if not paths:
            paths = self._get_paths()

        try:
            self._backup_compresslevel(paths)
        except TypeError:
            try:
                self._backup_pb_gui(paths)
            except ImportError:
                self._backup_pb_tqdm(paths)

        # Delete source if specified
        if self.delete_source:
            shutil.rmtree(self.source)
        return self.zip_filename
6809
def cli(env, volume_id, snapshot_id):
    """"""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    success = block_manager.restore_from_snapshot(volume_id, snapshot_id)

    if success:
        click.echo('Block volume %s is being restored using snapshot %s'
                   % (volume_id, snapshot_id))
949382
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The create_attach_volumes action must be called with '
            '-a or --action.'
        )

    if 'instance_id' not in kwargs:
        kwargs['instance_id'] = _get_node(name)['instanceId']

    if isinstance(kwargs['volumes'], six.string_types):
        volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
    else:
        volumes = kwargs['volumes']

    ret = []
    for volume in volumes:
        created = False
        volume_name = '{0} on {1}'.format(volume['device'], name)

        volume_dict = {
            'volume_name': volume_name,
            'zone': kwargs['zone']
        }
        if 'volume_id' in volume:
            volume_dict['volume_id'] = volume['volume_id']
        elif 'snapshot' in volume:
            volume_dict['snapshot'] = volume['snapshot']
        elif 'size' in volume:
            volume_dict['size'] = volume['size']
        else:
            raise SaltCloudConfigError(
                'Cannot create volume.  Please define one of \'volume_id\', '
                '\'snapshot\', or \'size\''
            )

        if 'tags' in volume:
            volume_dict['tags'] = volume['tags']
        if 'type' in volume:
            volume_dict['type'] = volume['type']
        if 'iops' in volume:
            volume_dict['iops'] = volume['iops']
        if 'encrypted' in volume:
            volume_dict['encrypted'] = volume['encrypted']
        if 'kmskeyid' in volume:
            volume_dict['kmskeyid'] = volume['kmskeyid']

        if 'volume_id' not in volume_dict:
            created_volume = create_volume(volume_dict, call='function', wait_to_finish=wait_to_finish)
            created = True
            if 'volumeId' in created_volume:
                volume_dict['volume_id'] = created_volume['volumeId']

        attach = attach_volume(
            name,
            {'volume_id': volume_dict['volume_id'],
             'device': volume['device']},
            instance_id=kwargs['instance_id'],
            call='action'
        )

        # Update the delvol parameter for this volume
        delvols_on_destroy = kwargs.get('del_all_vols_on_destroy', None)

        if attach and created and delvols_on_destroy is not None:
            _toggle_delvol(instance_id=kwargs['instance_id'],
                           device=volume['device'],
                           value=delvols_on_destroy)

        if attach:
            msg = (
                '{0} attached to {1} (aka {2}) as device {3}'.format(
                    volume_dict['volume_id'],
                    kwargs['instance_id'],
                    name,
                    volume['device']
                )
            )
            log.info(msg)
            ret.append(msg)
    return ret
385572
def backup(schema, uuid, export_filter, export_format, filename, pretty, export_all, omit):
    """"""

    export_format = export_format.upper()

    if pretty:
        indent = 4
    else:
        indent = 0

    f = None

    if filename:
        try:
            f = open(filename, 'w')
        except (IOError, PermissionError) as e:
            backup_log('Could not open output file for writing:', exc=True, lvl=error)
            return

    def output(what, convert=False):
        """Output the backup in a specified format."""

        if convert:
            if export_format == 'JSON':
                data = json.dumps(what, indent=indent)
            else:
                data = ""
        else:
            data = what

        if not filename:
            print(data)
        else:
            f.write(data)

    if schema is None:
        if export_all is False:
            backup_log('No schema given.', lvl=warn)
            return
        else:
            schemata = objectmodels.keys()
    else:
        schemata = [schema]

    all_items = {}

    for schema_item in schemata:
        model = objectmodels[schema_item]

        if uuid:
            obj = model.find({'uuid': uuid})
        elif export_filter:
            obj = model.find(literal_eval(export_filter))
        else:
            obj = model.find()

        items = []
        for item in obj:
            fields = item.serializablefields()
            for field in omit:
                try:
                    fields.pop(field)
                except KeyError:
                    pass
            items.append(fields)

        all_items[schema_item] = items

        # if pretty is True:
        #    output('\n// Objectmodel: ' + schema_item + '\n\n')
        # output(schema_item + ' = [\n')

    output(all_items, convert=True)

    if f is not None:
        f.flush()
        f.close()