// resolveTokenFromSnapshotCache is used to resolve an ACL object from a snapshot of state,
// using a cache to avoid parsing and ACL construction when possible. It is split from resolveToken
// to simplify testing.
497293
func resolveTokenFromSnapshotCache(snap *state.StateSnapshot, cache *lru.TwoQueueCache, secretID string) (*acl.ACL, error) {
	// Lookup the ACL Token
	var token *structs.ACLToken
	var err error

	// Handle anonymous requests
	if secretID == "" {
		token = structs.AnonymousACLToken
	} else {
		token, err = snap.ACLTokenBySecretID(nil, secretID)
		if err != nil {
			return nil, err
		}
		if token == nil {
			return nil, structs.ErrTokenNotFound
		}
	}

	// Check if this is a management token
	if token.Type == structs.ACLManagementToken {
		return acl.ManagementACL, nil
	}

	// Get all associated policies
	policies := make([]*structs.ACLPolicy, 0, len(token.Policies))
	for _, policyName := range token.Policies {
		policy, err := snap.ACLPolicyByName(nil, policyName)
		if err != nil {
			return nil, err
		}
		if policy == nil {
			// Ignore policies that don't exist, since they don't grant any more privilege
			continue
		}

		// Save the policy and update the cache key
		policies = append(policies, policy)
	}

	// Compile and cache the ACL object
	aclObj, err := structs.CompileACLObject(cache, policies)
	if err != nil {
		return nil, err
	}
	return aclObj, nil
}
1075457
func (f *FastTeamChainLoader) findStateInCache(m libkb.MetaContext, id keybase1.TeamID) *keybase1.FastTeamData {
	tmp := f.storage.Get(m, id, id.IsPublic())
	if tmp == nil {
		return nil
	}
	return tmp
}
1168931
func (a *LBClient) AckProxySnapshotQuiece(snapshotId string, unused *interface{}) error {
	glog.V(4).Infof("ControlCenterAgent.AckProxySnapshotQuiece()")
	return a.rpcClient.Call("ControlCenterAgent.AckProxySnapshotQuiece", snapshotId, unused, 0)
}
170219
func (s *Server) handleSnapshotRequest(conn net.Conn) error {
	var args structs.SnapshotRequest
	dec := codec.NewDecoder(conn, &codec.MsgpackHandle{})
	if err := dec.Decode(&args); err != nil {
		return fmt.Errorf("failed to decode request: %v", err)
	}

	var reply structs.SnapshotResponse
	snap, err := s.dispatchSnapshotRequest(&args, conn, &reply)
	if err != nil {
		reply.Error = err.Error()
		goto RESPOND
	}
	defer func() {
		if err := snap.Close(); err != nil {
			s.logger.Printf("[ERR] consul: Failed to close snapshot: %v", err)
		}
	}()

RESPOND:
	enc := codec.NewEncoder(conn, &codec.MsgpackHandle{})
	if err := enc.Encode(&reply); err != nil {
		return fmt.Errorf("failed to encode response: %v", err)
	}
	if snap != nil {
		if _, err := io.Copy(conn, snap); err != nil {
			return fmt.Errorf("failed to stream snapshot: %v", err)
		}
	}

	return nil
}
852980
func (a *HostAgent) AckProxySnapshotQuiece(snapshotId string, unused *interface{}) error {
	glog.Errorf("AckProxySnapshotQuiece() Unimplemented")
	return errors.New("unimplemented")
}
410748
func endpointsFromSnapshot(cfgSnap *proxycfg.ConfigSnapshot, token string) ([]proto.Message, error) {
	if cfgSnap == nil {
		return nil, errors.New("nil config given")
	}
	resources := make([]proto.Message, 0, len(cfgSnap.UpstreamEndpoints))
	for id, endpoints := range cfgSnap.UpstreamEndpoints {
		la := makeLoadAssignment(id, endpoints)
		resources = append(resources, la)
	}
	return resources, nil
}
365367
func (_m *API) AddSnapshot(_a0 api.SnapshotConfig) (string, error) {
	ret := _m.Called(_a0)

	var r0 string
	if rf, ok := ret.Get(0).(func(api.SnapshotConfig) string); ok {
		r0 = rf(_a0)
	} else {
		r0 = ret.Get(0).(string)
	}

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

	return r0, r1
}
232612
func (c *Client) LoadSnapshot(snap *Snapshot) error {
	return c.Post("/snapshot", snap, nil)
}
1189667
func (v VirtualMachine) FindSnapshot(ctx context.Context, name string) (*types.ManagedObjectReference, error) {
	var o mo.VirtualMachine

	err := v.Properties(ctx, v.Reference(), []string{"snapshot"}, &o)
	if err != nil {
		return nil, err
	}

	if o.Snapshot == nil || len(o.Snapshot.RootSnapshotList) == 0 {
		return nil, errors.New("no snapshots for this VM")
	}

	m := make(snapshotMap)
	m.add("", o.Snapshot.RootSnapshotList)

	s := m[name]
	switch len(s) {
	case 0:
		return nil, fmt.Errorf("snapshot %q not found", name)
	case 1:
		return &s[0], nil
	default:
		return nil, fmt.Errorf("%q resolves to %d snapshots", name, len(s))
	}
}
232410
func (d *domainClient) LoadSnapshot(ctx context.Context, args *LoadSnapshotArgs) (reply *LoadSnapshotReply, err error) {
	reply = new(LoadSnapshotReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "LayerTree.loadSnapshot", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "LayerTree.loadSnapshot", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "LayerTree", Op: "LoadSnapshot", Err: err}
	}
	return
}
534477
func GetTokenFromHOTPMockFile(path string) (token string, e error) {
	otp, err := LoadHOTPMockFromFile(path)
	if err != nil {
		return "", trace.Wrap(err)
	}

	token = otp.OTP()

	err = otp.SaveToFile(path)
	if err != nil {
		return "", trace.Wrap(err)
	}

	return token, nil
}
819490
func GetSnapshot(name string) (*Snapshot, error) {
	if !SnapshotExists(name) {
		return nil, fmt.Errorf("Snapshot not found")
	}
	return &Snapshot{
		Name: name,
	}, nil
}
1192856
func (s *Server) listenersFromSnapshot(cfgSnap *proxycfg.ConfigSnapshot, token string) ([]proto.Message, error) {
	if cfgSnap == nil {
		return nil, errors.New("nil config given")
	}

	// One listener for each upstream plus the public one
	resources := make([]proto.Message, len(cfgSnap.Proxy.Upstreams)+1)

	// Configure public listener
	var err error
	resources[0], err = s.makePublicListener(cfgSnap, token)
	if err != nil {
		return nil, err
	}
	for i, u := range cfgSnap.Proxy.Upstreams {
		resources[i+1], err = s.makeUpstreamListener(&u)
		if err != nil {
			return nil, err
		}
	}
	return resources, nil
}
71592
func (c *LeaseCache) RegisterAutoAuthToken(token string) error {
	// Get the token from the cache
	oldIndex, err := c.db.Get(cachememdb.IndexNameToken, token)
	if err != nil {
		return err
	}

	// If the index is found, defer its cancelFunc
	if oldIndex != nil {
		defer oldIndex.RenewCtxInfo.CancelFunc()
	}

	// The following randomly generated values are required for index stored by
	// the cache, but are not actually used. We use random values to prevent
	// accidental access.
	id, err := base62.Random(5)
	if err != nil {
		return err
	}
	namespace, err := base62.Random(5)
	if err != nil {
		return err
	}
	requestPath, err := base62.Random(5)
	if err != nil {
		return err
	}

	index := &cachememdb.Index{
		ID:          id,
		Token:       token,
		Namespace:   namespace,
		RequestPath: requestPath,
	}

	// Derive a context off of the lease cache's base context
	ctxInfo := c.createCtxInfo(nil)

	index.RenewCtxInfo = &cachememdb.ContextInfo{
		Ctx:        ctxInfo.Ctx,
		CancelFunc: ctxInfo.CancelFunc,
		DoneCh:     ctxInfo.DoneCh,
	}

	// Store the index in the cache
	c.logger.Debug("storing auto-auth token into the cache")
	err = c.db.Set(index)
	if err != nil {
		c.logger.Error("failed to cache the auto-auth token", "error", err)
		return err
	}

	return nil
}
767204
func (c *Cache) ClearSnapshot(success bool) {
	c.mu.RLock()
	snapStore := c.snapshot.store
	c.mu.RUnlock()

	// reset the snapshot store outside of the write lock
	if success {
		snapStore.reset()
	}

	c.mu.Lock()
	defer c.mu.Unlock()

	c.snapshotting = false

	if success {
		snapshotSize := c.tracker.SnapshotSize()
		c.tracker.SetSnapshotsActive(0)
		c.tracker.SubMemBytes(snapshotSize) // decrement the number of bytes in cache

		// Reset the snapshot to a fresh Cache.
		c.snapshot = &Cache{
			store:   c.snapshot.store,
			tracker: newCacheTracker(c.tracker.metrics, c.tracker.labels),
		}

		c.tracker.SetSnapshotSize(0)
		c.tracker.SetDiskBytes(0)
		c.tracker.SetSnapshotsActive(0)
	}
}
1170214
func (_m *API) GetSnapshotByServiceIDAndTag(_a0 string, _a1 string) (string, error) {
	ret := _m.Called(_a0, _a1)

	var r0 string
	if rf, ok := ret.Get(0).(func(string, string) string); ok {
		r0 = rf(_a0, _a1)
	} else {
		r0 = ret.Get(0).(string)
	}

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

	return r0, r1
}
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))
}