// Backup takes a backup of all installed applications
557039
func (f *Facade) Backup(ctx datastore.Context, w io.Writer, excludes []string, snapshotSpacePercent int, backupFilename string) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.Backup"))
	// Do not DFSLock here, ControlPlaneDao does that
	stime := time.Now()
	message := fmt.Sprintf("started backup at %s", stime.UTC())
	plog.WithField("excludes", excludes).Info("Started backup")
	alog := f.auditLogger.Message(ctx, "Started Backup").
		Action(audit.Backup).
		WithFields(logrus.Fields{
				"starttime": stime.UTC().Format("2006-01-02-150405"),
				"backupfile": backupFilename})
	alog.Succeeded()
	alog = f.auditLogger.Message(ctx, "Completed Backup").
		Action(audit.Backup)
	templates, images, err := f.GetServiceTemplatesAndImages(ctx)
	if err != nil {
		plog.WithError(err).Debug("Could not get service templates and images")
		return alog.Error(err)
	}
	plog.WithField("elapsed", time.Since(stime)).Info("Loaded templates and their images")
	pools, err := f.GetResourcePools(ctx)
	if err != nil {
		plog.WithError(err).Debug("Could not get resource pools")
		return alog.Error(err)
	}
	plog.WithField("elapsed", time.Since(stime)).Info("Loaded resource pools")
	tenants, err := f.GetTenantIDs(ctx)
	if err != nil {
		plog.WithError(err).Debug("Could not get tenants")
		return alog.Error(err)
	}
	snapshots := make([]string, len(tenants))
	snapshotExcludes := map[string][]string{}
	for i, tenant := range tenants {
		tenantLogger := plog.WithField("tenant", tenant)
		tag := fmt.Sprintf("backup-%s-%s", tenant, stime)
		snapshot, err := f.Snapshot(ctx, tenant, message, []string{tag}, snapshotSpacePercent)
		if err != nil {
			tenantLogger.WithError(err).Debug("Could not snapshot tenant")
			return alog.Error(err)
		}

		defer func(tenant, snapshot, tag string) {
			if err := f.DeleteSnapshot(ctx, snapshot); err != nil {
				tenantLogger.WithError(err).Warn("Could not delete snapshot; untagging for consumption by TTL")
				if _, err := f.RemoveSnapshotTag(ctx, tenant, tag); err != nil {
					tenantLogger.WithError(err).Error("Could not untag snapshot.  Snapshot must be deleted manually!")
				}
			}
		}(tenant, snapshot, tag)

		snapshots[i] = snapshot
		snapshotExcludes[snapshot] = append(excludes, f.getExcludedVolumes(ctx, tenant)...)
		tenantLogger.WithField("snapshot", snapshot).Info("Created a snapshot for tenant")
	}
	plog.WithField("elapsed", time.Since(stime)).Info("Loaded tenants")
	data := dfs.BackupInfo{
		Templates:        templates,
		BaseImages:       images,
		Pools:            pools,
		Snapshots:        snapshots,
		SnapshotExcludes: snapshotExcludes,
		Timestamp:        stime,
		BackupVersion:    1,
	}
	plog.WithField("data", data).Info("Calling dfs.Backup")
	if err := f.dfs.Backup(data, w); err != nil {
		plog.WithError(err).Debug("Could not backup")
		return alog.Error(err)
	}
	duration := time.Since(stime)
	plog.WithField("duration", duration).Info("Completed backup")
	alog.WithFields(logrus.Fields{
				"backupfile": backupFilename,
				"elasped": fmt.Sprintf("%fsec", duration.Seconds()),
			}).Succeeded()
	return nil
}
1147605
func (c *ServicedCli) cmdBackup(ctx *cli.Context)  {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "backup")
		c.exit(1)
		return
	}
	if ctx.Bool("check") {
		fmt.Printf("Checking for space...\n")
		if backupSpace, err := c.driver.GetBackupEstimate(args[0], ctx.StringSlice("exclude")); err != nil {
			fmt.Fprintf(os.Stderr, "Unable to estimate backup size: %s", err)
			c.exit(1)
			return
		} else {
			if ! backupSpace.AllowBackup {
				fmt.Fprintf(os.Stdout, "Unable to backup: estimated space required (%s) exceeds space available (%s) on %s\n", backupSpace.EstimatedString, backupSpace.AvailableString, backupSpace.BackupPath)
				c.exit(1)
				return
			}
			fmt.Printf("Okay to backup. Estimated space required: %s, Available: %s\n", backupSpace.EstimatedString, backupSpace.AvailableString)
		}
		fmt.Printf("Check only - not taking backup\n")
		return
	}
	// do backup
	if path, err := c.driver.Backup(args[0], ctx.StringSlice("exclude"), ctx.Bool("force")); err != nil {
		fmt.Fprintln(os.Stdout, err)
		c.exit(1)
		return
	} else if path == "" {
		fmt.Fprintln(os.Stderr, "received nil path to backup file")
		c.exit(1)
		return
	} else {
		fmt.Println(path)
	}
}
900295
func (s *RestoreBackupOutput) SetBackup(v *Backup) *RestoreBackupOutput {
	s.Backup = v
	return s
}
554733
func (context *ElasticRuntime) Restore() (err error) {
	err = context.backupRestore(cfbackup.ImportArchive)
	return
}
928494
func (c *Conn) Computers() ([]*Computer, error) {
	println("COMPUTERS")
	// Each backup is a top-level directory with a computerinfo file in it.
	list, err := c.list("", "/", 0)
	if err != nil {
		println("FAIL", err.Error())
		return nil, err
	}
	var out []*Computer
	for _, p := range list.CommonPrefixes {
		println("HAVE", p)
		data, err := c.bget(p + "computerinfo")
		if err != nil {
			continue
		}
		var info computerInfo
		println("PLIST", string(data))
		if err := plist.Unmarshal(data, &info); err != nil {
			return nil, err
		}

		comp := &Computer{
			Name:  info.ComputerName,
			User:  info.UserName,
			UUID:  p[:len(p)-1],
			conn:  c,
			index: map[score]ientry{},
		}

		salt, err := c.cget(p + "salt")
		if err != nil {
			return nil, err
		}
		comp.crypto.salt = salt

		out = append(out, comp)
	}
	return out, nil
}
1017181
func (c *ItemConsume) Backup2(t1 LexItem) {
	c.items[1] = t1
	c.peekCount = 2
}
1370222
func (fbs *FileBackupStorage) StartBackup(ctx context.Context, dir, name string) (backupstorage.BackupHandle, error) {
	// Make sure the directory exists.
	p := path.Join(*FileBackupStorageRoot, dir)
	if err := os.MkdirAll(p, os.ModePerm); err != nil {
		return nil, err
	}

	// Create the subdirectory for this named backup.
	p = path.Join(p, name)
	if err := os.Mkdir(p, os.ModePerm); err != nil {
		return nil, err
	}

	return &FileBackupHandle{
		fbs:      fbs,
		dir:      dir,
		name:     name,
		readOnly: false,
	}, nil
}
203973
func (a *api) Backup(dirpath string, excludes []string, force bool) (string, error) {
	client, err := a.connectDAO()
	if err != nil {
		return "", err
	}
	var path string
	req := dao.BackupRequest{
		Dirpath:              dirpath,
		SnapshotSpacePercent: config.GetOptions().SnapshotSpacePercent,
		Excludes:             excludes,
		Force:                force,
	}

	est := dao.BackupEstimate{}
	if err := client.GetBackupEstimate(req, &est); err != nil {
		return "", err
	}
	if err := client.Backup(req, &path); err != nil {
		return "", err
	}

	return path, nil
}
796897
func GetFilesToBackUp(rootDir string, paths *Paths, oldmachine string) ([]string, error) {
	var glob string

	glob = filepath.Join(rootDir, paths.DataDir, agentsDir, agentsConfs)
	agentConfs, err := filepath.Glob(glob)
	if err != nil {
		return nil, errors.Annotate(err, "failed to fetch agent config files")
	}

	glob = filepath.Join(rootDir, paths.DataDir, initDir, "*")
	serviceConfs, err := filepath.Glob(glob)
	if err != nil {
		return nil, errors.Annotate(err, "failed to fetch service config files")
	}

	backupFiles := []string{
		filepath.Join(rootDir, paths.DataDir, toolsDir),

		filepath.Join(rootDir, paths.DataDir, sshIdentFile),

		filepath.Join(rootDir, paths.DataDir, dbPEM),
		filepath.Join(rootDir, paths.DataDir, dbSecret),
	}
	backupFiles = append(backupFiles, agentConfs...)
	backupFiles = append(backupFiles, serviceConfs...)

	// Handle nonce.txt (might not exist).
	nonce := filepath.Join(rootDir, paths.DataDir, nonceFile)
	if _, err := os.Stat(nonce); err != nil {
		if !os.IsNotExist(err) {
			return nil, errors.Trace(err)
		}
		logger.Errorf("skipping missing file %q", nonce)
	} else {
		backupFiles = append(backupFiles, nonce)
	}

	// Handle user SSH files (might not exist).
	SSHDir := filepath.Join(rootDir, sshDir)
	if _, err := os.Stat(SSHDir); err != nil {
		if !os.IsNotExist(err) {
			return nil, errors.Trace(err)
		}
		logger.Errorf("skipping missing dir %q", SSHDir)
	} else {
		backupFiles = append(backupFiles, filepath.Join(SSHDir, authKeysFile))
	}

	return backupFiles, nil
}
1167593
func (lx *lexer) backup() {
	// This backup has a problem, if eof has already been hit
	// lx.width will be = 0
	// possibly just manually set to 1?
	lx.pos -= lx.width
	if lx.pos < len(lx.input) && lx.input[lx.pos] == '\n' {
		lx.line--
	}
}
1026470
func (c *Client) Backup() (io.ReadCloser, error) {
	res, err := c.RawReq("GET", "/backup", nil, nil, nil)
	if err != nil {
		return nil, err
	}
	return res.Body, nil
}
828906
func (be *BuiltinBackupEngine) backupFiles(ctx context.Context, cnf *Mycnf, mysqld MysqlDaemon, logger logutil.Logger, bh backupstorage.BackupHandle, replicationPosition mysql.Position, backupConcurrency int, hookExtraEnv map[string]string) (err error) {
	// Get the files to backup.
	fes, err := findFilesToBackup(cnf)
	if err != nil {
		return vterrors.Wrap(err, "can't find files to backup")
	}
	logger.Infof("found %v files to backup", len(fes))

	// Backup with the provided concurrency.
	sema := sync2.NewSemaphore(backupConcurrency, 0)
	rec := concurrency.AllErrorRecorder{}
	wg := sync.WaitGroup{}
	for i := range fes {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()

			// Wait until we are ready to go, skip if we already
			// encountered an error.
			sema.Acquire()
			defer sema.Release()
			if rec.HasErrors() {
				return
			}

			// Backup the individual file.
			name := fmt.Sprintf("%v", i)
			rec.RecordError(be.backupFile(ctx, cnf, mysqld, logger, bh, &fes[i], name, hookExtraEnv))
		}(i)
	}

	wg.Wait()
	if rec.HasErrors() {
		return rec.Error()
	}

	// open the MANIFEST
	wc, err := bh.AddFile(ctx, backupManifest, 0)
	if err != nil {
		return vterrors.Wrapf(err, "cannot add %v to backup", backupManifest)
	}
	defer func() {
		if closeErr := wc.Close(); err == nil {
			err = closeErr
		}
	}()

	// JSON-encode and write the MANIFEST
	bm := &builtinBackupManifest{
		FileEntries:   fes,
		Position:      replicationPosition,
		TransformHook: *backupStorageHook,
		SkipCompress:  !*backupStorageCompress,
	}
	data, err := json.MarshalIndent(bm, "", "  ")
	if err != nil {
		return vterrors.Wrapf(err, "cannot JSON encode %v", backupManifest)
	}
	if _, err := wc.Write([]byte(data)); err != nil {
		return vterrors.Wrapf(err, "cannot write %v", backupManifest)
	}

	return nil
}
1160908
func (l *lexer) backup() {
	l.pos -= l.width
	l.col, l.line = l.lastCol, l.lastLine
}
1032930
func (fbs *FileBackupStorage) ListBackups(ctx context.Context, dir string) ([]backupstorage.BackupHandle, error) {
	// ReadDir already sorts the results
	p := path.Join(*FileBackupStorageRoot, dir)
	fi, err := ioutil.ReadDir(p)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil
		}
		return nil, err
	}

	result := make([]backupstorage.BackupHandle, 0, len(fi))
	for _, info := range fi {
		if !info.IsDir() {
			continue
		}
		if info.Name() == "." || info.Name() == ".." {
			continue
		}
		result = append(result, &FileBackupHandle{
			fbs:      fbs,
			dir:      dir,
			name:     info.Name(),
			readOnly: true,
		})
	}
	return result, nil
}
398688
func (bs *GCSBackupStorage) StartBackup(ctx context.Context, dir, name string) (backupstorage.BackupHandle, error) {
	c, err := bs.client(ctx)
	if err != nil {
		return nil, err
	}

	return &GCSBackupHandle{
		client:   c,
		bs:       bs,
		dir:      dir,
		name:     name,
		readOnly: false,
	}, nil
}
371083
func (_m *DFS) Backup(info dfs.BackupInfo, w io.Writer) error {
	ret := _m.Called(info, w)

	var r0 error
	if rf, ok := ret.Get(0).(func(dfs.BackupInfo, io.Writer) error); ok {
		r0 = rf(info, w)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
1341658
func (s *Store) backupDB() error {
	if os.Geteuid() != 0 {
		return ErrDBUpdateNeedsRoot
	}
	backupsDir := filepath.Join(s.dir, "db-backups")
	return backup.CreateBackup(s.dbDir(), backupsDir, backupsNumber)
}