// checkSettings fetches tsmon settings and initializes, reinitializes or
// deinitializes tsmon, as needed.
//
// Returns current tsmon state and settings. Panics if the context is using
// unexpected tsmon state.
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
}
989090
func (u *UniterAPI) ConfigSettings(args params.Entities) (params.ConfigSettingsResults, error) {
	result := params.ConfigSettingsResults{
		Results: make([]params.ConfigSettingsResult, len(args.Entities)),
	}
	canAccess, err := u.accessUnit()
	if err != nil {
		return params.ConfigSettingsResults{}, err
	}
	for i, entity := range args.Entities {
		tag, err := names.ParseUnitTag(entity.Tag)
		if err != nil {
			result.Results[i].Error = common.ServerError(common.ErrPerm)
			continue
		}
		err = common.ErrPerm
		if canAccess(tag) {
			var unit *state.Unit
			unit, err = u.getUnit(tag)
			if err == nil {
				var settings charm.Settings
				settings, err = unit.ConfigSettings()
				if err == nil {
					result.Results[i].Settings = params.ConfigSettings(settings)
				}
			}
		}
		result.Results[i].Error = common.ServerError(err)
	}
	return result, 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
}
1027866
func (s *Settings) UseSettings(settings *Settings) {
	if settings.Token != "" {
		s.Token = settings.Token
	}
	if settings.ProjectId != "" {
		s.ProjectId = settings.ProjectId
	}
	if settings.Host != "" {
		s.Host = settings.Host
	}
	if settings.Scheme != "" {
		s.Scheme = settings.Scheme
	}
	if settings.ApiVersion != "" {
		s.ApiVersion = settings.ApiVersion
	}
	if settings.UserAgent != "" {
		s.UserAgent = settings.UserAgent
	}
	if settings.Port > 0 {
		s.Port = settings.Port
	}
}
756622
func (mgr *SettingsManager) SaveSettings(settings *ArgoCDSettings) error {
	err := mgr.ensureSynced(false)
	if err != nil {
		return err
	}

	// Upsert the config data
	argoCDCM, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(common.ArgoCDConfigMapName)
	createCM := false
	if err != nil {
		if !apierr.IsNotFound(err) {
			return err
		}
		argoCDCM = &apiv1.ConfigMap{
			ObjectMeta: metav1.ObjectMeta{
				Name: common.ArgoCDConfigMapName,
			},
		}
		createCM = true
	}
	if argoCDCM.Data == nil {
		argoCDCM.Data = make(map[string]string)
	}
	if settings.URL != "" {
		argoCDCM.Data[settingURLKey] = settings.URL
	} else {
		delete(argoCDCM.Data, settingURLKey)
	}
	if settings.DexConfig != "" {
		argoCDCM.Data[settingDexConfigKey] = settings.DexConfig
	} else {
		delete(argoCDCM.Data, settings.DexConfig)
	}
	if settings.OIDCConfigRAW != "" {
		argoCDCM.Data[settingsOIDCConfigKey] = settings.OIDCConfigRAW
	} else {
		delete(argoCDCM.Data, settingsOIDCConfigKey)
	}
	if len(settings.Repositories) > 0 {
		yamlStr, err := yaml.Marshal(settings.Repositories)
		if err != nil {
			return err
		}
		argoCDCM.Data[repositoriesKey] = string(yamlStr)
	} else {
		delete(argoCDCM.Data, repositoriesKey)
	}
	if len(settings.RepositoryCredentials) > 0 {
		yamlStr, err := yaml.Marshal(settings.RepositoryCredentials)
		if err != nil {
			return err
		}
		argoCDCM.Data[repositoryCredentialsKey] = string(yamlStr)
	} else {
		delete(argoCDCM.Data, repositoryCredentialsKey)
	}
	if settings.AppInstanceLabelKey != "" {
		argoCDCM.Data[settingsApplicationInstanceLabelKey] = settings.AppInstanceLabelKey
	} else {
		delete(argoCDCM.Data, settingsApplicationInstanceLabelKey)
	}

	if len(settings.ResourceOverrides) > 0 {
		yamlBytes, err := yaml.Marshal(settings.ResourceOverrides)
		if err != nil {
			return err
		}
		argoCDCM.Data[resourceCustomizationsKey] = string(yamlBytes)
	} else {
		delete(argoCDCM.Data, resourceCustomizationsKey)
	}

	if len(settings.ResourceInclusions) > 0 {
		yamlBytes, err := yaml.Marshal(settings.ResourceInclusions)
		if err != nil {
			return err
		}
		argoCDCM.Data[resourceInclusionsKey] = string(yamlBytes)
	} else {
		delete(argoCDCM.Data, resourceInclusionsKey)
	}

	if len(settings.ResourceExclusions) > 0 {
		yamlBytes, err := yaml.Marshal(settings.ResourceExclusions)
		if err != nil {
			return err
		}
		argoCDCM.Data[resourceExclusionsKey] = string(yamlBytes)
	} else {
		delete(argoCDCM.Data, resourceExclusionsKey)
	}

	if createCM {
		_, err = mgr.clientset.CoreV1().ConfigMaps(mgr.namespace).Create(argoCDCM)
	} else {
		_, err = mgr.clientset.CoreV1().ConfigMaps(mgr.namespace).Update(argoCDCM)
	}
	if err != nil {
		return err
	}

	// Upsert the secret data. Ensure we do not delete any extra keys which user may have added
	argoCDSecret, err := mgr.secrets.Secrets(mgr.namespace).Get(common.ArgoCDSecretName)
	createSecret := false
	if err != nil {
		if !apierr.IsNotFound(err) {
			return err
		}
		argoCDSecret = &apiv1.Secret{
			ObjectMeta: metav1.ObjectMeta{
				Name: common.ArgoCDSecretName,
			},
			Data: make(map[string][]byte),
		}
		createSecret = true
	}
	if argoCDSecret.Data == nil {
		argoCDSecret.Data = make(map[string][]byte)
	}

	argoCDSecret.Data[settingServerSignatureKey] = settings.ServerSignature
	argoCDSecret.Data[settingAdminPasswordHashKey] = []byte(settings.AdminPasswordHash)
	argoCDSecret.Data[settingAdminPasswordMtimeKey] = []byte(settings.AdminPasswordMtime.Format(time.RFC3339))
	if settings.WebhookGitHubSecret != "" {
		argoCDSecret.Data[settingsWebhookGitHubSecretKey] = []byte(settings.WebhookGitHubSecret)
	}
	if settings.WebhookGitLabSecret != "" {
		argoCDSecret.Data[settingsWebhookGitLabSecretKey] = []byte(settings.WebhookGitLabSecret)
	}
	if settings.WebhookBitbucketUUID != "" {
		argoCDSecret.Data[settingsWebhookBitbucketUUIDKey] = []byte(settings.WebhookBitbucketUUID)
	}
	if settings.Certificate != nil {
		cert, key := tlsutil.EncodeX509KeyPair(*settings.Certificate)
		argoCDSecret.Data[settingServerCertificate] = cert
		argoCDSecret.Data[settingServerPrivateKey] = key
	} else {
		delete(argoCDSecret.Data, settingServerCertificate)
		delete(argoCDSecret.Data, settingServerPrivateKey)
	}
	if createSecret {
		_, err = mgr.clientset.CoreV1().Secrets(mgr.namespace).Create(argoCDSecret)
	} else {
		_, err = mgr.clientset.CoreV1().Secrets(mgr.namespace).Update(argoCDSecret)
	}
	if err != nil {
		return err
	}
	return mgr.ResyncInformers()
}
914529
func (s *StateSettings) CreateSettings(key string, settings map[string]interface{}) error {
	_, err := createSettings(s.backend.db(), s.collection, key, settings)
	return err
}
488180
func (ctx *ContextRelation) WriteSettings() (err error) {
	if ctx.settings != nil {
		err = ctx.settings.Write()
	}
	return
}
262519
func (s *OutputDestination) SetSettings(v []*OutputDestinationSettings) *OutputDestination {
	s.Settings = v
	return s
}
881693
func InitGlobalSettings(stateDriver core.StateDriver, inst *core.InstanceInfo) error {

	/*
		Query global settings from state store
		1. if forward mode or private net is empty, retry after 1 seccond
		2. if forward mode doesn't match, return error
		3. if stored private net is wrong, return error
	*/

	gCfg := mastercfg.GlobConfig{}
	gCfg.StateDriver = stateDriver

	// wait until able to get fwd mode and private subnet
	for {
		if err := gCfg.Read(""); err != nil {
			logrus.Warnf("Error reading global settings from cluster store, error: %v", err.Error())
		} else {
			if gCfg.FwdMode == "" || gCfg.PvtSubnet == "" {
				if gCfg.FwdMode == "" {
					logrus.Warnf("No forwarding mode found from cluster store")
				}
				if gCfg.PvtSubnet == "" {
					logrus.Warnf("No private subnet found from cluster store")
				}

			} else {
				logrus.Infof("Got global forwarding mode: %v", gCfg.FwdMode)
				logrus.Infof("Got global private subnet: %v", gCfg.PvtSubnet)
				break
			}
		}
		logrus.Warnf("Sleep 1 second and retry pulling global settings")
		time.Sleep(1 * time.Second)
	}

	// make sure local config matches netmaster config
	if inst.FwdMode != "" && inst.FwdMode != gCfg.FwdMode {
		err := fmt.Errorf("netplugin's local forward mode %q doesn't match global settings %q", inst.FwdMode, gCfg.FwdMode)
		logrus.Errorf(err.Error())
		return err
	}
	inst.FwdMode = gCfg.FwdMode

	logrus.Infof("Using forwarding mode: %v", inst.FwdMode)
	net, err := netutils.CIDRToMask(gCfg.PvtSubnet)
	if err != nil {
		err := fmt.Errorf("error convert private subnet %v from CIDR to mask, error %v", gCfg.PvtSubnet, err.Error())
		logrus.Errorf(err.Error())
		return err
	}
	inst.HostPvtNW = net
	logrus.Infof("Using host private subnet: %v", gCfg.PvtSubnet)
	return nil
}
618688
func (s *Option) SetOptionSettings(v []*OptionSetting) *Option {
	s.OptionSettings = v
	return s
}
609519
func checkStrings(L *lua.LState, n int) []string {
	params := L.GetTop()
	if n > params {
		return []string{}
	}
	args := make([]string, 0, (params - n + 1))
	for i := n; i <= params; i++ {
		p := L.Get(i)
		if p.Type() == lua.LTUserData {
			continue
		}
		L.CheckTypes(i, lua.LTString, lua.LTNumber)
		args = append(args, p.String())
	}
	return args
}
95979
func (mgr *SettingsManager) InitializeSettings() (*ArgoCDSettings, error) {
	cdSettings, err := mgr.GetSettings()
	if err != nil && !isIncompleteSettingsError(err) {
		return nil, err
	}
	if cdSettings == nil {
		cdSettings = &ArgoCDSettings{}
	}
	if cdSettings.ServerSignature == nil {
		// set JWT signature
		signature, err := util.MakeSignature(32)
		if err != nil {
			return nil, err
		}
		cdSettings.ServerSignature = signature
		log.Info("Initialized server signature")
	}
	if cdSettings.AdminPasswordHash == "" {
		defaultPassword, err := os.Hostname()
		if err != nil {
			return nil, err
		}
		hashedPassword, err := password.HashPassword(defaultPassword)
		if err != nil {
			return nil, err
		}
		cdSettings.AdminPasswordHash = hashedPassword
		cdSettings.AdminPasswordMtime = time.Now().UTC()
		log.Info("Initialized admin password")
	}
	if cdSettings.AdminPasswordMtime.IsZero() {
		cdSettings.AdminPasswordMtime = time.Now().UTC()
		log.Info("Initialized admin mtime")
	}

	if cdSettings.Certificate == nil {
		// generate TLS cert
		hosts := []string{
			"localhost",
			"argocd-server",
			fmt.Sprintf("argocd-server.%s", mgr.namespace),
			fmt.Sprintf("argocd-server.%s.svc", mgr.namespace),
			fmt.Sprintf("argocd-server.%s.svc.cluster.local", mgr.namespace),
		}
		certOpts := tlsutil.CertOptions{
			Hosts:        hosts,
			Organization: "Argo CD",
			IsCA:         true,
		}
		cert, err := tlsutil.GenerateX509KeyPair(certOpts)
		if err != nil {
			return nil, err
		}
		cdSettings.Certificate = cert
		log.Info("Initialized TLS certificate")
	}

	if len(cdSettings.Repositories) == 0 {
		err = mgr.MigrateLegacyRepoSettings(cdSettings)
		if err != nil {
			return nil, err
		}
	}

	err = mgr.SaveSettings(cdSettings)
	if apierrors.IsConflict(err) {
		// assume settings are initialized by another instance of api server
		log.Warnf("conflict when initializing settings. assuming updated by another replica")
		return mgr.GetSettings()
	}
	return cdSettings, nil
}
939320
func (s *CreateJobTemplateInput) SetSettings(v *JobTemplateSettings) *CreateJobTemplateInput {
	s.Settings = v
	return s
}
417919
func validateSettings(ctx *validation.Context, settings *notifypb.Settings) {
	switch {
	case settings.MiloHost == "":
		ctx.Errorf(requiredFieldError, "milo_host")
	case validation.ValidateHostname(settings.MiloHost) != nil:
		ctx.Errorf(invalidFieldError, "milo_host")
	}
}
484015
func (mgr *SettingsManager) GetSettings() (*ArgoCDSettings, error) {
	err := mgr.ensureSynced(false)
	if err != nil {
		return nil, err
	}
	argoCDCM, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(common.ArgoCDConfigMapName)
	if err != nil {
		return nil, err
	}
	argoCDSecret, err := mgr.secrets.Secrets(mgr.namespace).Get(common.ArgoCDSecretName)
	if err != nil {
		return nil, err
	}
	var settings ArgoCDSettings
	var errs []error
	if err := updateSettingsFromConfigMap(&settings, argoCDCM); err != nil {
		errs = append(errs, err)
	}
	if err := updateSettingsFromSecret(&settings, argoCDSecret); err != nil {
		errs = append(errs, err)
	}
	if len(errs) > 0 {
		return &settings, errs[0]
	}
	return &settings, nil
}
1237680
func ReadSettings(configFolder string) (public, protected map[string]interface{}, _ error) {
	cf, err := settingsPath(configFolder)
	if err != nil {
		return nil, nil, fmt.Errorf("canot locate settings file: %v", err)
	}
	hs, err := parseHandlerSettingsFile(cf)
	if err != nil {
		return nil, nil, fmt.Errorf("error parsing settings file: %v", err)
	}

	public = hs.PublicSettings
	if err := unmarshalProtectedSettings(configFolder, hs, &protected); err != nil {
		return nil, nil, fmt.Errorf("failed to parse protected settings: %v", err)
	}
	return public, protected, nil
}
1343296
func (s *IndicesGetSettingsService) FlatSettings(flatSettings bool) *IndicesGetSettingsService {
	s.flatSettings = &flatSettings
	return s
}