// Persist saves the FSM snapshot out to the given sink.
13278
func (s *snapshot) Persist(sink raft.SnapshotSink) error {
	defer metrics.MeasureSince([]string{"fsm", "persist"}, time.Now())

	// Write the header
	header := snapshotHeader{
		LastIndex: s.state.LastIndex(),
	}
	encoder := codec.NewEncoder(sink, msgpackHandle)
	if err := encoder.Encode(&header); err != nil {
		sink.Cancel()
		return err
	}

	// Run all the persisters to write the FSM state.
	for _, fn := range persisters {
		if err := fn(s, sink, encoder); err != nil {
			sink.Cancel()
			return err
		}
	}
	return nil
}
169711
func (b *AESGCMBarrier) persistKeyring(ctx context.Context, keyring *Keyring) error {
	// Create the keyring entry
	keyringBuf, err := keyring.Serialize()
	defer memzero(keyringBuf)
	if err != nil {
		return errwrap.Wrapf("failed to serialize keyring: {{err}}", err)
	}

	// Create the AES-GCM
	gcm, err := b.aeadFromKey(keyring.MasterKey())
	if err != nil {
		return err
	}

	// Encrypt the barrier init value
	value, err := b.encrypt(keyringPath, initialKeyTerm, gcm, keyringBuf)
	if err != nil {
		return err
	}

	// Create the keyring physical entry
	pe := &physical.Entry{
		Key:   keyringPath,
		Value: value,
	}
	if err := b.backend.Put(ctx, pe); err != nil {
		return errwrap.Wrapf("failed to persist keyring: {{err}}", err)
	}

	// Serialize the master key value
	key := &Key{
		Term:    1,
		Version: 1,
		Value:   keyring.MasterKey(),
	}
	keyBuf, err := key.Serialize()
	defer memzero(keyBuf)
	if err != nil {
		return errwrap.Wrapf("failed to serialize master key: {{err}}", err)
	}

	// Encrypt the master key
	activeKey := keyring.ActiveKey()
	aead, err := b.aeadFromKey(activeKey.Value)
	if err != nil {
		return err
	}
	value, err = b.encrypt(masterKeyPath, activeKey.Term, aead, keyBuf)
	if err != nil {
		return err
	}

	// Update the masterKeyPath for standby instances
	pe = &physical.Entry{
		Key:   masterKeyPath,
		Value: value,
	}
	if err := b.backend.Put(ctx, pe); err != nil {
		return errwrap.Wrapf("failed to persist master key: {{err}}", err)
	}
	return nil
}
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)
}
710727
func (bsj BlockStoreStateJSON) Save(db dbm.DB) {
	bytes, err := cdc.MarshalJSON(bsj)
	if err != nil {
		cmn.PanicSanity(fmt.Sprintf("Could not marshal state bytes: %v", err))
	}
	db.SetSync(blockStoreKey, bytes)
}
890681
func persistInbound(s Store, m packets.ControlPacket) {
	switch m.Details().Qos {
	case 0:
		switch m.(type) {
		case *packets.PubackPacket, *packets.SubackPacket, *packets.UnsubackPacket, *packets.PubcompPacket:
			// Received a puback. delete matching publish
			// from obound
			s.Del(outboundKeyFromMID(m.Details().MessageID))
		case *packets.PublishPacket, *packets.PubrecPacket, *packets.PingrespPacket, *packets.ConnackPacket:
		default:
			ERROR.Println(STR, "Asked to persist an invalid messages type")
		}
	case 1:
		switch m.(type) {
		case *packets.PublishPacket, *packets.PubrelPacket:
			// Received a publish. store it in ibound
			// until puback sent
			s.Put(inboundKeyFromMID(m.Details().MessageID), m)
		default:
			ERROR.Println(STR, "Asked to persist an invalid messages type")
		}
	case 2:
		switch m.(type) {
		case *packets.PublishPacket:
			// Received a publish. store it in ibound
			// until pubrel received
			s.Put(inboundKeyFromMID(m.Details().MessageID), m)
		default:
			ERROR.Println(STR, "Asked to persist an invalid messages type")
		}
	}
}
771722
func (c *asyncClient) Save() (stat FutureBool, err Error) {
	resp, err := c.conn.QueueRequest(&SAVE, [][]byte{})
	if err == nil {
		stat = resp.future.(FutureBool)
	}

	return

}
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)
}
1096671
func (s *Store) persistSegments(ss *segmentStack, footer *Footer,
	file File, fref *FileRef) error {
	// First persist the child segments recursively.
	for cName, childSegStack := range ss.childSegStacks {
		err := s.persistSegments(childSegStack, footer.ChildFooters[cName],
			file, fref)
		if err != nil {
			return err
		}
	}

	for _, segment := range ss.a {
		if segment.Len() <= 0 {
			// With multiple child collections it is possible that some child
			// collections segments are empty. Ok to skip these empty segments.
			continue
		}

		segmentLoc, err := s.persistSegment(file, segment, s.options)
		if err != nil {
			return err
		}

		footer.SegmentLocs = append(footer.SegmentLocs, segmentLoc)
	}

	return nil
}
1346787
func (m *SnapshotMetadata) save() error {
	// This is not safe for concurrent access.
	// Exported methods will deal with locking.
	jsonData, err := json.Marshal(m.snapshotMetadata)
	if err != nil {
		glog.Errorf("Error encoding metadata to json: %s", err)
		return ErrInvalidMetadata
	}
	return ioutil.WriteFile(m.path, jsonData, 0644)
}
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
}
646308
func ContinueFSMWorkflowInput(ctx *FSMContext, data interface{}) string {
	ss := new(SerializedState)
	stateData := ctx.Serialize(data)

	ss.ReplicationData.StateData = stateData
	ss.ReplicationData.StateName = ctx.serialization.InitialState()
	ss.ReplicationData.StateVersion = ctx.stateVersion

	return ctx.Serialize(ss)
}
193525
func (pwm *Manager) Save(username, secret string) error {
	//TODO: username and secret validation

	storedSecret := userSecret{Username: username, Secret: secret}

	_, err := pwm.collection.Upsert(bson.M{"username": username}, storedSecret)

	return err
}
263729
func (woc *wfOperationCtx) persistWorkflowSizeLimitErr(wfClient v1alpha1.WorkflowInterface, err error) {
	woc.wf = woc.orig.DeepCopy()
	woc.markWorkflowError(err, true)
	_, err = wfClient.Update(woc.wf)
	if err != nil {
		woc.log.Warnf("Error updating workflow: %v", err)
	}
}
249131
func (c *Client) Persist(key string) (bool, error) {
	var ret bool

	err := c.command(
		&ret,
		[]byte("PERSIST"),
		[]byte(key),
	)

	return ret, err
}
1180654
func (e *Engine) writeSnapshotAndCommit(ctx context.Context, log *zap.Logger, snapshot *Cache, segments []string) (err error) {
	defer func() {
		if err != nil {
			e.Cache.ClearSnapshot(false)
		}
	}()

	// write the new snapshot files
	newFiles, err := e.Compactor.WriteSnapshot(ctx, snapshot)
	if err != nil {
		log.Info("Error writing snapshot from compactor", zap.Error(err))
		return err
	}

	return e.snapshotter.CommitSegments(ctx, segments, func() error {
		e.mu.RLock()
		defer e.mu.RUnlock()

		// update the file store with these new files
		if err := e.FileStore.Replace(nil, newFiles); err != nil {
			log.Info("Error adding new TSM files from snapshot", zap.Error(err))
			return err
		}

		// clear the snapshot from the in-memory cache
		e.Cache.ClearSnapshot(true)
		return nil
	})
}
112160
func (s *Snapshot) Persist(sink raft.SnapshotSink) (err error) {
	defer func() {
		if err != nil {
			sink.Cancel()
		}
	}()

	encoder := yaml.NewEncoder(sink)
	if err := encoder.Encode(s); err != nil {
		return errors.Trace(err)
	}
	if err := encoder.Close(); err != nil {
		return errors.Trace(err)
	}
	return sink.Close()
}
84619
func (cache *DiskMDCacheLocal) Commit(
	ctx context.Context, tlfID tlf.ID, rev kbfsmd.Revision) error {
	cache.lock.Lock()
	defer cache.lock.Unlock()
	err := cache.checkCacheLocked(ctx, "MD(Commit)")
	if err != nil {
		return err
	}

	stagedMDs := cache.tlfsStaged[tlfID]
	if len(stagedMDs) == 0 {
		// Nothing to do.
		return nil
	}
	newStagedMDs := make([]diskMDBlock, 0, len(stagedMDs)-1)
	foundMD := false
	// The staged MDs list is unordered, so iterate through the whole
	// thing to find what should remain after commiting `rev`.
	for _, md := range stagedMDs {
		if md.Revision > rev {
			newStagedMDs = append(newStagedMDs, md)
			continue
		} else if md.Revision < rev {
			continue
		} else if foundMD {
			// Duplicate.
			continue
		}
		foundMD = true

		encodedMetadata, err := cache.config.Codec().Encode(&md)
		if err != nil {
			return err
		}

		err = cache.headsDb.PutWithMeter(
			tlfID.Bytes(), encodedMetadata, cache.putMeter)
		if err != nil {
			return err
		}
	}

	if !foundMD {
		// Nothing to do.
		return nil
	}

	cache.tlfsCached[tlfID] = rev
	if len(newStagedMDs) == 0 {
		delete(cache.tlfsStaged, tlfID)
	} else {
		cache.tlfsStaged[tlfID] = newStagedMDs
	}
	return nil
}