// GetTeamSettings implements the KeybaseService interface for
// KeybaseServiceMeasured.
760797
func (k KeybaseServiceMeasured) GetTeamSettings(
	ctx context.Context, teamID keybase1.TeamID,
	offline keybase1.OfflineAvailability) (
	settings keybase1.KBFSTeamSettings, err error) {
	k.getTeamSettingsTimer.Time(func() {
		settings, err = k.delegate.GetTeamSettings(ctx, teamID, offline)
	})
	return settings, err
}
347932
func (s *State) checkSettings(c context.Context) (*tsmon.State, *tsmonSettings) {
	state := tsmon.GetState(c)

	var settings tsmonSettings
	if s.testingSettings != nil {
		settings = *s.testingSettings
	} else {
		settings = fetchCachedSettings(c)
	}

	// Read the values used when handling previous request. In most cases they
	// are identical to current ones and we can skip grabbing a heavier write
	// lock.
	s.lock.RLock()
	if s.state == state && s.lastSettings == settings {
		s.lock.RUnlock()
		return state, &settings
	}
	s.lock.RUnlock()

	// 'settings' or 'state' has changed. Reinitialize tsmon as needed under
	// the write lock.
	s.lock.Lock()
	defer s.lock.Unlock()

	// First call to 'checkSettings' ever?
	if s.state == nil {
		s.state = state
		s.state.SetMonitor(monitor.NewNilMonitor()) // doFlush uses its own monitor
		s.state.InhibitGlobalCallbacksOnFlush()
	} else if state != s.state {
		panic("tsmon state in the context was unexpectedly changed between requests")
	}

	switch {
	case !bool(s.lastSettings.Enabled) && bool(settings.Enabled):
		s.enableTsMon(c)
	case bool(s.lastSettings.Enabled) && !bool(settings.Enabled):
		s.disableTsMon(c)
	}
	s.lastSettings = settings

	return state, &settings
}
1309107
func (s *Service) GetConfigSets() *GetConfigSetsCall {
	c := &GetConfigSetsCall{s: s, urlParams_: make(gensupport.URLParams)}
	return c
}
406357
func listSettings(backend modelBackend, collection, keyPrefix string) (map[string]map[string]interface{}, error) {
	col, closer := backend.db().GetRawCollection(collection)
	defer closer()

	var matchingSettings []settingsDoc
	findExpr := fmt.Sprintf("^%s.*$", backend.docID(keyPrefix))
	if err := col.Find(bson.D{{"_id", bson.D{{"$regex", findExpr}}}}).All(&matchingSettings); err != nil {
		return nil, err
	}
	result := make(map[string]map[string]interface{})
	for i := range matchingSettings {
		result[backend.localID(matchingSettings[i].DocID)] = matchingSettings[i].Settings
	}
	return result, nil
}
125746
func (u *Unit) ConfigSettings() (charm.Settings, error) {
	var results params.ConfigSettingsResults
	args := params.Entities{
		Entities: []params.Entity{{Tag: u.tag.String()}},
	}
	err := u.st.facade.FacadeCall("ConfigSettings", args, &results)
	if err != nil {
		return nil, err
	}
	if len(results.Results) != 1 {
		return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
	}
	result := results.Results[0]
	if result.Error != nil {
		return nil, result.Error
	}
	return charm.Settings(result.Settings), nil
}
1095446
func (k *KeybaseServiceBase) LoadTeamPlusKeys(
	ctx context.Context, tid keybase1.TeamID, tlfType tlf.Type,
	desiredKeyGen kbfsmd.KeyGen, desiredUser keybase1.UserVersion,
	desiredKey kbfscrypto.VerifyingKey, desiredRole keybase1.TeamRole,
	offline keybase1.OfflineAvailability) (idutil.TeamInfo, error) {
	if !allowedLoadTeamRoles[desiredRole] {
		panic(fmt.Sprintf("Disallowed team role: %v", desiredRole))
	}

	cachedTeamInfo := k.getCachedTeamInfo(tid)
	if cachedTeamInfo.Name != kbname.NormalizedUsername("") {
		// If the cached team info doesn't satisfy our desires, don't
		// use it.
		satisfiesDesires := true
		if desiredKeyGen >= kbfsmd.FirstValidKeyGen {
			// If `desiredKeyGen` is at most as large as the keygen in
			// the cached latest team info, then our cached info
			// satisfies our desires.
			satisfiesDesires = desiredKeyGen <= cachedTeamInfo.LatestKeyGen
		}

		if satisfiesDesires && desiredUser.Uid.Exists() {
			// If the user is in the writer map, that satisfies none, reader
			// or writer desires.
			satisfiesDesires = cachedTeamInfo.Writers[desiredUser.Uid]
			if !satisfiesDesires {
				if desiredRole == keybase1.TeamRole_NONE ||
					desiredRole == keybase1.TeamRole_READER {
					// If the user isn't a writer, but the desired
					// role is a reader, we need to check the reader
					// map explicitly.
					satisfiesDesires = cachedTeamInfo.Readers[desiredUser.Uid]
				} else if !desiredKey.IsNil() {
					// If the desired role was at least a writer, but
					// the user isn't currently a writer, see if they
					// ever were.
					var err error
					cachedTeamInfo, err = k.getLastWriterInfo(
						ctx, cachedTeamInfo, tlfType, desiredUser.Uid,
						desiredKey)
					if err != nil {
						return idutil.TeamInfo{}, err
					}
					k.setCachedTeamInfo(tid, cachedTeamInfo)
				}
			}
		}

		if satisfiesDesires {
			return cachedTeamInfo, nil
		}
	}

	arg := keybase1.LoadTeamPlusApplicationKeysArg{
		Id:              tid,
		Application:     keybase1.TeamApplication_KBFS,
		IncludeKBFSKeys: true,
		Oa:              offline,
	}

	if desiredKeyGen >= kbfsmd.FirstValidKeyGen {
		arg.Refreshers.NeedApplicationsAtGenerationsWithKBFS =
			map[keybase1.PerTeamKeyGeneration][]keybase1.TeamApplication{
				keybase1.PerTeamKeyGeneration(desiredKeyGen): []keybase1.TeamApplication{
					keybase1.TeamApplication_KBFS,
				},
			}
	}

	if desiredUser.Uid.Exists() && desiredKey.IsNil() {
		arg.Refreshers.WantMembers = append(
			arg.Refreshers.WantMembers, desiredUser)
		arg.Refreshers.WantMembersRole = desiredRole
	}

	res, err := k.teamsClient.LoadTeamPlusApplicationKeys(ctx, arg)
	if err != nil {
		return idutil.TeamInfo{}, err
	}

	if tid != res.Id {
		return idutil.TeamInfo{}, fmt.Errorf(
			"TID doesn't match: %s vs %s", tid, res.Id)
	}

	info := idutil.TeamInfo{
		Name:      kbname.NormalizedUsername(res.Name),
		TID:       res.Id,
		CryptKeys: make(map[kbfsmd.KeyGen]kbfscrypto.TLFCryptKey),
		Writers:   make(map[keybase1.UID]bool),
		Readers:   make(map[keybase1.UID]bool),
	}
	for _, key := range res.ApplicationKeys {
		keyGen := kbfsmd.KeyGen(key.KeyGeneration)
		info.CryptKeys[keyGen] =
			kbfscrypto.MakeTLFCryptKey(key.Key)
		if keyGen > info.LatestKeyGen {
			info.LatestKeyGen = keyGen
		}
	}

	for _, user := range res.Writers {
		info.Writers[user.Uid] = true
	}
	for _, user := range res.OnlyReaders {
		info.Readers[user.Uid] = true
	}

	// For subteams, get the root team ID.
	if tid.IsSubTeam() {
		rootID, err := k.teamsClient.GetTeamRootID(ctx, tid)
		if err != nil {
			return idutil.TeamInfo{}, err
		}
		info.RootID = rootID
	}

	// Fill in `LastWriters`, only if needed.
	if desiredUser.Uid.Exists() && desiredRole == keybase1.TeamRole_WRITER &&
		!info.Writers[desiredUser.Uid] && !desiredKey.IsNil() {
		info, err = k.getLastWriterInfo(
			ctx, info, tlfType, desiredUser.Uid, desiredKey)
		if err != nil {
			return idutil.TeamInfo{}, err
		}
	}

	k.setCachedTeamInfo(tid, info)

	return info, nil
}
430368
func (w *relationUnitsWatcher) mergeSettings(changes *params.RelationUnitsChange, key string) error {
	var doc struct {
		TxnRevno int64 `bson:"txn-revno"`
		Version  int64 `bson:"version"`
	}
	if err := readSettingsDocInto(w.backend.db(), settingsC, key, &doc); err != nil {
		logger.Tracef("relationUnitsWatcher %q merging key %q (not found)", w.sw.prefix, key)
		return err
	}
	logger.Tracef("relationUnitsWatcher %q merging key %q revno: %d version: %d", w.sw.prefix, key, doc.TxnRevno, doc.Version)
	setRelationUnitChangeVersion(changes, key, doc.Version)
	return nil
}
462669
func (m MemSettings) ReadSettings(key string) (map[string]interface{}, error) {
	settings, ok := m.Settings[key]
	if !ok {
		return nil, errors.NotFoundf("settings with key %q", key)
	}
	return settings, nil
}
25495
func (api *RemoteRelationsAPI) RelationUnitSettings(relationUnits params.RelationUnits) (params.SettingsResults, error) {
	results := params.SettingsResults{
		Results: make([]params.SettingsResult, len(relationUnits.RelationUnits)),
	}
	one := func(ru params.RelationUnit) (params.Settings, error) {
		relationTag, err := names.ParseRelationTag(ru.Relation)
		if err != nil {
			return nil, errors.Trace(err)
		}
		rel, err := api.st.KeyRelation(relationTag.Id())
		if err != nil {
			return nil, errors.Trace(err)
		}
		unitTag, err := names.ParseUnitTag(ru.Unit)
		if err != nil {
			return nil, errors.Trace(err)
		}
		unit, err := rel.Unit(unitTag.Id())
		if err != nil {
			return nil, errors.Trace(err)
		}
		settings, err := unit.Settings()
		if err != nil {
			return nil, errors.Trace(err)
		}
		paramsSettings := make(params.Settings)
		for k, v := range settings {
			vString, ok := v.(string)
			if !ok {
				return nil, errors.Errorf(
					"invalid relation setting %q: expected string, got %T", k, v,
				)
			}
			paramsSettings[k] = vString
		}
		return paramsSettings, nil
	}
	for i, ru := range relationUnits.RelationUnits {
		settings, err := one(ru)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		results.Results[i].Settings = settings
	}
	return results, nil
}
659211
func (l *TeamLoader) MapTeamAncestors(ctx context.Context, f func(t keybase1.TeamSigChainState) error, teamID keybase1.TeamID, reason string, forceFullReloadOnceToAssert func(t keybase1.TeamSigChainState) bool) (err error) {
	me, err := l.world.getMe(ctx)
	if err != nil {
		return err
	}

	// Load the argument team
	team, err := l.load1(ctx, me, keybase1.LoadTeamArg{
		ID:      teamID,
		Public:  teamID.IsPublic(),
		StaleOK: true, // We only use immutable fields.
	})
	if err != nil {
		return err
	}
	teamChain := TeamSigChainState{inner: team.Chain}
	if !teamChain.IsSubteam() {
		return fmt.Errorf("cannot map over parents of a root team: %v", teamID)
	}
	return l.mapTeamAncestorsHelper(ctx, f, teamID, teamChain.GetParentID(), reason, forceFullReloadOnceToAssert)
}
1192192
func setPlayerSettings() {
	rows, err := db.DB.DB().Query("SELECT player_id, key, value FROM player_settings")
	if err != nil {
		logrus.Fatal(err)
	}
	for rows.Next() {
		var playerID uint
		var key, value string

		rows.Scan(&playerID, &key, &value)
		p, _ := player.GetPlayerByID(playerID)
		p.SetSetting(key, value)
	}

	db.DB.Exec("DROP TABLE player_settings")
}
691031
func (st *State) ReadSettings(collection, key string) (*Settings, error) {
	return readSettings(st.db(), collection, key)
}
914529
func (s *StateSettings) CreateSettings(key string, settings map[string]interface{}) error {
	_, err := createSettings(s.backend.db(), s.collection, key, settings)
	return err
}
157746
func (c KbfsClient) GetKBFSTeamSettings(ctx context.Context, __arg GetKBFSTeamSettingsArg) (res KBFSTeamSettings, err error) {
	err = c.Cli.Call(ctx, "keybase.1.kbfs.getKBFSTeamSettings", []interface{}{__arg}, &res)
	return
}
1086625
func GetSettings(c context.Context) *Settings {
	if s, ok := c.Value(contextKey(0)).(*Settings); ok && s != nil {
		return s
	}
	return nil
}
60008
func (api *CrossModelRelationsAPI) RelationUnitSettings(relationUnits params.RemoteRelationUnits) (params.SettingsResults, error) {
	results := params.SettingsResults{
		Results: make([]params.SettingsResult, len(relationUnits.RelationUnits)),
	}
	for i, arg := range relationUnits.RelationUnits {
		relationTag, err := api.st.GetRemoteEntity(arg.RelationToken)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		if err := api.checkMacaroonsForRelation(relationTag, arg.Macaroons); err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}

		ru := params.RelationUnit{
			Relation: relationTag.String(),
			Unit:     arg.Unit,
		}
		settings, err := commoncrossmodel.RelationUnitSettings(api.st, ru)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		results.Results[i].Settings = settings
	}
	return results, nil
}
1342720
func retrieveSysSettings(stmt string, db *sql.DB) (PGSettings, error) {
	rows, err := db.Query(stmt)
	if err != nil {
		return nil, err
	}

	defer closeRows(rows)

	settings := make(PGSettings)

	for rows.Next() {
		var name, setting, unit, shortDesc, source, sourceFile sql.NullString
		var sourceLine sql.NullInt64
		err = rows.Scan(&name, &setting, &unit, &shortDesc,
			&source, &sourceFile, &sourceLine)
		if err != nil {
			return nil, err
		}

		// If the source is "configuration file", but the file path is empty,
		// the connected postgres user does not have sufficient privileges.
		var line, file string
		if source.String == "configuration file" {
			// Shorten the source string.
			source.String = "conf file"
			if sourceFile.String == "" {
				file = "NO PERMISION"
			} else {
				file = sourceFile.String
				line = strconv.FormatInt(sourceLine.Int64, 10)
			}
		}

		settings[name.String] = PGSetting{
			Name:       name.String,
			Setting:    setting.String,
			Unit:       unit.String,
			ShortDesc:  shortDesc.String,
			Source:     source.String,
			SourceFile: file,
			SourceLine: line,
		}
	}

	return settings, nil
}