// Snapshots creates snapshots of the services by calling the
// simulation_snapshot RPC method
480264
func (sn *SimNode) Snapshots() (map[string][]byte, error) {
	sn.lock.RLock()
	services := make(map[string]node.Service, len(sn.running))
	for name, service := range sn.running {
		services[name] = service
	}
	sn.lock.RUnlock()
	if len(services) == 0 {
		return nil, errors.New("no running services")
	}
	snapshots := make(map[string][]byte)
	for name, service := range services {
		if s, ok := service.(interface {
			Snapshot() ([]byte, error)
		}); ok {
			snap, err := s.Snapshot()
			if err != nil {
				return nil, err
			}
			snapshots[name] = snap
		}
	}
	return snapshots, nil
}
1113724
func (s *Store) Snapshot() *Store {
	if s.IsReadOnly() {
		return s
	}

	s.collLock.RLock()
	defer s.collLock.RUnlock()

	// Return a read-only Store with the new Collection set.
	snap := &Store{
		collLock:  nil,
		colls:     make(map[string]*Collection, len(s.colls)),
		collNames: s.collNames,
	}

	// Create a read-only Collection for each coll.
	for k, coll := range s.colls {
		newColl := &Collection{
			name: coll.name,
		}
		newColl.setRoot(coll.currentRoot())
		snap.colls[k] = newColl
	}
	return snap
}
419723
func (c *OpenChannel) Snapshot() *ChannelSnapshot {
	c.RLock()
	defer c.RUnlock()

	localCommit := c.LocalCommitment
	snapshot := &ChannelSnapshot{
		RemoteIdentity:    *c.IdentityPub,
		ChannelPoint:      c.FundingOutpoint,
		Capacity:          c.Capacity,
		TotalMSatSent:     c.TotalMSatSent,
		TotalMSatReceived: c.TotalMSatReceived,
		ChainHash:         c.ChainHash,
		ChannelCommitment: ChannelCommitment{
			LocalBalance:  localCommit.LocalBalance,
			RemoteBalance: localCommit.RemoteBalance,
			CommitHeight:  localCommit.CommitHeight,
			CommitFee:     localCommit.CommitFee,
		},
	}

	// Copy over the current set of HTLCs to ensure the caller can't mutate
	// our internal state.
	snapshot.Htlcs = make([]HTLC, len(localCommit.Htlcs))
	for i, h := range localCommit.Htlcs {
		snapshot.Htlcs[i] = h.Copy()
	}

	return snapshot
}
265936
func (db *memDB) Snapshot() View {
	return &memdbView{
		txn: db.store.Txn(false),
	}
}
627847
func (d *Lepton3) Snapshot() (*RawFrame, error) {
	if err := d.Open(); err != nil {
		return nil, err
	}
	defer d.Close()
	frame := new(RawFrame)
	if err := d.NextFrame(frame); err != nil {
		return nil, err
	}
	return frame, nil
}
1054935
func (s *DescribeSnapshotsOutput) SetSnapshots(v []*Snapshot) *DescribeSnapshotsOutput {
	s.Snapshots = v
	return s
}
216601
func (rs *RaftStorage) Snapshot() raftpb.Snapshot {
	sn, _ := rs.ram.Snapshot() // Snapshot always returns nil error
	return sn
}
135564
func createSnapshot(filename string, nodes int, services []string) (err error) {
	log.Debug("create snapshot", "filename", filename, "nodes", nodes, "services", services)

	sim := simulation.New(map[string]simulation.ServiceFunc{
		"bzz": func(ctx *adapters.ServiceContext, bucket *sync.Map) (node.Service, func(), error) {
			addr := network.NewAddr(ctx.Config.Node())
			kad := network.NewKademlia(addr.Over(), network.NewKadParams())
			hp := network.NewHiveParams()
			hp.KeepAliveInterval = time.Duration(200) * time.Millisecond
			hp.Discovery = true // discovery must be enabled when creating a snapshot

			// store the kademlia in the bucket, needed later in the WaitTillHealthy function
			bucket.Store(simulation.BucketKeyKademlia, kad)

			config := &network.BzzConfig{
				OverlayAddr:  addr.Over(),
				UnderlayAddr: addr.Under(),
				HiveParams:   hp,
			}
			return network.NewBzz(config, kad, nil, nil, nil), nil, nil
		},
	})
	defer sim.Close()

	ids, err := sim.AddNodes(nodes)
	if err != nil {
		return fmt.Errorf("add nodes: %v", err)
	}

	err = sim.Net.ConnectNodesRing(ids)
	if err != nil {
		return fmt.Errorf("connect nodes: %v", err)
	}

	ctx, cancelSimRun := context.WithTimeout(context.Background(), 3*time.Minute)
	defer cancelSimRun()
	if _, err := sim.WaitTillHealthy(ctx); err != nil {
		return fmt.Errorf("wait for healthy kademlia: %v", err)
	}

	var snap *simulations.Snapshot
	if len(services) > 0 {
		// If service names are provided, include them in the snapshot.
		// But, check if "bzz" service is not among them to remove it
		// form the snapshot as it exists on snapshot creation.
		var removeServices []string
		var wantBzz bool
		for _, s := range services {
			if s == "bzz" {
				wantBzz = true
				break
			}
		}
		if !wantBzz {
			removeServices = []string{"bzz"}
		}
		snap, err = sim.Net.SnapshotWithServices(services, removeServices)
	} else {
		snap, err = sim.Net.Snapshot()
	}
	if err != nil {
		return fmt.Errorf("create snapshot: %v", err)
	}
	jsonsnapshot, err := json.Marshal(snap)
	if err != nil {
		return fmt.Errorf("json encode snapshot: %v", err)
	}
	return ioutil.WriteFile(filename, jsonsnapshot, 0666)
}
248162
func (kvm *Clone) Snapshot(wr io.Writer) error {
	kvm.mu.RLock()
	defer kvm.mu.RUnlock()
	data, err := json.Marshal(kvm.keys)
	if err != nil {
		return err
	}
	if _, err := wr.Write(data); err != nil {
		return err
	}
	return nil
}
810611
func (db *MemDB) Snapshot() *MemDB {
	clone := &MemDB{
		schema:  db.schema,
		root:    unsafe.Pointer(db.getRoot()),
		primary: false,
	}
	return clone
}
295357
func (_m *API) GetSnapshots() ([]dao.SnapshotInfo, error) {
	ret := _m.Called()

	var r0 []dao.SnapshotInfo
	if rf, ok := ret.Get(0).(func() []dao.SnapshotInfo); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]dao.SnapshotInfo)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func() error); ok {
		r1 = rf()
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
553327
func (fsm *SimpleFSM) Snapshot() (raft.FSMSnapshot, error) {
	fsm.mu.Lock()
	defer fsm.mu.Unlock()
	copied := make([][]byte, len(fsm.logs))
	copy(copied, fsm.logs)
	return &SimpleSnapshot{copied, len(copied)}, nil
}
1317203
func (f *Facade) Snapshot(ctx datastore.Context, serviceID, message string, tags []string, snapshotSpacePercent int) (string, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.Snapshot"))
	// Do not DFSLock here, ControlPlaneDao does that

	logger := plog.WithFields(logrus.Fields{
		"serviceid": serviceID,
	})

	tenantID, err := f.GetTenantID(ctx, serviceID)
	if err != nil {
		logger.WithError(err).Debug("Could not get tenant id of service")
		return "", err
	}
	logger = logger.WithField("tenantid", tenantID)
	if err := f.lockTenant(ctx, tenantID); err != nil {
		logger.WithError(err).Debug("Could not lock tenant")
		return "", err
	}
	defer f.retryUnlockTenant(ctx, tenantID, nil, time.Second)
	logger.Info("Got tenant lock")
	svcs, err := f.GetServices(ctx, dao.ServiceRequest{TenantID: tenantID})
	if err != nil {
		logger.WithError(err).Debug("Could not get services under tenant")
		return "", err
	}
	imagesMap := make(map[string]struct{})
	images := make([]string, 0)
	serviceids := []string{}
	servicesToPause := []*service.Service{}
	poolmap := make(map[string]bool)
	var pausedServiceIds []string
	for i, _ := range svcs {
		svc := &svcs[i]

		// only pause services that have access to the dfs
		hasDFS, ok := poolmap[svc.PoolID]
		if !ok {
			p := &pool.ResourcePool{}
			err := f.poolStore.Get(ctx, pool.Key(svc.PoolID), p)
			if err != nil {
				logger.WithField("poolid", svc.PoolID).WithError(err).Error("Could not get resource pool")
				return "", err
			}
			hasDFS = p.HasDfsAccess()
			poolmap[svc.PoolID] = hasDFS
		}

		if hasDFS {
			if svc.DesiredState == int(service.SVCRun) {
				servicesToPause = append(servicesToPause, svc)
				pausedServiceIds = append(pausedServiceIds, svc.ID)
			}
			serviceids = append(serviceids, svc.ID)
		}

		if svc.ImageID != "" {
			if _, ok := imagesMap[svc.ImageID]; !ok {
				imagesMap[svc.ImageID] = struct{}{}
				images = append(images, svc.ImageID)
			}
		}
	}
	// Pause the services that need pausing in a batch
	if _, err := scheduleServices(f, servicesToPause, ctx, tenantID, service.SVCPause, false); err != nil {
		logger.WithError(err).Debug("Could not pause services for snapshot")
		return "", err
	}

	defer func() {
		// Refresh service objects in case something has changed (like current state)
		servicesToPause = f.GetServicesForScheduling(ctx, pausedServiceIds)
		scheduleServices(f, servicesToPause, ctx, tenantID, service.SVCRun, false)
	}()

	// Wait for the paused services to reach the paused state (and other services to reach stopped)
	if err := f.WaitService(ctx, service.SVCPause, f.dfs.Timeout(), false, serviceids...); err != nil {
		logger.WithError(err).Debug("Could not wait for services to pause during snapshot")
		return "", err
	}
	logger.Infof("Services are now paused for snapshot")
	data := dfs.SnapshotInfo{
		SnapshotInfo: &volume.SnapshotInfo{
			TenantID: tenantID,
			Message:  message,
			Tags:     tags,
		},
		Services: svcs,
		Images:   images,
	}
	snapshotID, err := f.dfs.Snapshot(data, snapshotSpacePercent)
	if err != nil {
		logger.WithError(err).Debug("Could not snapshot disk and images for tenant")
		return "", err
	}
	logger.WithField("snapshotid", snapshotID).Info("Successfully captured application data and created snapshot")
	return snapshotID, nil
}
163283
func (s *SnapshotGetService) Snapshot(snapshots ...string) *SnapshotGetService {
	s.snapshot = append(s.snapshot, snapshots...)
	return s
}
135460
func (c *ServicedCli) printSnapshotsFirst(ctx *cli.Context) {
	if len(ctx.Args()) > 0 {
		return
	}

	for _, s := range c.snapshots("") {
		fmt.Println(s)
	}
}
42170
func (p *PolicyAuthorizer) Snapshot() bool {
	if allow, recurse := enforce(p.aclRule, PolicyWrite); !recurse {
		return allow
	}
	return p.parent.Snapshot()
}
311702
func snapshots(srv *clonesrv_t) (err error) {

	msg, err := srv.snapshot.RecvMessage(0)
	if err != nil {
		return
	}
	identity := msg[0]

	//  Request is in second frame of message
	request := msg[1]
	if request != "ICANHAZ?" {
		err = errors.New("E: bad request, aborting")
		return
	}
	subtree := msg[2]

	//  Send state socket to client
	for _, kvmsg := range srv.kvmap {
		if key, _ := kvmsg.GetKey(); strings.HasPrefix(key, subtree) {
			srv.snapshot.Send(identity, zmq.SNDMORE)
			kvmsg.Send(srv.snapshot)
		}
	}

	//  Now send END message with sequence number
	log.Println("I: sending shapshot =", srv.sequence)
	srv.snapshot.Send(identity, zmq.SNDMORE)
	kvmsg := kvmsg.NewKvmsg(srv.sequence)
	kvmsg.SetKey("KTHXBAI")
	kvmsg.SetBody(subtree)
	kvmsg.Send(srv.snapshot)

	return
}