Create a new backup
513050
def workspace_backup_add(ctx):
    
    backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
    backup_manager.add()
1057698
def backup(self):
        
        try:
            self.backup_df = self.df.copy()
        except Exception as e:
            self.err(e, "Can not backup data")
            return
        self.ok("Dataframe backed up")
957216
def restore(self) -> None:
        
        for name, parameter in self._parameters:
            parameter.data.copy_(self._backups[name])
1214385
def create
      return unless new_record?

      parent_machine.with_open_session do |session|
        machine = session.machine
        machine.create_shared_folder(name, host_path, writable)
      end

      existing_record!
      clear_dirty!
    end
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)
172104
def backup_file(*, file, host):
    
    if _driver:
        log.msg_debug("[{driver}] Backing up file '{file}'"
                      .format(driver=_driver.get_name(), file=file))
        _driver.backup_file(file=file, host=host)
484324
def require_backup_exists(func):
    
    def new_func(*args, **kwargs):
        backup_file = kwargs['backup_file']
        if not os.path.exists(backup_file):
            raise RestoreError("Could not find file '{0}'".format(backup_file))
        return func(*args, **kwargs)
    return new_func
523522
def backup_source_file(fname, options=None):
    
    opts = parse_options(options)
    backup_dir = opts.backup_dir
    assert os.path.exists(fname), \
        ("\n--%s-- Warning: File `%s' does not exist. . ." % (current_time(), fname))
    assert os.path.exists(os.path.abspath(backup_dir)), \
        ("\n--%s-- Warning: Directory `%s' does not exist. . ." % (current_time(), fname))
    backup_name = backup_dir + os.sep + os.path.split(fname)[1] + opts.backup_suffix
    try:
        shutil.copyfile(fname, backup_name)
    except IOError:
        message = "\n--%s-- Warning: Couldn't backup the file `%s' in `%s', check if you have enough permissions. "
        tpl = (current_time(), fname, backup_dir)
        sys.stderr.write(message % tpl)
649446
def backup_all(args):
    '''
    
    '''
    username = None
    password = None
    auth = args.get('--auth')
    path = args.get('--path')
    s3 = args.get('--upload_s3')
    glacier = args.get('--upload_glacier')
    dropbox = args.get('--upload_dropbox')
    swift = args.get('--upload_swift')
    encrypt = args.get('--encrypt') or 'Y'

    if (ADMIN_USER and ADMIN_PASSWORD):
        username = ADMIN_USER
        password = ADMIN_PASSWORD

    if not path:
        path = os.getcwd()
    if path and not os.path.isdir(path):
        raise SystemExit(_error_codes.get(105))

    if auth:
        query = 'mongodump -u {username} -p {password} '
    else:
        query = 'mongodump '
    if path:
        query += '-o {path}/dump'

    local(query.format(username=username,
                       password=password,
                       path=path))

    compress_file = compress_folder_dump(
        normalize_path(path) + 'dump', normalize_path(path))

    shutil.rmtree(normalize_path(path) + 'dump')

    optional_actions(encrypt, path, compress_file, s3=s3, glacier=glacier,
                     dropbox=dropbox, swift=swift)
248131
protected function createBackupFile($original, $backup)
    {
        $isOk = !file_exists($original) || rename($original, $backup);

        return $isOk;
    }
843017
function(lastOne) {
    if (buffer.length >= bufferSize || (lastOne && buffer.length > 0)) {
      debug('writing', buffer.length, 'changes to the backup file');
      var b = { docs: buffer.splice(0, bufferSize), batch: batch };
      logStream.write(':t batch' + batch + ' ' + JSON.stringify(b.docs) + '\n');
      ee.emit('changes', batch);
      batch++;
    }
  }
1194380
private function createBackup()
    {
        $hash       = $this->getHash();
        $connection = $this->entityManager->getConnection();

        $this->backupService->createBackup($connection, $hash);
    }
992182
def backup_file(filename, backup_ext):
    '''
    
    '''
    ext = backup_ext.strip(" .")
    if ext:
        backup_filename = ".".join([filename, ext])
        if not exists(backup_filename):
            shutil.copyfile(filename, backup_filename)
        else:
            if not filecmp.cmp(filename, backup_filename):
                raise DietException('Cannot make backup because a different'
                                    'file with that name already exists.')
        return backup_filename
    return None
732111
public function createBackup()
    {
        try {
            // compressor instance
            $compressor = new Compress('backup-' . date('Y-m-d_H-i-s'), $this->backupConfig->TempPath);

            // first we need to export all the databases
            $backupMongo = new BackupMongo($this->backupConfig->get('MongoDatabases', [], true), $this->backupConfig->TempPath);
            $compressor->addSources($backupMongo->exportDatabases());

            // add folders to the compressor
            $compressor->addSources($this->backupConfig->get('Folders', [], true));

            // compress all the folders and database exports in one archive
            $backupArchive = $compressor->compress();

            // encrypt the archive -> only if passpharse is set
            $encryptionStatus = false;
            if ($this->backupConfig->get('Encryption', false)) {
                $encryption = new Encrypt($backupArchive, $this->backupConfig->Encryption, $this->backupConfig->TempPath);
                $encArchive = $encryption->encrypt();
                $encryptionStatus = true;
            } else {
                $encArchive = $backupArchive;
            }

            $backupSize = filesize($encArchive);

            // check if we should backup to S3
            if ($this->backupConfig->get('S3', false)) {
                $s3 = new Lib\S3($this->backupConfig->get('S3'));

                // move the old 1-day backup to 2-day backup
                $oldBackup = $s3->moveOldBackup();
                $this->backupsCreated['s3']['48h'] = [
                    'filename'  => $oldBackup,
                    'encrypted' => $encryptionStatus
                ];
                

                // create new 1 day backup
                $uploadedFile = $s3->upload($encArchive, 'backup-1day-old');
                $this->backupsCreated['s3']['24h'] = [
                    'size'      => $backupSize,
                    'filename'  => $uploadedFile,
                    'encrypted' => $encryptionStatus
                ];

                // check if we need 7-day backup and 30-day backup
                $frequencies = $this->backupConfig->get('Frequency', [], true);

                // week
                // we always do weekly backups on sunday
                if (in_array('Week', $frequencies) && date('w') == '0') {
                    $s3->deleteBackup('backup-week');
                    $copiedFile = $s3->copyLatestBackup('backup-week');
                    $this->backupsCreated['s3']['weekly'] = [
                        'size'      => $backupSize,
                        'filename'  => $copiedFile,
                        'encrypted' => $encryptionStatus
                    ];
                }

                // month
                // we always do monthly backups on the last day of the month
                if (in_array('Month', $frequencies) && date('d') == date('t')) {
                    $s3->deleteBackup('backup-month');
                    $copiedFile = $s3->copyLatestBackup('backup-month');
                    $this->backupsCreated['s3']['monthly'] = [
                        'size'      => $backupSize,
                        'filename'  => $copiedFile,
                        'encrypted' => $encryptionStatus
                    ];
                }

                // year
                // we always do monthly backups on the last day of the year
                if (in_array('Year', $frequencies) && date('d.m') == '31.12') {
                    $s3->deleteBackup('backup-year');
                    $copiedFile = $s3->copyLatestBackup('backup-year');
                    $this->backupsCreated['s3']['yearly'] = [
                        'size'      => $backupSize,
                        'filename'  => $copiedFile,
                        'encrypted' => $encryptionStatus
                    ];
                }
            }

            // check if a file system backup is required
            if ($this->backupConfig->get('BackupStoragePath', false)) {
                $fsBackup = new Lib\Filesystem($this->backupConfig->get('BackupStoragePath'));

                // move the old 1-day backup to 2-day backup
                $oldBackup = $fsBackup->moveOldBackup();
                $this->backupsCreated['local']['48h'] = [
                    'filename'  => $oldBackup,
                    'encrypted' => $encryptionStatus
                ];

                // create new 1 day backup
                $uploadedFile = $fsBackup->upload($encArchive, 'backup-1day-old');
                $this->backupsCreated['local']['24h'] = [
                    'size'      => $backupSize,
                    'filename'  => $uploadedFile,
                    'encrypted' => $encryptionStatus
                ];

                // check if we need 7-day backup and 30-day backup
                $frequencies = $this->backupConfig->get('Frequency', [], true);

                // week
                // we always do weekly backups on sunday
                if (in_array('Week', $frequencies) && date('w') == '0') {
                    $fsBackup->deleteBackup('backup-week');
                    $copiedFile = $fsBackup->copyLatestBackup('backup-week');
                    $this->backupsCreated['local']['weekly'] = [
                        'size'      => $backupSize,
                        'filename'  => $copiedFile,
                        'encrypted' => $encryptionStatus
                    ];
                }

                // month
                // we always do monthly backups on the last day of the month
                if (in_array('Month', $frequencies) && date('d') == date('t')) {
                    $fsBackup->deleteBackup('backup-month');
                    $copiedFile = $fsBackup->copyLatestBackup('backup-month');
                    $this->backupsCreated['local']['monthly'] = [
                        'size'      => $backupSize,
                        'filename'  => $copiedFile,
                        'encrypted' => $encryptionStatus
                    ];
                }

                // year
                // we always do monthly backups on the last day of the year
                if (in_array('Year', $frequencies) && date('d.m') == '31.12') {
                    $fsBackup->deleteBackup('backup-year');
                    $copiedFile = $fsBackup->copyLatestBackup('backup-year');
                    $this->backupsCreated['local']['yearly'] = [
                        'size'      => $backupSize,
                        'filename'  => $copiedFile,
                        'encrypted' => $encryptionStatus
                    ];
                }
            }

            // do the cleanup
            Cleanup::doCleanup();

            // end log
            self::$log->msg('Backup ended');
            self::$log->msg('Execution time: ' . $this->getExecutionTime());

            // set success flag
            $this->isSuccessful = true;

            if ($this->storeLog) {
                self::$log->writeLog();
            } else {
                return self::$log->getLog();
            }

        } catch (\Exception $e) {
            // set success flag
            $this->isSuccessful = false;

            self::$log->msg('ERROR: ' . $e->getMessage());
            if ($this->storeLog) {
                self::$log->writeLog();
            } else {
                return self::$log->getLog();
            }
        }
    }
1146177
function restoreBackup(backupRecord, mongoUri) {
  var receipts = backupRecord.receipts;
  var handler = getHandler(backupRecord.type);

  var restorePromises = receipts.map(function (receipt) {
    var tmpfile = util.getTempFileName() + '.bson';
    return R.pPipe(
      handler.restore.bind(handler),
      R.curry(R.flip(mds.dump.fs.file))(tmpfile),
      R.curryN(4, mongoRestoreFromFile)(tmpfile, mongoUri, receipt.collection)
    )(receipt.data);
  });

  return q.all(restorePromises).thenResolve('done');
}
92953
function uploadNewBackup(s3, backupTmpFilePath, bucket, key) {
  return new Promise((resolve, reject) => {
    debug(`Uploading from ${backupTmpFilePath} to ${bucket}/${key}`);

    function uploadFromStream(s3, bucket, key) {
      const pass = new stream.PassThrough();

      const params = {
        Bucket: bucket,
        Key: key,
        Body: pass
      };
      s3.upload(params, function(err, data) {
        debug('S3 upload done');
        if (err) {
          debug(err);
          reject(new VError(err, 'Upload failed'));
          return;
        }
        debug('Upload succeeded');
        debug(data);
        resolve();
      }).httpUploadProgress = (progress) => {
        debug(`S3 upload progress: ${progress}`);
      };

      return pass;
    }

    const inputStream = fs.createReadStream(backupTmpFilePath);
    const s3Stream = uploadFromStream(s3, bucket, key);
    inputStream.pipe(s3Stream);
  });
}
1155333
def create_snapshot(self, name, *args, **kwargs):
        
        return self.provider.create_snapshot(name, *args, **kwargs)