setting

package
v0.0.0-...-33942d2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2025 License: AGPL-3.0 Imports: 32 Imported by: 3

Documentation

Index

Constants

View Source
const (
	RedactedPassword = "*********"
	DefaultHTTPAddr  = "0.0.0.0"
	Dev              = "development"
	Prod             = "production"
	ApplicationName  = "Grafana"
)
View Source
const (
	// GMSAlertRulesPaused configures Alert Rules to all be in Paused state.
	GMSAlertRulesPaused = "paused"

	// GMSAlertRulesUnchanged will not change the Alert Rules' states.
	GMSAlertRulesUnchanged = "unchanged"
)
View Source
const (
	StaticProviderType = "static"
	GOFFProviderType   = "goff"
)
View Source
const (
	PluginUpdateStrategyLatest = "latest"
	PluginUpdateStrategyMinor  = "minor"
)
View Source
const (
	ProviderPrefix        = "secrets_manager.encryption."
	MisconfiguredProvider = "misconfigured"
)
View Source
const (

	// SchedulerBaseInterval base interval of the scheduler. Controls how often the scheduler fetches database for new changes as well as schedules evaluation of a rule
	// changing this value is discouraged because this could cause existing alert definition
	// with intervals that are not exactly divided by this number not to be evaluated
	SchedulerBaseInterval = 10 * time.Second
	// DefaultRuleEvaluationInterval indicates a default interval of for how long a rule should be evaluated to change state from Pending to Alerting
	DefaultRuleEvaluationInterval = SchedulerBaseInterval * 6 // == 60 seconds

)

Variables

View Source
var (

	// App settings.
	Env       = Dev
	AppUrl    string
	AppSubUrl string

	// build
	BuildVersion          string
	BuildCommit           string
	EnterpriseBuildCommit string
	BuildBranch           string
	BuildStamp            int64
	IsEnterprise          bool

	// packaging
	Packaging = "unknown"

	CookieSecure           bool
	CookieSameSiteDisabled bool
	CookieSameSiteMode     http.SameSite
)
View Source
var (
	ErrOperationNotPermitted = errors.New("operation not permitted")
)

Functions

func AddExpander

func AddExpander(name string, priority int64, e Expander)

func EnvKey

func EnvKey(sectionName string, keyName string) string

func ExpandVar

func ExpandVar(s string) (string, error)

func GetAlertmanagerDefaultConfiguration

func GetAlertmanagerDefaultConfiguration() string

func GetAllowedOriginGlobs

func GetAllowedOriginGlobs(originPatterns []string) ([]glob.Glob, error)

func GetExpanderRegex

func GetExpanderRegex() *regexp.Regexp

Slightly hacky function to avoid code duplication. If this is eventually called in multiple places, consider refactoring or potentially adding more general helper functions to this package

func ReadFeatureTogglesFromInitFile

func ReadFeatureTogglesFromInitFile(featureTogglesSection *ini.Section) (map[string]bool, error)

func RedactedURL

func RedactedURL(value string) (string, error)

func RedactedValue

func RedactedValue(key, value string) string

func ToAbsUrl

func ToAbsUrl(relativeUrl string) string

Types

type AnnotationCleanupSettings

type AnnotationCleanupSettings struct {
	MaxAge   time.Duration
	MaxCount int64
}

type AnonymousSettings

type AnonymousSettings struct {
	Enabled     bool
	OrgName     string
	OrgRole     string
	HideVersion bool
	DeviceLimit int64
}

type AuthJWTSettings

type AuthJWTSettings struct {
	// JWT Auth
	Enabled                 bool
	HeaderName              string
	URLLogin                bool
	EmailClaim              string
	UsernameClaim           string
	ExpectClaims            string
	JWKSetURL               string
	JWKSetBearerTokenFile   string
	CacheTTL                time.Duration
	KeyFile                 string
	KeyID                   string
	JWKSetFile              string
	AutoSignUp              bool
	RoleAttributePath       string
	RoleAttributeStrict     bool
	OrgMapping              []string
	OrgAttributePath        string
	AllowAssignGrafanaAdmin bool
	SkipOrgRoleSync         bool
	GroupsAttributePath     string
	EmailAttributePath      string
	UsernameAttributePath   string
	TlsClientCa             string
	TlsSkipVerify           bool
}

type AuthPasswordlessMagicLinkSettings

type AuthPasswordlessMagicLinkSettings struct {
	// Passwordless Auth via Magic Link
	Enabled        bool
	CodeExpiration time.Duration
}

type AuthProxySettings

type AuthProxySettings struct {
	// Auth Proxy
	Enabled          bool
	HeaderName       string
	HeaderProperty   string
	AutoSignUp       bool
	EnableLoginToken bool
	Whitelist        string
	Headers          map[string]string
	HeadersEncoded   bool
	SyncTTL          int
}

type Cfg

type Cfg struct {
	Target []string
	Raw    *ini.File
	Logger log.Logger

	// HTTP Server Settings
	CertFile          string
	KeyFile           string
	CertPassword      string
	CertWatchInterval time.Duration
	HTTPAddr          string
	HTTPPort          string
	Env               string
	AppURL            string
	AppSubURL         string
	InstanceName      string
	ServeFromSubPath  bool
	StaticRootPath    string
	Protocol          Scheme
	SocketGid         int
	SocketMode        int
	SocketPath        string
	RouterLogging     bool
	Domain            string
	CDNRootURL        *url.URL
	ReadTimeout       time.Duration
	EnableGzip        bool
	EnforceDomain     bool
	MinTLSVersion     string

	// Security settings
	SecretKey             string
	EmailCodeValidMinutes int

	// build
	BuildVersion          string
	BuildCommit           string
	EnterpriseBuildCommit string
	BuildBranch           string
	BuildStamp            int64
	IsEnterprise          bool

	// packaging
	Packaging string

	// Paths
	HomePath                   string
	ProvisioningPath           string
	PermittedProvisioningPaths []string
	// Provisioning config
	ProvisioningDisableControllers bool
	ProvisioningLokiURL            string
	ProvisioningLokiUser           string
	ProvisioningLokiPassword       string
	ProvisioningLokiTenantID       string
	DataPath                       string
	LogsPath                       string
	PluginsPath                    string
	EnterpriseLicensePath          string

	// SMTP email settings
	Smtp SmtpSettings

	// Rendering
	ImagesDir                      string
	CSVsDir                        string
	PDFsDir                        string
	RendererServerUrl              string
	RendererCallbackUrl            string
	RendererAuthToken              string
	RendererConcurrentRequestLimit int
	RendererRenderKeyLifeTime      time.Duration
	RendererDefaultImageWidth      int
	RendererDefaultImageHeight     int
	RendererDefaultImageScale      float64

	// Security
	DisableInitAdminCreation             bool
	DisableBruteForceLoginProtection     bool
	BruteForceLoginProtectionMaxAttempts int64
	DisableUsernameLoginProtection       bool
	DisableIPAddressLoginProtection      bool
	CookieSecure                         bool
	CookieSameSiteDisabled               bool
	CookieSameSiteMode                   http.SameSite
	AllowEmbedding                       bool
	XSSProtectionHeader                  bool
	ContentTypeProtectionHeader          bool
	StrictTransportSecurity              bool
	StrictTransportSecurityMaxAge        int
	StrictTransportSecurityPreload       bool
	StrictTransportSecuritySubDomains    bool
	// CSPEnabled toggles Content Security Policy support.
	CSPEnabled bool
	// CSPTemplate contains the Content Security Policy template.
	CSPTemplate string
	// CSPReportEnabled toggles Content Security Policy Report Only support.
	CSPReportOnlyEnabled bool
	// CSPReportOnlyTemplate contains the Content Security Policy Report Only template.
	CSPReportOnlyTemplate           string
	EnableFrontendSandboxForPlugins []string
	DisableGravatar                 bool
	DataProxyWhiteList              map[string]bool
	ActionsAllowPostURL             string

	// K8s Dashboard Cleanup
	K8sDashboardCleanup K8sDashboardCleanupSettings

	TempDataLifetime time.Duration

	// Plugins
	PluginsEnableAlpha               bool
	PluginsAppsSkipVerifyTLS         bool
	PluginSettings                   PluginSettings
	PluginsAllowUnsigned             []string
	PluginCatalogURL                 string
	PluginCatalogHiddenPlugins       []string
	PluginAdminEnabled               bool
	PluginAdminExternalManageEnabled bool
	PluginForcePublicKeyDownload     bool
	PluginSkipPublicKeyDownload      bool
	DisablePlugins                   []string
	ForwardHostEnvVars               []string
	PreinstallPluginsAsync           []InstallPlugin
	PreinstallPluginsSync            []InstallPlugin

	PluginsCDNURLTemplate    string
	PluginLogBackendRequests bool

	PluginUpdateStrategy string

	// Plugin API restrictions - maps API name to list of plugin IDs/patterns
	PluginRestrictedAPIsAllowList map[string][]string
	PluginRestrictedAPIsBlockList map[string][]string

	// Panels
	DisableSanitizeHtml bool

	// Metrics
	MetricsEndpointEnabled           bool
	MetricsEndpointBasicAuthUsername string
	MetricsEndpointBasicAuthPassword string
	MetricsEndpointDisableTotalStats bool
	// MetricsIncludeTeamLabel configures grafana to set a label for
	// the team responsible for the code at Grafana labs. We don't expect anyone else to
	// use this setting.
	MetricsIncludeTeamLabel          bool
	MetricsTotalStatsIntervalSeconds int
	MetricsGrafanaEnvironmentInfo    map[string]string

	// Dashboards
	DashboardVersionsToKeep     int
	MinRefreshInterval          string
	DefaultHomeDashboardPath    string
	DashboardPerformanceMetrics []string
	PanelSeriesLimit            int

	// Auth
	LoginCookieName               string
	LoginMaxInactiveLifetime      time.Duration
	LoginMaxLifetime              time.Duration
	TokenRotationIntervalMinutes  int
	SigV4AuthEnabled              bool
	SigV4VerboseLogging           bool
	AzureAuthEnabled              bool
	AzureSkipOrgRoleSync          bool
	BasicAuthEnabled              bool
	BasicAuthStrongPasswordPolicy bool
	AdminUser                     string
	AdminPassword                 string
	DisableLogin                  bool
	AdminEmail                    string
	DisableLoginForm              bool
	SignoutRedirectUrl            string
	IDResponseHeaderEnabled       bool
	IDResponseHeaderPrefix        string
	IDResponseHeaderNamespaces    map[string]struct{}
	ManagedServiceAccountsEnabled bool

	// AWS Plugin Auth
	AWSAllowedAuthProviders   []string
	AWSAssumeRoleEnabled      bool
	AWSSessionDuration        string
	AWSExternalId             string
	AWSListMetricsPageLimit   int
	AWSForwardSettingsPlugins []string

	// Azure Cloud settings
	Azure *azsettings.AzureSettings

	// Auth proxy settings
	AuthProxy AuthProxySettings

	// OAuth
	OAuthAutoLogin                       bool
	OAuthLoginErrorMessage               string
	OAuthCookieMaxAge                    int
	OAuthAllowInsecureEmailLookup        bool
	OAuthRefreshTokenServerLockMinWaitMs int64

	JWTAuth    AuthJWTSettings
	ExtJWTAuth ExtJWTSettings

	PasswordlessMagicLinkAuth AuthPasswordlessMagicLinkSettings

	// SSO Settings Auth
	SSOSettingsReloadInterval        time.Duration
	SSOSettingsConfigurableProviders map[string]bool

	// Dataproxy
	SendUserHeader                 bool
	DataProxyLogging               bool
	DataProxyTimeout               int
	DataProxyDialTimeout           int
	DataProxyTLSHandshakeTimeout   int
	DataProxyExpectContinueTimeout int
	DataProxyMaxConnsPerHost       int
	DataProxyMaxIdleConns          int
	DataProxyKeepAlive             int
	DataProxyIdleConnTimeout       int
	ResponseLimit                  int64
	DataProxyRowLimit              int64
	DataProxyUserAgent             string

	// DistributedCache
	RemoteCacheOptions *RemoteCacheSettings

	// Deprecated: no longer used
	ViewersCanEdit bool

	ApiKeyMaxSecondsToLive int64

	// Check if a feature toggle is enabled
	// Deprecated: use featuremgmt.FeatureFlags
	IsFeatureToggleEnabled func(key string) bool // filled in dynamically

	Anonymous AnonymousSettings

	DateFormats DateFormats
	QuickRanges QuickRanges

	// User
	UserInviteMaxLifetime        time.Duration
	HiddenUsers                  map[string]struct{}
	CaseInsensitiveLogin         bool // Login and Email will be considered case insensitive
	UserLastSeenUpdateInterval   time.Duration
	VerificationEmailMaxLifetime time.Duration

	// Service Accounts
	SATokenExpirationDayLimit int

	// Annotations
	AnnotationCleanupJobBatchSize      int64
	AnnotationMaximumTagsLength        int64
	AlertingAnnotationCleanupSetting   AnnotationCleanupSettings
	DashboardAnnotationCleanupSettings AnnotationCleanupSettings
	APIAnnotationCleanupSettings       AnnotationCleanupSettings

	// GrafanaJavascriptAgent config
	GrafanaJavascriptAgent GrafanaJavascriptAgent

	// Data sources
	DataSourceLimit int
	// Number of queries to be executed concurrently. Only for the datasource supports concurrency.
	ConcurrentQueryCount int
	// Default behavior for the "Manage alerts via Alerting UI" toggle when configuring a data source.
	// It only works if the data source's `jsonData.manageAlerts` prop does not contain a previously configured value.
	DefaultDatasourceManageAlertsUIToggle bool
	// Default behavior for the "Allow as recording rules target" toggle when configuring a data source.
	// It only works if the data source's `jsonData.allowAsRecordingRulesTarget` prop does not contain a previously configured value.
	DefaultAllowRecordingRulesTargetAlertsUIToggle bool

	// IP range access control
	IPRangeACEnabled     bool
	IPRangeACAllowedURLs []*url.URL
	IPRangeACSecretKey   string

	// SQL Data sources
	SqlDatasourceMaxOpenConnsDefault    int
	SqlDatasourceMaxIdleConnsDefault    int
	SqlDatasourceMaxConnLifetimeDefault int

	// Snapshots
	SnapshotEnabled      bool
	ExternalSnapshotUrl  string
	ExternalSnapshotName string
	ExternalEnabled      bool

	// Only used in https://snapshots.raintank.io/
	SnapshotPublicMode bool

	ErrTemplateName string

	StackID string
	Slug    string

	LocalFileSystemAvailable bool

	// Analytics
	CheckForGrafanaUpdates              bool
	CheckForPluginUpdates               bool
	ReportingDistributor                string
	ReportingEnabled                    bool
	ApplicationInsightsConnectionString string
	ApplicationInsightsEndpointUrl      string
	FeedbackLinksEnabled                bool
	ReportingStaticContext              map[string]string

	// Frontend analytics
	GoogleAnalyticsID                   string
	GoogleAnalytics4ID                  string
	GoogleAnalytics4SendManualPageViews bool
	GoogleTagManagerID                  string
	RudderstackDataPlaneURL             string
	RudderstackWriteKey                 string
	RudderstackSDKURL                   string
	RudderstackConfigURL                string
	RudderstackIntegrationsURL          string
	IntercomSecret                      string
	FrontendAnalyticsConsoleReporting   bool

	// LDAP
	LDAPAuthEnabled       bool
	LDAPSkipOrgRoleSync   bool
	LDAPConfigFilePath    string
	LDAPAllowSignup       bool
	LDAPActiveSyncEnabled bool
	LDAPSyncCron          string

	DefaultTheme    string
	DefaultLanguage string
	HomePage        string

	Quota QuotaSettings

	// User settings
	AllowUserSignUp                bool
	AllowUserOrgCreate             bool
	VerifyEmailEnabled             bool
	LoginHint                      string
	PasswordHint                   string
	DisableSignoutMenu             bool
	ExternalUserMngLinkUrl         string
	ExternalUserMngLinkName        string
	ExternalUserMngInfo            string
	ExternalUserMngAnalytics       bool
	ExternalUserMngAnalyticsParams string
	AutoAssignOrg                  bool
	AutoAssignOrgId                int
	AutoAssignOrgRole              string
	LoginDefaultOrgId              int64
	OAuthSkipOrgRoleUpdateSync     bool

	// ExpressionsEnabled specifies whether expressions are enabled.
	ExpressionsEnabled bool

	// SQLExpressionCellLimit is the maximum number of cells (rows × columns, across all frames) that can be accepted by a SQL expression.
	SQLExpressionCellLimit int64

	// SQLExpressionOutputCellLimit is the maximum number of cells (rows × columns) that can be outputted by a SQL expression.
	SQLExpressionOutputCellLimit int64

	// SQLExpressionQueryLengthLimit is the maximum length of a SQL query that can be used in a SQL expression.
	SQLExpressionQueryLengthLimit int64

	// SQLExpressionTimeoutSeconds is the duration a SQL expression will run before timing out
	SQLExpressionTimeout time.Duration

	ImageUploadProvider string

	// LiveMaxConnections is a maximum number of WebSocket connections to
	// Grafana Live ws endpoint (per Grafana server instance). 0 disables
	// Live, -1 means unlimited connections.
	LiveMaxConnections int
	// LiveHAEngine is a type of engine to use to achieve HA with Grafana Live.
	// Zero value means in-memory single node setup.
	LiveHAEngine string
	// LiveHAPRefix is a prefix for HA engine keys.
	LiveHAPrefix string
	// LiveHAEngineAddress is a connection address for Live HA engine.
	LiveHAEngineAddress  string
	LiveHAEnginePassword string
	// LiveAllowedOrigins is a set of origins accepted by Live. If not provided
	// then Live uses AppURL as the only allowed origin.
	LiveAllowedOrigins []string
	// LiveMessageSizeLimit is the maximum size in bytes of Websocket messages
	// from clients. Defaults to 64KB.
	LiveMessageSizeLimit int

	// Grafana.com URL, used for OAuth redirect.
	GrafanaComURL string
	// Grafana.com API URL. Can be set separately to GrafanaComURL
	// in case API is not publicly accessible.
	// Defaults to GrafanaComURL setting + "/api" if unset.
	GrafanaComAPIURL string

	// Grafana.com SSO API token used for Unified SSO between instances and Grafana.com.
	GrafanaComSSOAPIToken string

	// Geomap base layer config
	GeomapDefaultBaseLayerConfig map[string]any
	GeomapEnableCustomBaseLayers bool

	// Unified Alerting
	UnifiedAlerting UnifiedAlertingSettings

	// Query history
	QueryHistoryEnabled bool

	// Open feature settings
	OpenFeature OpenFeatureSettings

	Storage StorageSettings

	Search SearchSettings

	SecureSocksDSProxy SecureSocksDSProxySettings

	// SAML Auth
	SAMLAuthEnabled            bool
	SAMLSkipOrgRoleSync        bool
	SAMLRoleValuesGrafanaAdmin string

	// OAuth2 Server
	OAuth2ServerEnabled bool

	// OAuth2Server supports the two recommended key types from the RFC https://www.rfc-editor.org/rfc/rfc7518#section-3.1: RS256 and ES256
	OAuth2ServerGeneratedKeyTypeForClient string
	OAuth2ServerAccessTokenLifespan       time.Duration

	RBAC RBACSettings

	ZanzanaClient ZanzanaClientSettings
	ZanzanaServer ZanzanaServerSettings

	// GRPC Server.
	GRPCServer GRPCServerSettings

	CustomResponseHeaders map[string]string

	// This is used to override the general error message shown to users when we want to obfuscate a sensitive backend error
	UserFacingDefaultError string

	// DatabaseInstrumentQueries is used to decide if database queries
	// should be instrumented with metrics, logs and traces.
	// This needs to be on the global object since its used in the
	// sqlstore package and HTTP middlewares.
	DatabaseInstrumentQueries bool

	// Public dashboards
	PublicDashboardsEnabled bool

	// Cloud Migration
	CloudMigration CloudMigrationSettings

	// Feature Management Settings
	FeatureManagement FeatureMgmtSettings

	// Alerting
	AlertingEvaluationTimeout   time.Duration
	AlertingNotificationTimeout time.Duration
	AlertingMaxAttempts         int
	AlertingMinInterval         int64

	// Explore UI
	ExploreEnabled           bool
	ExploreDefaultTimeOffset string
	ExploreHideLogsDownload  bool

	// Help UI
	HelpEnabled bool

	// Profile UI
	ProfileEnabled bool

	// News Feed
	NewsFeedEnabled bool

	// Experimental scope settings
	ScopesListScopesURL     string
	ScopesListDashboardsURL string

	// Short Links
	ShortLinkExpiration int

	// Unified Storage
	UnifiedStorage                             map[string]UnifiedStorageConfig
	MaxPageSizeBytes                           int
	IndexPath                                  string
	IndexWorkers                               int
	IndexMaxBatchSize                          int
	IndexFileThreshold                         int
	IndexMinCount                              int
	IndexMaxCount                              int
	IndexRebuildInterval                       time.Duration
	IndexCacheTTL                              time.Duration
	EnableSharding                             bool
	QOSEnabled                                 bool
	QOSNumberWorker                            int
	QOSMaxSizePerTenant                        int
	MemberlistBindAddr                         string
	MemberlistAdvertiseAddr                    string
	MemberlistAdvertisePort                    int
	MemberlistJoinMember                       string
	MemberlistClusterLabel                     string
	MemberlistClusterLabelVerificationDisabled bool
	SearchRingReplicationFactor                int
	InstanceID                                 string
	SprinklesApiServer                         string
	SprinklesApiServerPageLimit                int
	CACertPath                                 string
	HttpsSkipVerify                            bool

	// Secrets Management
	SecretsManagement SecretsManagerSettings
	// contains filtered or unexported fields
}

TODO move all global vars to this struct

func NewCfg

func NewCfg() *Cfg

func NewCfgFromArgs

func NewCfgFromArgs(args CommandLineArgs) (*Cfg, error)

func NewCfgFromBytes

func NewCfgFromBytes(bytes []byte) (*Cfg, error)

NewCfgFromBytes specialized function to create a new Cfg from bytes (INI file).

func NewCfgFromBytesWithoutJSValidation

func NewCfgFromBytesWithoutJSValidation(bytes []byte) (*Cfg, error)

prevents a log line from being printed when the static root path is not found, useful for apiservers that have no frontend

func NewCfgFromINIFile

func NewCfgFromINIFile(iniFile *ini.File) (*Cfg, error)

NewCfgFromINIFile specialized function to create a new Cfg from an ini.File.

func NewCfgWithFeatures deprecated

func NewCfgWithFeatures(features func(string) bool) *Cfg

Deprecated: Avoid using IsFeatureToggleEnabled from settings. If you need to access feature flags, read them from the FeatureToggle (or FeatureManager) interface

func (cfg *Cfg) AddChangePasswordLink() bool

AddChangePasswordLink returns if login form is disabled or not since the same intention can be used to hide both features.

func (*Cfg) DefaultOrgID

func (cfg *Cfg) DefaultOrgID() int64

func (*Cfg) GetContentDeliveryURL

func (cfg *Cfg) GetContentDeliveryURL(prefix string) (string, error)

GetContentDeliveryURL returns full content delivery URL with /<edition>/<version> added to URL

func (*Cfg) Load

func (cfg *Cfg) Load(args CommandLineArgs) error

func (*Cfg) LogConfigSources

func (cfg *Cfg) LogConfigSources()

func (*Cfg) ReadUnifiedAlertingSettings

func (cfg *Cfg) ReadUnifiedAlertingSettings(iniFile *ini.File) error

ReadUnifiedAlertingSettings reads both the `unified_alerting` and `alerting` sections of the configuration while preferring configuration the `alerting` section. It first reads the `unified_alerting` section, then looks for non-defaults on the `alerting` section and prefers those.

nolint: gocyclo

func (*Cfg) SectionWithEnvOverrides

func (cfg *Cfg) SectionWithEnvOverrides(s string) *DynamicSection

SectionWithEnvOverrides dynamically overrides keys with environment variables. As a side effect, the value of the setting key will be updated if an environment variable is present.

type CloudMigrationSettings

type CloudMigrationSettings struct {
	GcomAPIToken                string
	AuthAPIUrl                  string
	SnapshotFolder              string
	GMSDomain                   string
	AlertRulesState             string
	ResourceStorageType         string
	GMSStartSnapshotTimeout     time.Duration
	GMSGetSnapshotStatusTimeout time.Duration
	GMSCreateUploadUrlTimeout   time.Duration
	GMSValidateKeyTimeout       time.Duration
	GMSReportEventTimeout       time.Duration
	FetchInstanceTimeout        time.Duration
	CreateAccessPolicyTimeout   time.Duration
	FetchAccessPolicyTimeout    time.Duration
	DeleteAccessPolicyTimeout   time.Duration
	ListTokensTimeout           time.Duration
	CreateTokenTimeout          time.Duration
	DeleteTokenTimeout          time.Duration
	TokenExpiresAfter           time.Duration
	FrontendPollInterval        time.Duration

	IsTarget        bool
	IsDeveloperMode bool
}

type CommandLineArgs

type CommandLineArgs struct {
	Config   string
	HomePath string
	Args     []string
}

type DateFormatIntervals

type DateFormatIntervals struct {
	Millisecond string `json:"millisecond"`
	Second      string `json:"second"`
	Minute      string `json:"minute"`
	Hour        string `json:"hour"`
	Day         string `json:"day"`
	Month       string `json:"month"`
	Year        string `json:"year"`
}

type DateFormats

type DateFormats struct {
	FullDate         string              `json:"fullDate"`
	UseBrowserLocale bool                `json:"useBrowserLocale"`
	Interval         DateFormatIntervals `json:"interval"`
	DefaultTimezone  string              `json:"defaultTimezone"`
	DefaultWeekStart string              `json:"defaultWeekStart"`
}

type DynamicSection

type DynamicSection struct {
	Logger log.Logger
	// contains filtered or unexported fields
}

func (*DynamicSection) Key

func (s *DynamicSection) Key(k string) *ini.Key

Key dynamically overrides keys with environment variables. As a side effect, the value of the setting key will be updated if an environment variable is present.

func (*DynamicSection) KeysHash

func (s *DynamicSection) KeysHash() map[string]string

type Expander

type Expander interface {
	SetupExpander(file *ini.File) error
	Expand(string) (string, error)
}

type ExtJWTSettings

type ExtJWTSettings struct {
	Enabled      bool
	ExpectIssuer string
	JWKSUrl      string
	Audiences    []string
}

type FeatureMgmtSettings

type FeatureMgmtSettings struct {
	HiddenToggles      map[string]struct{}
	ReadOnlyToggles    map[string]struct{}
	AllowEditing       bool
	UpdateWebhook      string
	UpdateWebhookToken string
}

type GRPCServerSettings

type GRPCServerSettings struct {
	Enabled        bool
	Network        string
	Address        string      // with flags, call Process to fill this field defaults
	TLSConfig      *tls.Config // with flags, call Process to fill this field
	EnableLogging  bool        // log request and response of each unary gRPC call
	MaxRecvMsgSize int
	MaxSendMsgSize int
	// contains filtered or unexported fields
}

func (*GRPCServerSettings) AddFlags

func (c *GRPCServerSettings) AddFlags(fs *pflag.FlagSet)

func (*GRPCServerSettings) Process

func (c *GRPCServerSettings) Process() error

type GlobalQuota

type GlobalQuota struct {
	Org          int64 `target:"org"`
	User         int64 `target:"user"`
	DataSource   int64 `target:"data_source"`
	Dashboard    int64 `target:"dashboard"`
	ApiKey       int64 `target:"api_key"`
	Session      int64 `target:"-"`
	AlertRule    int64 `target:"alert_rule"`
	File         int64 `target:"file"`
	Correlations int64 `target:"correlations"`
}

type GrafanaJavascriptAgent

type GrafanaJavascriptAgent struct {
	Enabled                             bool   `json:"enabled"`
	CustomEndpoint                      string `json:"customEndpoint"`
	EndpointRPS                         int    `json:"-"`
	EndpointBurst                       int    `json:"-"`
	AllInstrumentationsEnabeld          bool   `json:"allInstrumentationEnabeld"`
	ErrorInstrumentalizationEnabled     bool   `json:"errorInstrumentalizationEnabled"`
	ConsoleInstrumentalizationEnabled   bool   `json:"consoleInstrumentalizationEnabled"`
	WebVitalsInstrumentalizationEnabled bool   `json:"webVitalsInstrumentalizationEnabled"`
	TracingInstrumentalizationEnabled   bool   `json:"tracingInstrumentalizationEnabled"`
	InternalLoggerLevel                 int    `json:"internalLoggerLevel"`
	ApiKey                              string `json:"apiKey"`
}

type InstallPlugin

type InstallPlugin struct {
	ID      string `json:"id"`
	Version string `json:"version"`
	URL     string `json:"url,omitempty"`
}

type K8sDashboardCleanupSettings

type K8sDashboardCleanupSettings struct {
	Interval  time.Duration
	Timeout   time.Duration
	BatchSize int64
}

type KeyValue

type KeyValue interface {
	// Key returns pair's key.
	Key() string
	// Value returns pair's value.
	Value() string

	// MustString returns the value's string representation
	// If empty, then it returns the given default.
	MustString(defaultVal string) string
	// MustBool returns the value's boolean representation
	// Otherwise returns the given default.
	MustBool(defaultVal bool) bool
	// MustDuration returns the value's time.Duration
	// representation. Otherwise returns the given default.
	MustDuration(defaultVal time.Duration) time.Duration
}

KeyValue represents a settings key-value for a given pair of section and key.

type OSSImpl

type OSSImpl struct {
	Cfg *Cfg
}

func ProvideProvider

func ProvideProvider(cfg *Cfg) *OSSImpl

func (*OSSImpl) Current

func (o *OSSImpl) Current() SettingsBag

func (*OSSImpl) CurrentVerbose

func (o *OSSImpl) CurrentVerbose() VerboseSettingsBag

func (*OSSImpl) KeyValue

func (o *OSSImpl) KeyValue(section, key string) KeyValue

func (*OSSImpl) RegisterReloadHandler

func (*OSSImpl) RegisterReloadHandler(string, ReloadHandler)

func (*OSSImpl) Section

func (o *OSSImpl) Section(section string) Section

func (OSSImpl) Update

type OpenFeatureSettings

type OpenFeatureSettings struct {
	APIEnabled   bool
	ProviderType string
	URL          *url.URL
	TargetingKey string
	ContextAttrs map[string]any
}

type OpenFgaCacheSettings

type OpenFgaCacheSettings struct {
	// Number of items that will be kept in the in-memory cache used to resolve Check queries.
	// If CheckQueryCacheEnabled or CheckIteratorCacheEnabled, this is the size limit of the cache
	CheckCacheLimit uint32
	// When enabled, cache controller will verify whether check subproblem cache and check
	// iterator cache needs to be invalidated when there is a check or list objects API request.
	// The invalidation determination is based on whether there are recent write or deletes for
	// the store. This feature allows a larger check-query-cache-ttl and check-iterator-cache-ttl
	// at the expense of additional datastore queries for recent writes and deletes.
	CacheControllerEnabled bool
	// Specifies how frequently the cache controller checks for Writes occurring. While the
	// cache controller result is cached, the server will not read the datastore to check
	// whether subproblem cache and iterator cache needs to be invalidated.
	CacheControllerTTL time.Duration
	// Enables in-memory caching of Check subproblems. For example, if you have a relation
	// `define viewer: owner or editor`, and the query is `Check(user:anne, viewer, doc:1)`,
	// we'll evaluate the `owner` relation and the `editor` relation and cache both results:
	// `(user:anne, viewer, doc:1) -> allowed=true` and `(user:anne, owner, doc:1) -> allowed=true`.
	CheckQueryCacheEnabled bool
	// Time that items will be kept in the cache of Check subproblems
	CheckQueryCacheTTL time.Duration
	// Enables in-memory caching of database iterators. Each iterator is the result of a database
	// query, for example, usersets related to a specific object, or objects related to a specific
	// user, up to a certain number of tuples per iterator
	CheckIteratorCacheEnabled bool
	// Number of tuples that will be stored for each database iterator
	CheckIteratorCacheMaxResults uint32
	// Time that items will be kept in the cache of database iterators
	CheckIteratorCacheTTL time.Duration
	// Enables in-memory caching of database iterators for ListObjects. Each iterator is the result
	// of a database query, for example, usersets related to a specific object, or objects related
	// to a specific user, up to a certain number of tuples per iterator
	ListObjectsIteratorCacheEnabled bool
	// Number of tuples that will be stored for each ListObjects database iterator
	ListObjectsIteratorCacheMaxResults uint32
	// Time that items will be kept in the cache of ListObjects database iterators
	ListObjectsIteratorCacheTTL time.Duration
	// Enables sharing of datastore iterators with different consumers. Each iterator is the result
	// of a database query, for example usersets related to a specific object, or objects related
	// to a specific user, up to a certain number of tuples per iterator
	SharedIteratorEnabled bool
	// Limit of the number of iterators that can be shared when shared iterator is enabled
	SharedIteratorLimit uint32
	// Time that shared iterators will be kept in the cache
	SharedIteratorTTL time.Duration
}

Parameters to configure OpenFGA cache.

type OrgQuota

type OrgQuota struct {
	User       int64 `target:"org_user"`
	DataSource int64 `target:"data_source"`
	Dashboard  int64 `target:"dashboard"`
	ApiKey     int64 `target:"api_key"`
	AlertRule  int64 `target:"alert_rule"`
}

type PluginSettings

type PluginSettings map[string]map[string]string

PluginSettings maps plugin id to map of key/value settings.

type Provider

type Provider interface {
	// Current returns a SettingsBag with a static copy of
	// the current configured pairs of key/values for each
	// configuration section.
	Current() SettingsBag

	CurrentVerbose() VerboseSettingsBag

	// Update receives a SettingsBag with the pairs of key/values
	// to be updated per section and a SettingsRemovals with the
	// section keys to be removed.
	Update(updates SettingsBag, removals SettingsRemovals) error
	// KeyValue returns a key-value abstraction
	// for the given pair of section and key.
	KeyValue(section, key string) KeyValue
	// Section returns a settings section
	// abstraction for the given section name.
	Section(section string) Section
	// RegisterReloadHandler registers a handler for validation and reload
	// of configuration updates tied to a specific section
	RegisterReloadHandler(section string, handler ReloadHandler)
}

Provider is a settings provider abstraction with thread-safety and runtime updates.

type QuickRange

type QuickRange struct {
	// Display is the user-friendly label shown in the UI for this time range
	Display string `json:"display"`
	// From is the start of the time range in a format like "now-6h" or an absolute time
	From string `json:"from"`
	// To is the end of the time range, defaults to "now" if omitted
	To string `json:"to,omitempty"`
}

QuickRange represents a time range option in the time picker. It defines a preset time range that users can select from the time picker dropdown.

type QuickRanges

type QuickRanges []QuickRange

QuickRanges is a slice of QuickRange objects that can be directly used in frontend

type QuotaSettings

type QuotaSettings struct {
	Enabled bool
	Org     OrgQuota
	User    UserQuota
	Global  GlobalQuota
}

type RBACSettings

type RBACSettings struct {
	// Enable permission cache
	PermissionCache bool
	// Enable Permission validation during role creation and provisioning
	PermissionValidationEnabled bool
	// Reset basic roles permissions on start-up
	ResetBasicRoles bool
	// RBAC single organization. This configuration option is subject to change.
	SingleOrganization bool
	// If zanzana feature toggle is enabled this controls how often we
	// run the zanzana reconciliation loop.
	ZanzanaReconciliationInterval time.Duration

	OnlyStoreAccessActionSets bool
	// contains filtered or unexported fields
}

func (RBACSettings) PermissionsOnCreation

func (r RBACSettings) PermissionsOnCreation(resource string) bool

func (RBACSettings) PermissionsWildcardSeed

func (r RBACSettings) PermissionsWildcardSeed(resource string) bool

type RecordingRuleSettings

type RecordingRuleSettings struct {
	Enabled              bool
	CustomHeaders        map[string]string
	Timeout              time.Duration
	DefaultDatasourceUID string
}

type ReloadHandler

type ReloadHandler interface {
	// Reload handles reloading of configuration changes.
	ReloadSection(section Section) error

	// Validate validates the configuration, if the validation
	// fails the configuration will not be updated neither reloaded.
	ValidateSection(section Section) error
}

ReloadHandler defines the expected behaviour from a service that have support for configuration reloads.

type RemoteAlertmanagerSettings

type RemoteAlertmanagerSettings struct {
	URL          string
	TenantID     string
	Password     string
	SyncInterval time.Duration
	Timeout      time.Duration
}

RemoteAlertmanagerSettings contains the configuration needed to disable the internal Alertmanager and use an external one instead.

type RemoteCacheSettings

type RemoteCacheSettings struct {
	Name       string
	ConnStr    string
	Prefix     string
	Encryption bool
}

type Scheme

type Scheme string
const (
	HTTPScheme   Scheme = "http"
	HTTPSScheme  Scheme = "https"
	HTTP2Scheme  Scheme = "h2"
	SocketScheme Scheme = "socket"
)

type SearchSettings

type SearchSettings struct {
	FullReindexInterval       time.Duration
	IndexUpdateInterval       time.Duration
	DashboardLoadingBatchSize int
}

type SecretsManagerSettings

type SecretsManagerSettings struct {
	CurrentEncryptionProvider string

	// ConfiguredKMSProviders is a map of KMS providers found in the config file. The keys are in the format of <provider>.<keyName>, and the values are a map of the properties in that section
	// In OSS, the provider type can only be "secret_key". In Enterprise, it can additionally be one of: "aws_kms", "azure_keyvault", "google_kms", "hashicorp_vault"
	ConfiguredKMSProviders map[string]map[string]string

	GrpcClientEnable        bool   // Whether to enable the gRPC client. If disabled, it will use the in-process services implementations.
	GrpcServerUseTLS        bool   // Whether to use TLS when communicating with the gRPC server
	GrpcServerTLSSkipVerify bool   // Whether to skip TLS verification when communicating with the gRPC server
	GrpcServerTLSServerName string // Server name to use for TLS verification
	GrpcServerAddress       string // Address for gRPC secrets server
	GrpcGrafanaServiceName  string // Service name to use for background grafana decryption/inline

	// Used for testing. Set to false to disable the control loop.
	GCWorkerEnabled bool
	// Max number of inactive secure values to fetch from the database.
	GCWorkerMaxBatchSize uint16
	// Max number of tasks to delete secure values that can be inflight at a time.
	GCWorkerMaxConcurrentCleanups uint16
	// How long to wait for between fetching inactive secure values for cleanup.
	GCWorkerPollInterval time.Duration
	// How long to wait for the process to clean up a secure value to complete.
	GCWorkerPerSecureValueCleanupTimeout time.Duration
}

type Section

type Section interface {
	// KeyValue returns a key-value
	// abstraction for the given key.
	KeyValue(key string) KeyValue
}

Section is a settings section copy with all of its pairs of keys-values.

type SecureSocksDSProxySettings

type SecureSocksDSProxySettings struct {
	Enabled            bool
	ShowUI             bool
	AllowInsecure      bool
	ClientCert         string
	ClientCertFilePath string
	ClientKey          string
	ClientKeyFilePath  string
	RootCAs            []string
	RootCAFilePaths    []string
	ProxyAddress       string
	ServerName         string
}

type SettingsBag

type SettingsBag map[string]map[string]string

type SettingsRemovals

type SettingsRemovals map[string][]string

type SmtpSettings

type SmtpSettings struct {
	Enabled        bool
	Host           string
	User           string
	Password       string
	CertFile       string
	KeyFile        string
	FromAddress    string
	FromName       string
	EhloIdentity   string
	StartTLSPolicy string
	SkipVerify     bool
	StaticHeaders  map[string]string
	EnableTracing  bool

	SendWelcomeEmailOnSignUp bool
	TemplatesPatterns        []string
	ContentTypes             []string
}

type StorageSettings

type StorageSettings struct {
	AllowUnsanitizedSvgUpload bool
}

type UnifiedAlertingLokiSettings

type UnifiedAlertingLokiSettings struct {
	LokiRemoteURL string
	LokiReadURL   string
	LokiWriteURL  string
	LokiTenantID  string
	// LokiBasicAuthUsername and LokiBasicAuthPassword are used for basic auth
	// if one of them is set.
	LokiBasicAuthPassword string
	LokiBasicAuthUsername string
	LokiMaxQueryLength    time.Duration
	LokiMaxQuerySize      int
	ExternalLabels        map[string]string
}

type UnifiedAlertingNotificationHistorySettings

type UnifiedAlertingNotificationHistorySettings struct {
	Enabled      bool
	LokiSettings UnifiedAlertingLokiSettings
}

type UnifiedAlertingPrometheusConversionSettings

type UnifiedAlertingPrometheusConversionSettings struct {
	// RuleQueryOffset defines a time offset to apply to rule queries during conversion from Prometheus to Grafana format
	RuleQueryOffset time.Duration
}

UnifiedAlertingPrometheusConversionSettings contains configuration for converting Prometheus rules to Grafana format

type UnifiedAlertingReservedLabelSettings

type UnifiedAlertingReservedLabelSettings struct {
	DisabledLabels map[string]struct{}
}

func (*UnifiedAlertingReservedLabelSettings) IsReservedLabelDisabled

func (u *UnifiedAlertingReservedLabelSettings) IsReservedLabelDisabled(label string) bool

IsReservedLabelDisabled returns true if UnifiedAlertingReservedLabelSettings.DisabledLabels contains the given reserved label.

type UnifiedAlertingScreenshotSettings

type UnifiedAlertingScreenshotSettings struct {
	Capture                    bool
	CaptureTimeout             time.Duration
	MaxConcurrentScreenshots   int64
	UploadExternalImageStorage bool
}

type UnifiedAlertingSettings

type UnifiedAlertingSettings struct {
	AdminConfigPollInterval         time.Duration
	AlertmanagerConfigPollInterval  time.Duration
	AlertmanagerMaxSilenceSizeBytes int
	AlertmanagerMaxSilencesCount    int
	HAListenAddr                    string
	HAAdvertiseAddr                 string
	HAPeers                         []string
	HAPeerTimeout                   time.Duration
	HAGossipInterval                time.Duration
	HAReconnectTimeout              time.Duration
	HAPushPullInterval              time.Duration
	HALabel                         string
	HARedisClusterModeEnabled       bool
	HARedisSentinelModeEnabled      bool
	HARedisSentinelMasterName       string
	HARedisSentinelUsername         string
	HARedisSentinelPassword         string
	HARedisAddr                     string
	HARedisPeerName                 string
	HARedisPrefix                   string
	HARedisUsername                 string
	HARedisPassword                 string
	HARedisDB                       int
	HARedisMaxConns                 int
	HARedisTLSEnabled               bool
	HARedisTLSConfig                dstls.ClientConfig
	InitializationTimeout           time.Duration
	MaxAttempts                     int64
	InitialRetryDelay               time.Duration
	MaxRetryDelay                   time.Duration
	RandomizationFactor             float64
	MinInterval                     time.Duration
	EvaluationTimeout               time.Duration
	EvaluationResultLimit           int
	DisableJitter                   bool
	ExecuteAlerts                   bool
	DefaultConfiguration            string
	Enabled                         *bool // determines whether unified alerting is enabled. If it is nil then user did not define it and therefore its value will be determined during migration. Services should not use it directly.
	DisabledOrgs                    map[int64]struct{}
	// BaseInterval interval of time the scheduler updates the rules and evaluates rules.
	// Only for internal use and not user configuration.
	BaseInterval time.Duration
	// DefaultRuleEvaluationInterval default interval between evaluations of a rule.
	DefaultRuleEvaluationInterval time.Duration
	Screenshots                   UnifiedAlertingScreenshotSettings
	ReservedLabels                UnifiedAlertingReservedLabelSettings
	StateHistory                  UnifiedAlertingStateHistorySettings
	NotificationHistory           UnifiedAlertingNotificationHistorySettings
	RemoteAlertmanager            RemoteAlertmanagerSettings
	RecordingRules                RecordingRuleSettings
	PrometheusConversion          UnifiedAlertingPrometheusConversionSettings

	// MaxStateSaveConcurrency controls the number of goroutines (per rule) that can save alert state in parallel.
	MaxStateSaveConcurrency    int
	StatePeriodicSaveInterval  time.Duration
	StatePeriodicSaveBatchSize int
	RulesPerRuleGroupLimit     int64

	// Retention period for Alertmanager notification log entries.
	NotificationLogRetention time.Duration

	// Duration for which a resolved alert state transition will continue to be sent to the Alertmanager.
	ResolvedAlertRetention time.Duration

	// RuleVersionRecordLimit defines the limit of how many alert rule versions
	// should be stored in the database for each alert_rule in an organization including the current one.
	// 0 value means no limit
	RuleVersionRecordLimit int

	// DeletedRuleRetention defines the maximum duration to retain deleted alerting rules before permanent removal.
	DeletedRuleRetention time.Duration
}

func (*UnifiedAlertingSettings) IsEnabled

func (u *UnifiedAlertingSettings) IsEnabled() bool

IsEnabled returns true if UnifiedAlertingSettings.Enabled is either nil or true. It hides the implementation details of the Enabled and simplifies its usage.

type UnifiedAlertingStateHistorySettings

type UnifiedAlertingStateHistorySettings struct {
	Enabled                       bool
	Backend                       string
	LokiSettings                  UnifiedAlertingLokiSettings
	PrometheusMetricName          string
	PrometheusTargetDatasourceUID string
	PrometheusWriteTimeout        time.Duration
	MultiPrimary                  string
	MultiSecondaries              []string
	ExternalLabels                map[string]string
}

type UnifiedStorageConfig

type UnifiedStorageConfig struct {
	DualWriterMode                       rest.DualWriterMode
	DualWriterPeriodicDataSyncJobEnabled bool
	DualWriterMigrationDataSyncDisabled  bool
	// DataSyncerInterval defines how often the data syncer should run for a resource on the grafana instance.
	DataSyncerInterval time.Duration
	// DataSyncerRecordsLimit defines how many records will be processed at max during a sync invocation.
	DataSyncerRecordsLimit int
}

type UserQuota

type UserQuota struct {
	Org int64 `target:"org_user"`
}

type ValidationError

type ValidationError struct {
	Errors []error
}

func (ValidationError) Error

func (v ValidationError) Error() string

type VerboseSettingsBag

type VerboseSettingsBag map[string]map[string]map[VerboseSourceType]string

type VerboseSourceType

type VerboseSourceType string
const (
	DB     VerboseSourceType = "db"
	System VerboseSourceType = "system"
)

type ZanzanaClientSettings

type ZanzanaClientSettings struct {
	// Mode can either be embedded or client.
	Mode ZanzanaMode
	// Addr is the address of the Zanzana server.
	// Only used when mode is set to client.
	Addr string
	// Certificate used to authenticate the Server
	// Only used when mode is set to client
	ServerCertFile string
	// Token used to perform the exchange request.
	// Only used when mode is set to client.
	Token string
	// URL called to perform exchange request.
	// Only used when mode is set to client.
	TokenExchangeURL string
}

type ZanzanaMode

type ZanzanaMode string
const (
	ZanzanaModeClient   ZanzanaMode = "client"
	ZanzanaModeEmbedded ZanzanaMode = "embedded"
)

type ZanzanaServerSettings

type ZanzanaServerSettings struct {
	// OpenFGA http server address which allows to connect with fga cli.
	// Can only be used in dev mode.
	OpenFGAHttpAddr string
	// Cache settings
	CacheSettings OpenFgaCacheSettings
	// Max number of results returned by ListObjects() query. Default is 1000.
	ListObjectsMaxResults uint32
	// Deadline for the ListObjects() query. Default is 3 seconds.
	ListObjectsDeadline time.Duration
	// Use streamed version of list objects.
	// Returns full list of objects, but takes more time.
	UseStreamedListObjects bool
	// URL for fetching signing keys.
	SigningKeysURL string
	// Allow insecure connections to the server for development purposes.
	AllowInsecure bool
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL