// Restore mongo database
514175
func (p MongoPlugin) Restore(endpoint plugin.ShieldEndpoint) error {
	mongo, err := mongoConnectionInfo(endpoint)
	if err != nil {
		return err
	}

	cmd := fmt.Sprintf("%s/mongorestore %s", mongo.Bin, connectionString(mongo, false))
	plugin.DEBUG("Exec: %s", cmd)
	return plugin.Exec(cmd, plugin.STDIN)
}
54361
func (r *Runc) Restore(context context.Context, id, bundle string, opts *RestoreOpts) (int, error) {
	args := []string{"restore"}
	if opts != nil {
		oargs, err := opts.args()
		if err != nil {
			return -1, err
		}
		args = append(args, oargs...)
	}
	args = append(args, "--bundle", bundle)
	cmd := r.command(context, append(args, id)...)
	if opts != nil && opts.IO != nil {
		opts.Set(cmd)
	}
	ec, err := Monitor.Start(cmd)
	if err != nil {
		return -1, err
	}
	if opts != nil && opts.IO != nil {
		if c, ok := opts.IO.(StartCloser); ok {
			if err := c.CloseAfterStart(); err != nil {
				return -1, err
			}
		}
	}
	return Monitor.Wait(cmd, ec)
}
137272
func (c *Client) RestoreBackup(id, backupID string) error {
	values := url.Values{
		"SUBID":    {id},
		"BACKUPID": {backupID},
	}

	if err := c.post(`server/restore_backup`, values, nil); err != nil {
		return err
	}
	return nil
}
366181
func (t *Terminal) Restore() error {
	if t.mode != 0 {
		if err := sys.Setattr(t.fd, sys.TCSANOW, &t.oldState); err != nil {
			return os.NewSyscallError("sys.Setattr", err)
		}
		t.lastState = t.oldState
		t.mode = 0
	}
	return nil
}
408815
func (p *Plot) Restore() *Plot {
	if p.env.parent == nil {
		panic("unbalanced Save/Restore")
	}
	p.env = p.env.parent
	return p
}
283615
func (l *kvLedger) recoverDBs() error {
	logger.Debugf("Entering recoverDB()")
	if err := l.syncStateAndHistoryDBWithBlockstore(); err != nil {
		return err
	}
	if err := l.syncStateDBWithPvtdatastore(); err != nil {
		return err
	}
	return nil
}
1069156
func (f *flotillaState) Restore(in io.ReadCloser) error {
	// stream to filePath.tmp
	tempData := f.tempPath + "/data.mdb"
	_ = os.Remove(tempData)
	tempFile, err := os.Create(tempData)
	if err != nil {
		return err
	}
	defer tempFile.Close()
	if _, err = io.Copy(tempFile, in); err != nil {
		return err
	}
	// unlink existing DB and move new one into place
	// can't atomically rename directories so have to lock for this
	f.l.Lock()
	defer f.l.Unlock()
	if err = syscall.Unlink(f.dataPath + "/data.mdb"); err != nil {
		return err
	}
	if err = syscall.Unlink(f.dataPath + "/lock.mdb"); err != nil {
		return err
	}
	if err = os.Rename(tempData, f.dataPath+"/data.mdb"); err != nil {
		return err
	}
	// mark existing env as closeable when all outstanding txns finish
	// posix holds onto our data until we release FD
	f.env.Close()
	// re-initialize env
	f.env, err = newenv(f.dataPath)
	return err
}
537274
func Restore(
	ctx context.Context,
	cnf *Mycnf,
	mysqld MysqlDaemon,
	dir string,
	restoreConcurrency int,
	hookExtraEnv map[string]string,
	localMetadata map[string]string,
	logger logutil.Logger,
	deleteBeforeRestore bool,
	dbName string) (mysql.Position, error) {

	rval := mysql.Position{}

	// Wait for mysqld to be ready, in case it was launched in parallel with us.
	if err := mysqld.Wait(ctx, cnf); err != nil {
		return mysql.Position{}, err
	}

	if !deleteBeforeRestore {
		logger.Infof("Restore: checking no existing data is present")
		ok, err := checkNoDB(ctx, mysqld, dbName)
		if err != nil {
			return mysql.Position{}, err
		}
		if !ok {
			logger.Infof("Auto-restore is enabled, but mysqld already contains data. Assuming vttablet was just restarted.")
			if err = PopulateMetadataTables(mysqld, localMetadata, dbName); err == nil {
				err = ErrExistingDB
			}
			return mysql.Position{}, err
		}
	}

	// find the right backup handle: most recent one, with a MANIFEST
	logger.Infof("Restore: looking for a suitable backup to restore")
	bs, err := backupstorage.GetBackupStorage()
	if err != nil {
		return mysql.Position{}, err
	}
	defer bs.Close()

	bhs, err := bs.ListBackups(ctx, dir)
	if err != nil {
		return mysql.Position{}, vterrors.Wrap(err, "ListBackups failed")
	}

	if len(bhs) == 0 {
		// There are no backups (not even broken/incomplete ones).
		logger.Errorf("no backup to restore on BackupStorage for directory %v. Starting up empty.", dir)
		// Since this is an empty database make sure we start replication at the beginning
		if err = mysqld.ResetReplication(ctx); err == nil {
			logger.Errorf("error reseting slave replication: %v. Continuing", err)
			err = ErrNoBackup
		}

		if err2 := PopulateMetadataTables(mysqld, localMetadata, dbName); err2 == nil {
			err = ErrNoBackup
		}
		return mysql.Position{}, err
	}

	be, err := GetBackupEngine()
	if err != nil {
		return mysql.Position{}, vterrors.Wrap(err, "Failed to find backup engine")
	}
	if rval, err = be.ExecuteRestore(ctx, cnf, mysqld, logger, dir, bhs, restoreConcurrency, hookExtraEnv); err != nil {
		return rval, err
	}

	// mysqld needs to be running in order for mysql_upgrade to work.
	// If we've just restored from a backup from previous MySQL version then mysqld
	// may fail to start due to a different structure of mysql.* tables. The flag
	// --skip-grant-tables ensures that these tables are not read until mysql_upgrade
	// is executed. And since with --skip-grant-tables anyone can connect to MySQL
	// without password, we are passing --skip-networking to greatly reduce the set
	// of those who can connect.
	logger.Infof("Restore: starting mysqld for mysql_upgrade")
	// Note Start will use dba user for waiting, this is fine, it will be allowed.
	err = mysqld.Start(context.Background(), cnf, "--skip-grant-tables", "--skip-networking")
	if err != nil {
		return mysql.Position{}, err
	}

	logger.Infof("Restore: running mysql_upgrade")
	if err := mysqld.RunMysqlUpgrade(); err != nil {
		return mysql.Position{}, vterrors.Wrap(err, "mysql_upgrade failed")
	}

	// Populate local_metadata before starting without --skip-networking,
	// so it's there before we start announcing ourselves.
	logger.Infof("Restore: populating local_metadata")
	err = PopulateMetadataTables(mysqld, localMetadata, dbName)
	if err != nil {
		return mysql.Position{}, err
	}

	// The MySQL manual recommends restarting mysqld after running mysql_upgrade,
	// so that any changes made to system tables take effect.
	logger.Infof("Restore: restarting mysqld after mysql_upgrade")
	err = mysqld.Shutdown(context.Background(), cnf, true)
	if err != nil {
		return mysql.Position{}, err
	}
	err = mysqld.Start(context.Background(), cnf)
	if err != nil {
		return mysql.Position{}, err
	}

	return rval, nil
}
1115082
func Restore() error {
	o, err := getOriginalTermios(saveTermiosFD)
	if err != nil {
		return err
	}
	return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, &o)
}
52678
func (s *CloudBackupServer) Restore(
	ctx context.Context,
	req *api.SdkCloudBackupRestoreRequest,
) (*api.SdkCloudBackupRestoreResponse, error) {
	if s.driver(ctx) == nil {
		return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
	}
	credId := req.GetCredentialId()
	var err error
	if len(req.GetBackupId()) == 0 {
		return nil, status.Error(codes.InvalidArgument, "Must provide backup id")
	} else if len(req.GetCredentialId()) == 0 {
		credId, err = s.defaultCloudBackupCreds(ctx)
		if err != nil {
			return nil, err
		}
	}

	if len(req.GetCredentialId()) != 0 {
		if err := s.checkAccessToCredential(ctx, req.GetCredentialId()); err != nil {
			return nil, err
		}
	}

	r, err := s.driver(ctx).CloudBackupRestore(&api.CloudBackupRestoreRequest{
		ID:                req.GetBackupId(),
		RestoreVolumeName: req.GetRestoreVolumeName(),
		CredentialUUID:    credId,
		NodeID:            req.GetNodeId(),
		Name:              req.GetTaskId(),
	})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "Failed to restore backup: %v", err)
	}

	return &api.SdkCloudBackupRestoreResponse{
		RestoreVolumeId: r.RestoreVolumeID,
		TaskId:          r.Name,
	}, nil

}
57405
func (cr *Context) Restore() {
	C.cairo_restore(cr.Ptr)
	if err := cr.status(); err != nil {
		panic(err)
	}
}
590776
func (m *Mrb) ArenaRestore(idx ArenaIndex) {
	C.mrb_gc_arena_restore(m.state, C.int(idx))
}
702059
func (t *ContainerVolumeTracker) Restore(containerID string, client *docker.Client) error {
	if t == nil {
		return nil
	}
	for dest, archivePath := range t.paths {
		if len(archivePath) == 0 {
			return fmt.Errorf("path %s does not have an archive and cannot be restored", dest)
		}
		glog.V(4).Infof("Restoring contents of %s from %s", dest, archivePath)
		if !strings.HasSuffix(dest, "/") {
			dest = dest + "/"
		}
		exec, err := client.CreateExec(docker.CreateExecOptions{
			Container: containerID,
			Cmd:       []string{"/bin/sh", "-c", "rm -rf $@", "", dest + "*"},
			User:      "0",
		})
		if err != nil {
			return fmt.Errorf("unable to setup clearing preserved path %s: %v", dest, err)
		}
		if err := client.StartExec(exec.ID, docker.StartExecOptions{}); err != nil {
			return fmt.Errorf("unable to clear preserved path %s: %v", dest, err)
		}
		var status *docker.ExecInspect
		for status == nil {
			status, err = client.InspectExec(exec.ID)
			if err != nil {
				break
			}
			if !status.Running {
				break
			}
			status = nil
		}
		if err != nil {
			return fmt.Errorf("clearing preserved path %s did not succeed: %v", dest, err)
		}
		if status.ExitCode != 0 {
			return fmt.Errorf("clearing preserved path %s failed with exit code %d", dest, status.ExitCode)
		}
		err = func() error {
			f, err := os.Open(archivePath)
			if err != nil {
				return fmt.Errorf("unable to open archive %s for preserved path %s: %v", archivePath, dest, err)
			}
			defer f.Close()
			if err := client.UploadToContainer(containerID, docker.UploadToContainerOptions{
				InputStream: f,
				Path:        dest,
			}); err != nil {
				return fmt.Errorf("unable to upload preserved contents from %s to %s: %v", archivePath, dest, err)
			}
			return nil
		}()
		if err != nil {
			return err
		}
	}
	return nil
}
1369022
func (m *ExpirationManager) Restore(errorFunc func()) (retErr error) {
	defer func() {
		// Turn off restore mode. We can do this safely without the lock because
		// if restore mode finished successfully, restore mode was already
		// disabled with the lock. In an error state, this will allow the
		// Stop() function to shut everything down.
		atomic.StoreInt32(m.restoreMode, 0)

		switch {
		case retErr == nil:
		case strings.Contains(retErr.Error(), context.Canceled.Error()):
			// Don't run error func because we lost leadership
			m.logger.Warn("context cancled while restoring leases, stopping lease loading")
			retErr = nil
		case errwrap.Contains(retErr, ErrBarrierSealed.Error()):
			// Don't run error func because we're likely already shutting down
			m.logger.Warn("barrier sealed while restoring leases, stopping lease loading")
			retErr = nil
		default:
			m.logger.Error("error restoring leases", "error", retErr)
			if errorFunc != nil {
				errorFunc()
			}
		}
	}()

	// Accumulate existing leases
	m.logger.Debug("collecting leases")
	existing, leaseCount, err := m.collectLeases()
	if err != nil {
		return err
	}
	m.logger.Debug("leases collected", "num_existing", leaseCount)

	// Make the channels used for the worker pool
	type lease struct {
		namespace *namespace.Namespace
		id        string
	}
	broker := make(chan *lease)
	quit := make(chan bool)
	// Buffer these channels to prevent deadlocks
	errs := make(chan error, len(existing))
	result := make(chan struct{}, len(existing))

	// Use a wait group
	wg := &sync.WaitGroup{}

	// Create 64 workers to distribute work to
	for i := 0; i < consts.ExpirationRestoreWorkerCount; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()

			for {
				select {
				case lease, ok := <-broker:
					// broker has been closed, we are done
					if !ok {
						return
					}

					ctx := namespace.ContextWithNamespace(m.quitContext, lease.namespace)
					err := m.processRestore(ctx, lease.id)
					if err != nil {
						errs <- err
						continue
					}

					// Send message that lease is done
					result <- struct{}{}

				// quit early
				case <-quit:
					return

				case <-m.quitCh:
					return
				}
			}
		}()
	}

	// Distribute the collected keys to the workers in a go routine
	wg.Add(1)
	go func() {
		defer wg.Done()
		i := 0
		for ns := range existing {
			for _, leaseID := range existing[ns] {
				i++
				if i%500 == 0 {
					m.logger.Debug("leases loading", "progress", i)
				}

				select {
				case <-quit:
					return

				case <-m.quitCh:
					return

				default:
					broker <- &lease{
						namespace: ns,
						id:        leaseID,
					}
				}
			}
		}

		// Close the broker, causing worker routines to exit
		close(broker)
	}()

	// Ensure all keys on the chan are processed
	for i := 0; i < leaseCount; i++ {
		select {
		case err := <-errs:
			// Close all go routines
			close(quit)
			return err

		case <-m.quitCh:
			close(quit)
			return nil

		case <-result:
		}
	}

	// Let all go routines finish
	wg.Wait()

	m.restoreModeLock.Lock()
	atomic.StoreInt32(m.restoreMode, 0)
	m.restoreLoaded.Range(func(k, v interface{}) bool {
		m.restoreLoaded.Delete(k)
		return true
	})
	m.restoreLocks = nil
	m.restoreModeLock.Unlock()

	m.logger.Info("lease restore complete")
	return nil
}
1056631
func (f *Facade) Restore(ctx datastore.Context, r io.Reader, backupInfo *dfs.BackupInfo, backupFilename string) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.Restore"))
	// Do not DFSLock here, ControlPlaneDao does that
	stime := time.Now()
	plog.Info("Started restore from backup")
	alog := f.auditLogger.Message(ctx, "Started Restoring from Backup").Action(audit.Restore).
			WithFields(logrus.Fields{
				"backupfile": backupFilename,
				"starttime": stime.UTC().Format("2006-01-02-150405"),
			})
	alog.Succeeded()
	if err := f.dfs.Restore(r, backupInfo.BackupVersion); err != nil {
		plog.WithError(err).Debug("Could not restore from backup")
		return alog.Error(err)
	}
	if err := f.RestoreServiceTemplates(ctx, backupInfo.Templates); err != nil {
		plog.WithError(err).Debug("Could not restore service templates from backup")
		return alog.Error(err)
	}
	plog.Infof("Restored service templates")
	if err := f.RestoreResourcePools(ctx, backupInfo.Pools); err != nil {
		plog.WithError(err).Debug("Could not restore resource pools from backup")
		return alog.Error(err)
	}
	plog.Info("Restored resource pools")
	for _, snapshot := range backupInfo.Snapshots {
		logger := plog.WithField("snapshot", snapshot)
		if err := f.Rollback(ctx, snapshot, false); err != nil {
			logger.WithError(err).Debug("Could not rollback snapshot")
			return alog.Error(err)
		} else {
			logger.Info("Rolled back snapshot")
			if err := f.dfs.Delete(snapshot); err != nil {
				// if we couldn't delete, untag it so the TTL reaper will get it eventually
				info, err := f.dfs.Info(snapshot)
				if err != nil {
					logger.WithError(err).Warning("Could not get info for snapshot.")
				} else if len(info.Tags) > 0 {
					if _, err := f.dfs.Untag(info.TenantID, info.Tags[0]); err != nil {
						logger.WithError(err).Warning("Could not untag snapshot.  Snapshot must be deleted manually!")
					} else {
						logger.Info("Snapshot from backup untagged.")
					}
				}
			} else {
				logger.Info("Removed snapshot after rollback")
			}
		}

	}
	restoreDuration := time.Since(stime)
	plog.Info("Completed restore from backup")
	alog = f.auditLogger.Message(ctx, "Completed Restoring from Backup").Action(audit.Restore).
		WithFields(logrus.Fields{
			"backupfile": backupFilename,
			"elapsed": fmt.Sprintf("%fsec", restoreDuration.Seconds()),
		})
	alog.Succeeded()
	return nil
}
1042036
func (s *State) Restore(backend Backend, buffers host.LogBuffers) (func(), error) {
	if err := s.Acquire(); err != nil {
		return nil, err
	}
	defer s.Release()

	s.backend = backend

	var resurrect []*host.Job
	if err := s.stateDB.View(func(tx *bolt.Tx) error {
		jobsBucket := tx.Bucket([]byte("jobs"))
		backendJobsBucket := tx.Bucket([]byte("backend-jobs"))
		backendGlobalBucket := tx.Bucket([]byte("backend-global"))
		persistentBucket := tx.Bucket([]byte("persistent-jobs"))

		// restore jobs
		if err := jobsBucket.ForEach(func(k, v []byte) error {
			job := &host.ActiveJob{}
			if err := json.Unmarshal(v, job); err != nil {
				return err
			}
			if job.CreatedAt.IsZero() {
				job.CreatedAt = time.Now().UTC()
			}
			s.jobs[string(k)] = job

			if statusDown(job.Status) {
				if err := s.trackDownJob(job, tx); err != nil {
					return err
				}
			}

			return nil
		}); err != nil {
			return err
		}

		// hand opaque blobs back to backend so it can do its restore
		backendJobsBlobs := make(map[string][]byte)
		if err := backendJobsBucket.ForEach(func(k, v []byte) error {
			backendJobsBlobs[string(k)] = v
			return nil
		}); err != nil {
			return err
		}
		backendGlobalBlob := backendGlobalBucket.Get([]byte("backend"))
		if err := backend.UnmarshalState(s.jobs, backendJobsBlobs, backendGlobalBlob, buffers); err != nil {
			return err
		}

		// resurrect any persistent jobs which are not running
		if err := persistentBucket.ForEach(func(k, v []byte) error {
			for _, job := range s.jobs {
				if job.Job.ID == string(v) && !backend.JobExists(job.Job.ID) {
					resurrect = append(resurrect, job.Job)
				}
			}
			return nil
		}); err != nil {
			return err
		}

		return nil
	}); err != nil && err != io.EOF {
		return nil, fmt.Errorf("could not restore from host persistence db: %s", err)
	}

	return func() {
		if len(resurrect) == 0 {
			return
		}
		var wg sync.WaitGroup
		wg.Add(len(resurrect))
		for _, job := range resurrect {
			go func(job *host.Job) {
				// generate a new job id, this is a new job
				newJob := job.Dup()
				newJob.ID = cluster.GenerateJobID(s.id, "")
				if _, ok := newJob.Config.Env["FLYNN_JOB_ID"]; ok {
					newJob.Config.Env["FLYNN_JOB_ID"] = newJob.ID
				}
				log.Printf("resurrecting %s as %s", job.ID, newJob.ID)
				s.AddJob(newJob)
				backend.Run(newJob, nil, nil)
				wg.Done()
			}(job)
		}
		wg.Wait()
	}, nil
}
1188889
func (p *parser) restore(pt savepoint) {
	if pt.offset == p.pt.offset {
		return
	}
	p.pt = pt
}