// Snapshot returns connection statistics' snapshot.
//
// Use stats returned from ConnStats.Snapshot() on live Client and / or Server,
// since the original stats can be updated by concurrently running goroutines.
503125
func (cs *ConnStats) Snapshot() *ConnStats {
	cs.lock.Lock()
	snapshot := *cs
	cs.lock.Unlock()

	snapshot.lock = sync.Mutex{}
	return &snapshot
}
651198
func (self *StateDB) Snapshot() int {
	id := self.nextRevisionId
	self.nextRevisionId++
	self.validRevisions = append(self.validRevisions, revision{id, self.journal.length()})
	return id
}
42170
func (p *PolicyAuthorizer) Snapshot() bool {
	if allow, recurse := enforce(p.aclRule, PolicyWrite); !recurse {
		return allow
	}
	return p.parent.Snapshot()
}
1237245
func (client *Client) DeleteSnapshot(snapshotId string) error {
	args := DeleteSnapshotArgs{SnapshotId: snapshotId}
	response := DeleteSnapshotResponse{}

	return client.Invoke("DeleteSnapshot", &args, &response)
}
1165361
func fetchSnapshot(c context.Context, info *SnapshotInfo) error {
	srv := getAuthService(c, info.AuthServiceURL)
	snap, err := srv.GetSnapshot(c, info.Rev)
	if err != nil {
		return err
	}
	blob, err := service.DeflateAuthDB(snap.AuthDB)
	if err != nil {
		return err
	}
	ent := Snapshot{
		ID:             info.GetSnapshotID(),
		AuthDBDeflated: blob,
		CreatedAt:      snap.Created.UTC(),
		FetchedAt:      clock.Now(c).UTC(),
	}
	logging.Infof(c, "Lag: %s", ent.FetchedAt.Sub(ent.CreatedAt))
	return transient.Tag.Apply(ds.Put(ds.WithoutTransaction(c), &ent))
}
683005
func (v *NFSVolume) Snapshot(label, message string, tags []string) (err error) {
	return ErrNotSupported
}
705587
func (c *Cache) Snapshot() (*Cache, error) {
	c.mu.Lock()
	defer c.mu.Unlock()

	if c.snapshotting {
		return nil, ErrSnapshotInProgress
	}

	c.snapshotting = true
	c.tracker.IncSnapshotsActive() // increment the number of times we tried to do this

	// If no snapshot exists, create a new one, otherwise update the existing snapshot
	if c.snapshot == nil {
		c.snapshot = &Cache{
			store:   newRing(),
			tracker: newCacheTracker(c.tracker.metrics, c.tracker.labels),
		}
	}

	// Did a prior snapshot exist that failed?  If so, return the existing
	// snapshot to retry.
	if c.snapshot.Size() > 0 {
		return c.snapshot, nil
	}

	c.snapshot.store, c.store = c.store, c.snapshot.store
	snapshotSize := c.Size()

	c.snapshot.tracker.SetSnapshotSize(snapshotSize) // Save the size of the snapshot on the snapshot cache
	c.tracker.SetSnapshotSize(snapshotSize)          // Save the size of the snapshot on the live cache

	// Reset the cache's store.
	c.store.reset()
	c.tracker.SetCacheSize(0)
	c.lastSnapshot = time.Now()

	c.tracker.AddSnapshottedBytes(snapshotSize) // increment the number of bytes added to the snapshot
	c.tracker.SetDiskBytes(0)
	c.tracker.SetSnapshotsActive(0)

	return c.snapshot, nil
}
1027419
func (net *Network) Load(snap *Snapshot) error {
	// Start nodes.
	for _, n := range snap.Nodes {
		if _, err := net.NewNodeWithConfig(n.Node.Config); err != nil {
			return err
		}
		if !n.Node.Up() {
			continue
		}
		if err := net.startWithSnapshots(n.Node.Config.ID, n.Snapshots); err != nil {
			return err
		}
	}

	// Prepare connection events counter.
	allConnected := make(chan struct{}) // closed when all connections are established
	done := make(chan struct{})         // ensures that the event loop goroutine is terminated
	defer close(done)

	// Subscribe to event channel.
	// It needs to be done outside of the event loop goroutine (created below)
	// to ensure that the event channel is blocking before connect calls are made.
	events := make(chan *Event)
	sub := net.Events().Subscribe(events)
	defer sub.Unsubscribe()

	go func() {
		// Expected number of connections.
		total := len(snap.Conns)
		// Set of all established connections from the snapshot, not other connections.
		// Key array element 0 is the connection One field value, and element 1 connection Other field.
		connections := make(map[[2]enode.ID]struct{}, total)

		for {
			select {
			case e := <-events:
				// Ignore control events as they do not represent
				// connect or disconnect (Up) state change.
				if e.Control {
					continue
				}
				// Detect only connection events.
				if e.Type != EventTypeConn {
					continue
				}
				connection := [2]enode.ID{e.Conn.One, e.Conn.Other}
				// Nodes are still not connected or have been disconnected.
				if !e.Conn.Up {
					// Delete the connection from the set of established connections.
					// This will prevent false positive in case disconnections happen.
					delete(connections, connection)
					log.Warn("load snapshot: unexpected disconnection", "one", e.Conn.One, "other", e.Conn.Other)
					continue
				}
				// Check that the connection is from the snapshot.
				for _, conn := range snap.Conns {
					if conn.One == e.Conn.One && conn.Other == e.Conn.Other {
						// Add the connection to the set of established connections.
						connections[connection] = struct{}{}
						if len(connections) == total {
							// Signal that all nodes are connected.
							close(allConnected)
							return
						}

						break
					}
				}
			case <-done:
				// Load function returned, terminate this goroutine.
				return
			}
		}
	}()

	// Start connecting.
	for _, conn := range snap.Conns {

		if !net.GetNode(conn.One).Up() || !net.GetNode(conn.Other).Up() {
			//in this case, at least one of the nodes of a connection is not up,
			//so it would result in the snapshot `Load` to fail
			continue
		}
		if err := net.Connect(conn.One, conn.Other); err != nil {
			return err
		}
	}

	select {
	// Wait until all connections from the snapshot are established.
	case <-allConnected:
	// Make sure that we do not wait forever.
	case <-time.After(snapshotLoadTimeout):
		return errors.New("snapshot connections not established")
	}
	return nil
}
835958
func (s *Server) handleSnapshotConn(conn net.Conn) {
	go func() {
		defer conn.Close()
		if err := s.handleSnapshotRequest(conn); err != nil {
			s.logger.Printf("[ERR] consul.rpc: Snapshot RPC error: %v %s", err, logConn(conn))
		}
	}()
}
1201159
func (mc *Connection) Stats(argument string) (result []byte, err error) {
	defer handleError(&err)
	mc.setDeadline()
	if argument == "" {
		mc.writestrings("stats\r\n")
	} else {
		mc.writestrings("stats ", argument, "\r\n")
	}
	mc.flush()
	for {
		l := mc.readline()
		if strings.HasPrefix(l, "END") {
			break
		}
		if strings.Contains(l, "ERROR") {
			return nil, NewError(l)
		}
		result = append(result, l...)
		result = append(result, '\n')
	}
	return result, err
}
389233
func (r *Registry) Snapshot() map[string]interface{} {
	r.m.Lock()
	defer r.m.Unlock()
	instruments := r.instruments
	r.instruments = make(map[string]interface{})
	return instruments
}
974491
func (r *PortAllocator) Snapshot(dst *api.RangeAllocation) error {
	snapshottable, ok := r.alloc.(allocator.Snapshottable)
	if !ok {
		return fmt.Errorf("not a snapshottable allocator")
	}
	rangeString, data := snapshottable.Snapshot()
	dst.Range = rangeString
	dst.Data = data
	return nil
}
1186192
func (p *peer) ChannelSnapshots() []*channeldb.ChannelSnapshot {
	p.activeChanMtx.RLock()
	defer p.activeChanMtx.RUnlock()

	snapshots := make([]*channeldb.ChannelSnapshot, 0, len(p.activeChannels))
	for _, activeChan := range p.activeChannels {
		// We'll only return a snapshot for channels that are
		// *immedately* available for routing payments over.
		if activeChan.RemoteNextRevocation() == nil {
			continue
		}

		snapshot := activeChan.StateSnapshot()
		snapshots = append(snapshots, snapshot)
	}

	return snapshots
}
1305134
func (s *UniformSample) Snapshot() Sample {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	values := make([]int64, len(s.values))
	copy(values, s.values)
	return &SampleSnapshot{
		count:  s.count,
		values: values,
	}
}
1300998
func (db *DB) Snapshot(dir string, withHead bool) error {
	if dir == db.dir {
		return errors.Errorf("cannot snapshot into base directory")
	}
	if _, err := ulid.ParseStrict(dir); err == nil {
		return errors.Errorf("dir must not be a valid ULID")
	}

	db.cmtx.Lock()
	defer db.cmtx.Unlock()

	db.mtx.RLock()
	defer db.mtx.RUnlock()

	for _, b := range db.blocks {
		level.Info(db.logger).Log("msg", "snapshotting block", "block", b)

		if err := b.Snapshot(dir); err != nil {
			return errors.Wrapf(err, "error snapshotting block: %s", b.Dir())
		}
	}
	if !withHead {
		return nil
	}
	_, err := db.compactor.Write(dir, db.head, db.head.MinTime(), db.head.MaxTime(), nil)
	return errors.Wrap(err, "snapshot head block")
}
1104550
func (s *Store) Snapshot() *Snapshot {
	tx := s.db.Txn(false)

	var tables []string
	for table := range s.schema.Tables {
		tables = append(tables, table)
	}
	idx := maxIndexTxn(tx, tables...)

	return &Snapshot{s, tx, idx}
}
1141108
func (dfs *DistributedFilesystem) Snapshot(data SnapshotInfo, spaceFactor int) (string, error) {
	label := generateSnapshotLabel()
	vol, err := dfs.disk.Get(data.TenantID)

	if volume.DriverTypeDeviceMapper == dfs.disk.DriverType() {
		freeSpace, err := ensureFreeSpace(vol, dfs, spaceFactor)
		if err != nil {
			glog.Errorf("Could not determine freespace on devicemapper device %s", err)
			return "", err
		}
		if !freeSpace {
			return "", errors.New("There is not enough diskspace to complete your request. You should enlarge your thin pool using LVM tools and/or delete some snapshots")
		}
	}
	if err != nil {
		glog.Errorf("Could not get volume for tenant %s: %s", data.TenantID, err)
		return "", err
	}
	// relabel all registry tags for this snapshot
	images := make([]string, len(data.Images))
	for i, image := range data.Images {
		rImage, err := dfs.index.FindImage(image)
		if err != nil {
			glog.Errorf("Could not find image %s for snapshot: %s", image, err)
			return "", err
		}

		// make sure we actually have the image locally before changing the tag and triggering a push
		if _, err := dfs.reg.FindImage(rImage); err != nil {
			glog.Errorf("Could not find image %s locally for snapshot:  %s", rImage.String(), err)
			return "", err
		}

		rImage.Tag = label
		if err := dfs.index.PushImage(rImage.String(), rImage.UUID, rImage.Hash); err != nil {
			glog.Errorf("Could not retag image %s for snapshot: %s", image, err)
			return "", err
		}
		fullImagePath, err := dfs.reg.ImagePath(rImage.String())
		if err != nil {
			glog.Errorf("Could not get the full image path for image %s: %s", image, err)
			return "", err
		}
		images[i] = fullImagePath
	}
	// write snapshot metadata
	w, err := vol.WriteMetadata(label, ImagesMetadataFile)
	if err != nil {
		glog.Errorf("Could not create image metadata file for tenant %s: %s", data.TenantID, err)
		return "", err
	}
	if err := exportJSON(w, images); err != nil {
		glog.Errorf("Could not write service metadata file for tenant %s: %s", data.TenantID, err)
		return "", err
	}
	w, err = vol.WriteMetadata(label, ServicesMetadataFile)
	if err != nil {
		glog.Errorf("Could not create service metadata file for tenant %s: %s", data.TenantID, err)
		return "", err
	}
	if err := exportJSON(w, data.Services); err != nil {
		glog.Errorf("Could not write service metadata file for tenant %s: %s", data.TenantID, err)
		return "", err
	}
	// snapshot the volume
	if err := vol.Snapshot(label, data.Message, data.Tags); err != nil {
		glog.Errorf("Could not snapshot volume for tenant %s: %s", data.TenantID, err)
		return "", err
	}
	info, err := vol.SnapshotInfo(label)
	if err != nil {
		glog.Errorf("Could not get info for snapshot %s of tenant %s: %s", label, data.TenantID, err)
		return "", err
	}
	return info.Name, nil
}