// Persist should dump all necessary state to the WriteCloser,
// and invoke close when finished or call Cancel on error.
968824
func (s *flotillaSnapshot) Persist(sink raft.SnapshotSink) error {
	defer sink.Close()
	defer s.pipeR.Close()
	_, e1 := io.Copy(sink, s.pipeR)
	e2 := <-s.copyErr

	if e2 != nil {
		sink.Cancel()
		return fmt.Errorf("Error copying snapshot to pipe: %s", e2)
	}
	if e1 != nil {
		sink.Cancel()
	} else {
		sink.Close()
	}
	return e1
}
1031106
func (w *minifyWriter) Close() error {
	w.pw.Close()
	w.wg.Wait()
	return w.err
}
735238
func persistOutbound(s Store, m packets.ControlPacket) {
	switch m.Details().Qos {
	case 0:
		switch m.(type) {
		case *packets.PubackPacket, *packets.PubcompPacket:
			// Sending puback. delete matching publish
			// from ibound
			s.Del(inboundKeyFromMID(m.Details().MessageID))
		}
	case 1:
		switch m.(type) {
		case *packets.PublishPacket, *packets.PubrelPacket, *packets.SubscribePacket, *packets.UnsubscribePacket:
			// Sending publish. store in obound
			// until puback received
			s.Put(outboundKeyFromMID(m.Details().MessageID), m)
		default:
			chkcond(false)
		}
	case 2:
		switch m.(type) {
		case *packets.PublishPacket:
			// Sending publish. store in obound
			// until pubrel received
			s.Put(outboundKeyFromMID(m.Details().MessageID), m)
		default:
			chkcond(false)
		}
	}
}
1328257
func (p *ProgressWriter) Close() (err error) {
	err = p.w.Close()
	p.stopProgress()
	return
}
540088
func (c *RangeCursor) Continue(val []byte) bool {
	if c.Reverse {
		return val != nil && c.CompareFn(val, c.Min) >= 0
	}

	return val != nil && c.CompareFn(val, c.Max) <= 0
}
670025
func (e *InsertExec) Close() error {
	e.ctx.GetSessionVars().CurrInsertValues = chunk.Row{}
	e.setMessage()
	if e.SelectExec != nil {
		return e.SelectExec.Close()
	}
	return nil
}
843243
func (s *SlaveHealthChecker) Continue(slaveUPID *upid.UPID) {
	s.Lock()
	defer s.Unlock()
	s.paused = false
	s.slaveUPID = slaveUPID
}
520947
func (a *Agent) persistCheckState(check *checks.CheckTTL, status, output string) error {
	// Create the persisted state
	state := persistedCheckState{
		CheckID: check.CheckID,
		Status:  status,
		Output:  output,
		Expires: time.Now().Add(check.TTL).Unix(),
	}

	// Encode the state
	buf, err := json.Marshal(state)
	if err != nil {
		return err
	}

	// Create the state dir if it doesn't exist
	dir := filepath.Join(a.config.DataDir, checkStateDir)
	if err := os.MkdirAll(dir, 0700); err != nil {
		return fmt.Errorf("failed creating check state dir %q: %s", dir, err)
	}

	// Write the state to the file
	file := filepath.Join(dir, checkIDHash(check.CheckID))

	// Create temp file in same dir, to make more likely atomic
	tempFile := file + ".tmp"

	// persistCheckState is called frequently, so don't use writeFileAtomic to avoid calling fsync here
	if err := ioutil.WriteFile(tempFile, buf, 0600); err != nil {
		return fmt.Errorf("failed writing temp file %q: %s", tempFile, err)
	}
	if err := os.Rename(tempFile, file); err != nil {
		return fmt.Errorf("failed to rename temp file from %q to %q: %s", tempFile, file, err)
	}

	return nil
}
1227243
func (c *Client) saveState() error {
	var wg sync.WaitGroup
	var l sync.Mutex
	var mErr multierror.Error
	runners := c.getAllocRunners()
	wg.Add(len(runners))

	for id, ar := range runners {
		go func(id string, ar AllocRunner) {
			err := c.stateDB.PutAllocation(ar.Alloc())
			if err != nil {
				c.logger.Error("error saving alloc state", "error", err, "alloc_id", id)
				l.Lock()
				multierror.Append(&mErr, err)
				l.Unlock()
			}
			wg.Done()
		}(id, ar)
	}

	wg.Wait()
	return mErr.ErrorOrNil()
}
241632
func (s *Store) persist(higher Snapshot, persistOptions StorePersistOptions) (
	Snapshot, error) {
	wasCompacted, err := s.compactMaybe(higher, persistOptions)
	if err != nil {
		return nil, err
	}
	if wasCompacted {
		return s.Snapshot()
	}

	// If no dirty higher items, we're still clean, so just snapshot.
	// If in case of ReadOnly mode, just snapshot.
	if higher == nil || s.Options().CollectionOptions.ReadOnly {
		return s.Snapshot()
	}

	startTime := time.Now()

	ss, ok := higher.(*segmentStack)
	if !ok {
		return nil, fmt.Errorf("store: can only persist segmentStack")
	}

	// If higher segment has no data, we're still clean, so just snapshot.
	if ss.isEmpty() {
		return s.Snapshot()
	}

	fref, file, err := s.startOrReuseFile()
	if err != nil {
		return nil, err
	}
	defer fref.DecRef()

	// TODO: Pre-allocate file space up front?

	// Recursively sort all child collection stacks if sorting was deferred.
	ss.ensureFullySorted()

	// Recursively build a new store footer combined with higher snapshot.
	s.m.Lock()
	footer := s.buildNewFooter(s.footer, ss)
	s.m.Unlock()

	// Recursively write out all the segments of the snapshot.
	err = s.persistSegments(ss, footer, file, fref)
	if err != nil {
		return nil, err
	}

	// Recursively load all segments of the newly persisted footer.
	err = footer.loadSegments(s.options, fref)
	if err != nil {
		return nil, err
	}

	// Recursively persist all footers of top-level and child collections.
	err = s.persistFooter(file, footer, persistOptions)
	if err != nil {
		footer.DecRef()
		return nil, err
	}

	footer.AddRef() // One ref-count will be held by the store.

	s.m.Lock()
	prevFooter := s.footer
	s.footer = footer
	s.totPersists++
	s.m.Unlock()

	s.histograms["PersistUsecs"].Add(
		uint64(time.Since(startTime).Nanoseconds()/1000), 1)

	if prevFooter != nil {
		prevFooter.DecRef()
	}

	return footer, nil // The other ref-count returned to caller.
}
1044246
func (ss *raftSnapshot) Persist(sink raft.SnapshotSink) error {
	// Write data to sink.
	if _, err := sink.Write(ss.data); err != nil {
		sink.Cancel()
		return err
	}

	// Close and exit.
	return sink.Close()
}
1236952
func (a *Agent) persistService(service *structs.NodeService) error {
	svcPath := filepath.Join(a.config.DataDir, servicesDir, stringHash(service.ID))

	wrapped := persistedService{
		Token:   a.State.ServiceToken(service.ID),
		Service: service,
	}
	encoded, err := json.Marshal(wrapped)
	if err != nil {
		return err
	}

	return file.WriteAtomic(svcPath, encoded)
}
406677
func (st *State) Close() (err error) {
	defer errors.DeferredAnnotatef(&err, "closing state failed")
	if err := st.stopWorkers(); err != nil {
		return errors.Trace(err)
	}
	st.session.Close()
	logger.Debugf("closed state without error")
	// Remove the reference.
	profileTracker.Remove(st)
	return nil
}
245994
func ToWriteCloser(w io.Writer) io.WriteCloser {
	if rw, ok := w.(io.WriteCloser); ok {
		return rw
	}

	return struct {
		io.Writer
		io.Closer
	}{
		w,
		ioutil.NopCloser(nil),
	}
}
122369
func (writer *MultiWriter) Close() {
	writer.lock.Lock()
	defer writer.lock.Unlock()

	for _, fileWriter := range writer.writers {
		fileWriter.Close()
	}
	writer.closed = true
}
889256
func (a *Agent) persistProxy(proxy *local.ManagedProxy, FromFile bool) error {
	proxyPath := filepath.Join(a.config.DataDir, proxyDir,
		stringHash(proxy.Proxy.ProxyService.ID))

	wrapped := persistedProxy{
		ProxyToken: proxy.ProxyToken,
		Proxy:      proxy.Proxy,
		FromFile:   FromFile,
	}
	encoded, err := json.Marshal(wrapped)
	if err != nil {
		return err
	}

	return file.WriteAtomic(proxyPath, encoded)
}
1312776
func (cfg *Config) save(storage util.Storage) {
	storage.Set("uuid", []byte(cfg.id))
	storage.Set("version", []byte(fmt.Sprintf("%d", cfg.version)))
	storage.Set("configHash", []byte(cfg.configHash))
}