// Restore restores the settings from State.
8938
func Restore(fd int, st State) error {
	if err := sys.Setattr(fd, sys.TCSANOW, &st.wrap); err != nil {
		return os.NewSyscallError("sys.Setattr", err)
	}
	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
}
864724
func (kvm *Clone) Restore(rd io.Reader) error {
	kvm.mu.Lock()
	defer kvm.mu.Unlock()
	data, err := ioutil.ReadAll(rd)
	if err != nil {
		return err
	}
	var keys map[string][]byte
	if err := json.Unmarshal(data, &keys); err != nil {
		return err
	}
	kvm.keys = keys
	return nil
}
164232
func restoreTerm(fd int, state *State) error {
	return setTermios(fd, &state.termios)
}
1172347
func (t *Term) Restore() error {
	return termios.Tcsetattr(uintptr(t.fd), termios.TCIOFLUSH, &t.orig)
}
408815
func (p *Plot) Restore() *Plot {
	if p.env.parent == nil {
		panic("unbalanced Save/Restore")
	}
	p.env = p.env.parent
	return p
}
1309861
func Reset() {
	states = stateMap{
		m: map[string]*remote.State{},
	}

	locks = lockMap{
		m: map[string]*state.LockInfo{},
	}
}
119999
func (deploy *Deploy) Restore() (*Response, error) {
	return deploy.client.Request("POST", path.Join(deploy.apiPath(), "restore"), nil, deploy)
}
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
}
801039
func (e *Executor) Restore(id string, stdout, stderr io.WriteCloser) (bool, error) {
	alive, _, p, err := e.client.Restore(context.Background(), id, attachStreamsFunc(stdout, stderr))
	if err != nil && !errdefs.IsNotFound(err) {
		return false, err
	}
	if !alive {
		deleteTaskAndContainer(context.Background(), e.client, id, p)
	}
	return alive, nil
}
885237
func (s *Store) Restore(rc io.ReadCloser) error {
	s.restoreMu.Lock()
	defer s.restoreMu.Unlock()

	// Get size of database.
	var sz uint64
	if err := binary.Read(rc, binary.LittleEndian, &sz); err != nil {
		return err
	}

	// Now read in the database file data and restore.
	database := make([]byte, sz)
	if _, err := io.ReadFull(rc, database); err != nil {
		return err
	}

	// Create temp file and write incoming database to there.
	temp, err := tempfile()
	if err != nil {
		return err
	}
	defer os.Remove(temp.Name())
	defer temp.Close()

	if _, err := temp.Write(database); err != nil {
		return err
	}

	// Create new database from file, connect, and load
	// existing database from that.
	db, err := sdb.New(temp.Name(), "", false)
	if err != nil {
		return err
	}
	conn, err := db.Connect()
	if err != nil {
		return err
	}
	defer conn.Close()
	if err := s.dbConn.Load(conn); err != nil {
		return err
	}

	// Get size of meta, read those bytes, and set to meta.
	if err := binary.Read(rc, binary.LittleEndian, &sz); err != nil {
		return err
	}
	meta := make([]byte, sz)
	if _, err := io.ReadFull(rc, meta); err != nil {
		return err
	}
	err = func() error {
		s.metaMu.Lock()
		defer s.metaMu.Unlock()
		return json.Unmarshal(meta, &s.meta)
	}()
	if err != nil {
		return err
	}

	// Get size of connections, read those bytes, and set to connections.
	if err := binary.Read(rc, binary.LittleEndian, &sz); err != nil {
		return err
	}
	conns := make([]byte, sz)
	if _, err := io.ReadFull(rc, conns); err != nil {
		return err
	}
	err = func() error {
		s.connsMu.Lock()
		defer s.connsMu.Unlock()
		if err := json.Unmarshal(conns, &s.conns); err != nil {
			return err
		}
		for _, c := range s.conns {
			dbConn, err := s.db.Connect()
			if err != nil {
				return err
			}
			c.Restore(dbConn, s)
		}
		return nil
	}()
	if err != nil {
		return err
	}

	stats.Add(numRestores, 1)
	return nil
}
1127946
func (r *raftFSM) Restore(snapshot io.ReadCloser) (retErr error) {
	s := r.server
	defer snapshot.Close()

	r.Lock()
	defer r.Unlock()

	// This function may be invoked directly from raft.NewRaft() when
	// the node is initialized and if there were exisiting local snapshots,
	// or later, when catching up with a leader. We behave differently
	// depending on the situation. So we need to know if we are called
	// from NewRaft().
	//
	// To do so, we first look at the number of local snapshots before
	// calling NewRaft(). If the number is > 0, it means that Raft will
	// call us within NewRaft(). Raft will restore the latest snapshot
	// first, and only in case of Restore() returning an error will move
	// to the next (earliest) one. When there are none and Restore() still
	// returns an error raft.NewRaft() will return an error.
	//
	// So on error we decrement the number of snapshots, on success we set
	// it to 0. This means that next time Restore() is invoked, we know it
	// is restoring from a leader, not from the local snapshots.
	inNewRaftCall := r.snapshotsOnInit != 0
	if inNewRaftCall {
		defer func() {
			if retErr != nil {
				r.snapshotsOnInit--
			} else {
				r.snapshotsOnInit = 0
			}
		}()
	} else {
		s.log.Noticef("restoring from snapshot")
		defer s.log.Noticef("done restoring from snapshot")
	}

	// We need to drop current state. The server will recover from snapshot
	// and all newer Raft entry logs (basically the entire state is being
	// reconstructed from this point on).
	for _, c := range s.channels.getAll() {
		for _, sub := range c.ss.getAllSubs() {
			sub.RLock()
			clientID := sub.ClientID
			sub.RUnlock()
			if err := s.unsubscribeSub(c, clientID, "unsub", sub, false, false); err != nil {
				return err
			}
		}
		c.store.Subs.Flush()
	}
	for clientID := range s.clients.getClients() {
		if _, err := s.clients.unregister(clientID); err != nil {
			return err
		}
	}

	sizeBuf := make([]byte, 4)
	// Read the snapshot size.
	if _, err := io.ReadFull(snapshot, sizeBuf); err != nil {
		if err == io.EOF {
			return nil
		}
		return err
	}
	// Read the snapshot.
	size := util.ByteOrder.Uint32(sizeBuf)
	buf := make([]byte, size)
	if _, err := io.ReadFull(snapshot, buf); err != nil {
		return err
	}

	serverSnap := &spb.RaftSnapshot{}
	if err := serverSnap.Unmarshal(buf); err != nil {
		panic(err)
	}
	if err := r.restoreClientsFromSnapshot(serverSnap); err != nil {
		return err
	}
	return r.restoreChannelsFromSnapshot(serverSnap, inNewRaftCall)
}
954984
func (n *networkNamespace) Restore(ifsopt map[string][]IfaceOption, routes []*types.StaticRoute, gw net.IP, gw6 net.IP) error {
	// restore interfaces
	for name, opts := range ifsopt {
		if !strings.Contains(name, "+") {
			return fmt.Errorf("wrong iface name in restore osl sandbox interface: %s", name)
		}
		seps := strings.Split(name, "+")
		srcName := seps[0]
		dstPrefix := seps[1]
		i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n}
		i.processInterfaceOptions(opts...)
		if i.master != "" {
			i.dstMaster = n.findDst(i.master, true)
			if i.dstMaster == "" {
				return fmt.Errorf("could not find an appropriate master %q for %q",
					i.master, i.srcName)
			}
		}
		if n.isDefault {
			i.dstName = i.srcName
		} else {
			links, err := n.nlHandle.LinkList()
			if err != nil {
				return fmt.Errorf("failed to retrieve list of links in network namespace %q during restore", n.path)
			}
			// due to the docker network connect/disconnect, so the dstName should
			// restore from the namespace
			for _, link := range links {
				addrs, err := n.nlHandle.AddrList(link, netlink.FAMILY_V4)
				if err != nil {
					return err
				}
				ifaceName := link.Attrs().Name
				if strings.HasPrefix(ifaceName, "vxlan") {
					if i.dstName == "vxlan" {
						i.dstName = ifaceName
						break
					}
				}
				// find the interface name by ip
				if i.address != nil {
					for _, addr := range addrs {
						if addr.IPNet.String() == i.address.String() {
							i.dstName = ifaceName
							break
						}
						continue
					}
					if i.dstName == ifaceName {
						break
					}
				}
				// This is to find the interface name of the pair in overlay sandbox
				if strings.HasPrefix(ifaceName, "veth") {
					if i.master != "" && i.dstName == "veth" {
						i.dstName = ifaceName
					}
				}
			}

			var index int
			indexStr := strings.TrimPrefix(i.dstName, dstPrefix)
			if indexStr != "" {
				index, err = strconv.Atoi(indexStr)
				if err != nil {
					return err
				}
			}
			index++
			n.Lock()
			if index > n.nextIfIndex[dstPrefix] {
				n.nextIfIndex[dstPrefix] = index
			}
			n.iFaces = append(n.iFaces, i)
			n.Unlock()
		}
	}

	// restore routes
	for _, r := range routes {
		n.Lock()
		n.staticRoutes = append(n.staticRoutes, r)
		n.Unlock()
	}

	// restore gateway
	if len(gw) > 0 {
		n.Lock()
		n.gw = gw
		n.Unlock()
	}

	if len(gw6) > 0 {
		n.Lock()
		n.gwv6 = gw6
		n.Unlock()
	}

	return nil
}
189365
func restore() (err error) {
	if _, err = stty("echo"); err != nil {
		return
	}

	if _, err = stty(originalState); err != nil {
		return
	}

	return
}
252439
func (ar *allocRunner) Restore() error {
	// Retrieve deployment status to avoid reseting it across agent
	// restarts. Once a deployment status is set Nomad no longer monitors
	// alloc health, so we must persist deployment state across restarts.
	ds, err := ar.stateDB.GetDeploymentStatus(ar.id)
	if err != nil {
		return err
	}

	ar.stateLock.Lock()
	ar.state.DeploymentStatus = ds
	ar.stateLock.Unlock()

	// Restore task runners
	for _, tr := range ar.tasks {
		if err := tr.Restore(); err != nil {
			return err
		}
	}

	return nil
}
390540
func (s *ChangesService) RestoreChange(changeID string, input *RestoreInput) (*ChangeInfo, *Response, error) {
	return s.change("restore", changeID, input)
}
629799
func (v *volumeClient) Restore(volumeID string, snapID string) error {
	response := &api.VolumeResponse{}
	req := v.c.Post().Resource(snapPath + "/restore").Instance(volumeID)
	req.QueryOption(api.OptSnapID, snapID)

	if err := req.Do().Unmarshal(response); err != nil {
		return err
	}
	if response.Error != "" {
		return errors.New(response.Error)
	}
	return nil
}