// shardRoot returns entity group key to use for a given shard.
191366
func (s *Set) shardRoot(c context.Context, n int) *datastore.Key {
	return datastore.NewKey(c, "dsset.Shard", fmt.Sprintf("%s:%d", s.ID, n), 0, nil)
}
808604
func (m ConcurrentMap) Upsert(key string, value interface{}, cb UpsertCb) (res interface{}) {
	shard := m.GetShard(key)
	shard.Lock()
	v, ok := shard.items[key]
	res = cb(ok, v, value)
	shard.items[key] = res
	shard.Unlock()
	return res
}
541442
func (ts *Server) UpdateShardReplicationFields(ctx context.Context, cell, keyspace, shard string, update func(*topodatapb.ShardReplication) error) error {
	nodePath := path.Join(KeyspacesPath, keyspace, ShardsPath, shard, ShardReplicationFile)

	conn, err := ts.ConnForCell(ctx, cell)
	if err != nil {
		return err
	}

	for {
		data, version, err := conn.Get(ctx, nodePath)
		sr := &topodatapb.ShardReplication{}
		switch {
		case IsErrType(err, NoNode):
			// Empty node, version is nil
		case err == nil:
			// Use any data we got.
			if err = proto.Unmarshal(data, sr); err != nil {
				return vterrors.Wrap(err, "bad ShardReplication data")
			}
		default:
			return err
		}

		err = update(sr)
		switch {
		case IsErrType(err, NoUpdateNeeded):
			return nil
		case err == nil:
			// keep going
		default:
			return err
		}

		// marshall and save
		data, err = proto.Marshal(sr)
		if err != nil {
			return err
		}
		if version == nil {
			// We have to create, and we catch NodeExists.
			_, err = conn.Create(ctx, nodePath, data)
			if IsErrType(err, NodeExists) {
				// Node was created by another process, try
				// again.
				continue
			}
			return err
		}

		// We have to update, and we catch ErrBadVersion.
		_, err = conn.Update(ctx, nodePath, data, version)
		if IsErrType(err, BadVersion) {
			// Node was updated by another process, try again.
			continue
		}
		return err
	}
}
713461
func CopyShards(ctx context.Context, fromTS, toTS *topo.Server) {
	keyspaces, err := fromTS.GetKeyspaces(ctx)
	if err != nil {
		log.Fatalf("fromTS.GetKeyspaces: %v", err)
	}

	for _, keyspace := range keyspaces {
		shards, err := fromTS.GetShardNames(ctx, keyspace)
		if err != nil {
			log.Fatalf("GetShardNames(%v): %v", keyspace, err)
			return
		}

		for _, shard := range shards {

			si, err := fromTS.GetShard(ctx, keyspace, shard)
			if err != nil {
				log.Fatalf("GetShard(%v, %v): %v", keyspace, shard, err)
			}

			if err := toTS.CreateShard(ctx, keyspace, shard); err != nil {
				if topo.IsErrType(err, topo.NodeExists) {
					log.Warningf("shard %v/%v already exists", keyspace, shard)
				} else {
					log.Fatalf("CreateShard(%v, %v): %v", keyspace, shard, err)
				}
			}
			if _, err := toTS.UpdateShardFields(ctx, keyspace, shard, func(toSI *topo.ShardInfo) error {
				*toSI.Shard = *si.Shard
				return nil
			}); err != nil {
				log.Fatalf("UpdateShardFields(%v, %v): %v", keyspace, shard, err)
			}
		}
	}
}
708614
func (c *ConsulProvider) GenerateRoot() error {
	idx, providerState, err := c.getState()
	if err != nil {
		return err
	}

	if !c.isRoot {
		return fmt.Errorf("provider is not the root certificate authority")
	}
	if providerState.RootCert != "" {
		return nil
	}

	// Generate a private key if needed
	newState := *providerState
	if c.config.PrivateKey == "" {
		_, pk, err := connect.GeneratePrivateKey()
		if err != nil {
			return err
		}
		newState.PrivateKey = pk
	} else {
		newState.PrivateKey = c.config.PrivateKey
	}

	// Generate the root CA if necessary
	if c.config.RootCert == "" {
		ca, err := c.generateCA(newState.PrivateKey, idx+1)
		if err != nil {
			return fmt.Errorf("error generating CA: %v", err)
		}
		newState.RootCert = ca
	} else {
		newState.RootCert = c.config.RootCert
	}

	// Write the provider state
	args := &structs.CARequest{
		Op:            structs.CAOpSetProviderState,
		ProviderState: &newState,
	}
	if err := c.Delegate.ApplyCARequest(args); err != nil {
		return err
	}

	return nil
}
1096308
func NewTreeRootNode(t *Tree) noder.Noder {
	if t == nil {
		return &treeNoder{}
	}

	return &treeNoder{
		parent: t,
		name:   "",
		mode:   filemode.Dir,
		hash:   t.Hash,
	}
}
670005
func (b *Browser) Chroot(p string) (newFS billy.Filesystem, err error) {
	if b.tree == nil {
		return nil, errors.New("Empty repo")
	}

	defer translateGitError(&err)
	newTree, err := b.tree.Tree(p)
	if err != nil {
		return nil, err
	}
	return &Browser{
		tree:        newTree,
		root:        b.Join(b.root, p),
		mtime:       b.mtime,
		commitHash:  b.commitHash,
		sharedCache: b.sharedCache,
	}, nil
}
495630
func (s *EnablePolicyTypeOutput) SetRoot(v *Root) *EnablePolicyTypeOutput {
	s.Root = v
	return s
}
176350
func (c *Client) HelpRoot() (string, error) {
	if err := c.condDiscovery(); err != nil {
		return "", err
	}
	if c.helpRoot == "" {
		return "", ErrNoHelpRoot
	}
	return c.helpRoot, nil
}
1134854
func (ts *Server) GetOrCreateShard(ctx context.Context, keyspace, shard string) (si *ShardInfo, err error) {
	si, err = ts.GetShard(ctx, keyspace, shard)
	if !IsErrType(err, NoNode) {
		return
	}

	// create the keyspace, maybe it already exists
	if err = ts.CreateKeyspace(ctx, keyspace, &topodatapb.Keyspace{}); err != nil && !IsErrType(err, NodeExists) {
		return nil, vterrors.Wrapf(err, "CreateKeyspace(%v) failed", keyspace)
	}

	// now try to create with the lock, may already exist
	if err = ts.CreateShard(ctx, keyspace, shard); err != nil && !IsErrType(err, NodeExists) {
		return nil, vterrors.Wrapf(err, "CreateShard(%v/%v) failed", keyspace, shard)
	}

	// try to read the shard again, maybe someone created it
	// in between the original GetShard and the LockKeyspace
	return ts.GetShard(ctx, keyspace, shard)
}
966595
func (f *Finder) findRoot(ctx context.Context, root *list.Element, parts []string) bool {
	if len(parts) == 0 {
		return false
	}

	ix := len(parts) - 1

	if parts[ix] != "..." {
		return false
	}

	if ix == 0 {
		return true // We already have the Object for root.Path
	}

	// Lookup the Object for the new root.Path
	rootPath := path.Join(root.Path, path.Join(parts[:ix]...))

	ref, err := f.si.FindByInventoryPath(ctx, rootPath)
	if err != nil || ref == nil {
		// If we get an error or fail to match, fall through to find() with the original root and path
		return false
	}

	root.Path = rootPath
	root.Object = ref

	return true
}
1301716
func (k KeybaseServiceMeasured) VerifyMerkleRoot(
	ctx context.Context, root keybase1.MerkleRootV2,
	kbfsRoot keybase1.KBFSRoot) (err error) {
	k.verifyMerkleRootTimer.Time(func() {
		err = k.delegate.VerifyMerkleRoot(ctx, root, kbfsRoot)
	})
	return err
}
1354781
func setRoot(root *Root, str string) error {
	switch {
	case strings.HasPrefix(str, privatePrefix):
		root.TlfType = tlf.Private
		setRootTlfNameAndPath(root, str[len(privatePrefix):])
		return nil
	case strings.HasPrefix(str, publicPrefix):
		root.TlfType = tlf.Public
		setRootTlfNameAndPath(root, str[len(publicPrefix):])
		return nil
	case strings.HasPrefix(str, teamPrefix):
		root.TlfType = tlf.SingleTeam
		setRootTlfNameAndPath(root, str[len(teamPrefix):])
		return nil
	default:
		return ErrInvalidKeybasePagesRecord{}
	}
}
229027
func (tr *Repo) InitRoot(root, timestamp, snapshot, targets data.BaseRole, consistent bool) error {
	rootRoles := make(map[data.RoleName]*data.RootRole)
	rootKeys := make(map[string]data.PublicKey)

	for _, r := range []data.BaseRole{root, timestamp, snapshot, targets} {
		rootRoles[r.Name] = &data.RootRole{
			Threshold: r.Threshold,
			KeyIDs:    r.ListKeyIDs(),
		}
		for kid, k := range r.Keys {
			rootKeys[kid] = k
		}
	}
	r, err := data.NewRoot(rootKeys, rootRoles, consistent)
	if err != nil {
		return err
	}
	tr.Root = r
	tr.originalRootRole = root
	return nil
}
1311514
func (m *BaseShardManager) GetShardsForSentinelsFromKeys(
	keys []string) map[int]*ShardMapping {

	m.rwMutex.RLock()
	defer m.rwMutex.RUnlock()

	return m.getShardsForSentinelsLocked(keys)
}
1226293
func (m *MemEngine) LookupRoot(_ context.Context) (Hash, error) {
	return m.root, nil
}
448385
func (s *shard) Evict() {
	key := -1

	s.RLock()
	for k := range s.items {
		key = int(k)
		break
	}
	s.RUnlock()

	if key == -1 {
		// empty cache
		return
	}

	// If this item is gone between the RUnlock and Lock race we don't care.
	s.Remove(uint32(key))
}