prometheus

package
v0.84.0-rhobs1 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2025 License: Apache-2.0 Imports: 48 Imported by: 0

Documentation

Index

Constants

View Source
const (
	StorageDir   = "/prometheus"
	ConfDir      = "/etc/prometheus/config"
	ConfOutDir   = "/etc/prometheus/config_out"
	WebConfigDir = "/etc/prometheus/web_config"

	//TODO: RulesDir should be moved to the server package, since it is not used by the agent.
	// It is here at the moment because promcfg uses it, and moving as is will cause import cycle error.
	RulesDir = "/etc/prometheus/rules"

	ConfigFilename         = "prometheus.yaml.gz"
	ConfigEnvsubstFilename = "prometheus.env.yaml"
	DefaultPortName        = "web"
	DefaultLogFileVolume   = "log-file"
	DefaultLogDirectory    = "/var/log/prometheus"

	// DefaultTerminationGracePeriodSeconds defines how long Kubernetes should
	// wait before killing Prometheus on pod termination.
	// Prometheus may take a significant time to shut down due to data
	// checkpointing. By default, the operator allows up to 10 minutes for
	// clean termination.
	DefaultTerminationGracePeriodSeconds = int64(600)
)

Variables

View Source
var (
	ShardLabelName                = "operator.prometheus.io/shard"
	PrometheusNameLabelName       = "operator.prometheus.io/name"
	PrometheusModeLabeLName       = "operator.prometheus.io/mode"
	PrometheusK8sLabelName        = "app.kubernetes.io/name"
	ProbeTimeoutSeconds     int32 = 3
	LabelPrometheusName           = "prometheus-name"
)

Functions

func AddAPIServerConfigToStore

func AddAPIServerConfigToStore(ctx context.Context, store *assets.StoreBuilder, namespace string, config *monitoringv1.APIServerConfig) error

func AddRemoteReadsToStore

func AddRemoteReadsToStore(ctx context.Context, store *assets.StoreBuilder, namespace string, rrs []monitoringv1.RemoteReadSpec) error

AddRemoteReadsToStore loads all secret/configmap references from remote-read configs into the store.

func AddRemoteWritesToStore

func AddRemoteWritesToStore(ctx context.Context, store *assets.StoreBuilder, namespace string, rws []monitoringv1.RemoteWriteSpec) error

AddRemoteWritesToStore loads all secret/configmap references from remote-write configs into the store.

func AddScrapeClassesToStore

func AddScrapeClassesToStore(ctx context.Context, store *assets.StoreBuilder, namespace string, scrapeClasses []monitoringv1.ScrapeClass) error

func ApplyConfigurationFromPrometheus

func ApplyConfigurationFromPrometheus(p *monitoringv1.Prometheus, updateScaleSubresource bool) *monitoringv1ac.PrometheusApplyConfiguration

ApplyConfigurationFromPrometheus updates the Prometheus/PrometheusAgent Status subresource. It can optionally update the scale subresource as well.

func BuildCommonVolumes

func BuildCommonVolumes(p monitoringv1.PrometheusInterface, tlsSecrets *operator.ShardedSecret, statefulSet bool) ([]v1.Volume, []v1.VolumeMount, error)

BuildCommonVolumes returns a set of volumes to be mounted on the spec that are common between Prometheus Server and Agent.

func BuildConfigReloader

func BuildConfigReloader(
	p monitoringv1.PrometheusInterface,
	c Config,
	initContainer bool,
	mounts []v1.VolumeMount,
	watchedDirectories []string,
	opts ...operator.ReloaderOption,
) v1.Container

func BuildStatefulSetService

func BuildStatefulSetService(name string, selector map[string]string, p monitoringv1.PrometheusInterface, config Config) *v1.Service

BuildStatefulSetService returns a governing service to be used for a statefulset.

func CompareScrapeTimeoutToScrapeInterval

func CompareScrapeTimeoutToScrapeInterval(scrapeTimeout, scrapeInterval monitoringv1.Duration) error

CompareScrapeTimeoutToScrapeInterval validates value of scrapeTimeout based on scrapeInterval.

func CreateConfigReloaderVolumeMounts

func CreateConfigReloaderVolumeMounts() []v1.VolumeMount

func ExpectedStatefulSetShardNames

func ExpectedStatefulSetShardNames(
	p monitoringv1.PrometheusInterface,
) []string

func KeyToStatefulSetKey

func KeyToStatefulSetKey(p monitoringv1.PrometheusInterface, key string, shard int) string

func MakeConfigurationSecret

func MakeConfigurationSecret(p monitoringv1.PrometheusInterface, config Config, data []byte) (*v1.Secret, error)

func MakeExpectedLivenessProbe

func MakeExpectedLivenessProbe() *v1.Probe

func MakeExpectedReadinessProbe

func MakeExpectedReadinessProbe() *v1.Probe

func MakeExpectedStartupProbe

func MakeExpectedStartupProbe() *v1.Probe

func MakeK8sTopologySpreadConstraint

func MakeK8sTopologySpreadConstraint(selectorLabels map[string]string, tscs []monitoringv1.TopologySpreadConstraint) []v1.TopologySpreadConstraint

func NewLogger

func NewLogger() *slog.Logger

func NewTLSAssetSecret

func NewTLSAssetSecret(p monitoringv1.PrometheusInterface, config Config) *v1.Secret

func ReplicasNumberPtr

func ReplicasNumberPtr(
	p monitoringv1.PrometheusInterface,
) *int32

ReplicasNumberPtr returns a ptr to the normalized number of replicas.

func ShareProcessNamespace

func ShareProcessNamespace(p monitoringv1.PrometheusInterface) *bool

func SubPathForStorage

func SubPathForStorage(s *monitoringv1.StorageSpec) string

It is stil here because promcfg still uses it.

func TLSAssetsSecretName

func TLSAssetsSecretName(p monitoringv1.PrometheusInterface) string

func UsesDefaultFileVolume

func UsesDefaultFileVolume(file string) bool

func WebConfigSecretName

func WebConfigSecretName(p monitoringv1.PrometheusInterface) string

Types

type Collector

type Collector struct {
	// contains filtered or unexported fields
}

func NewCollectorForStores

func NewCollectorForStores(s ...cache.Store) *Collector

func (*Collector) Collect

func (c *Collector) Collect(ch chan<- prometheus.Metric)

Collect implements the prometheus.Collector interface.

func (*Collector) Describe

func (c *Collector) Describe(ch chan<- *prometheus.Desc)

Describe implements the prometheus.Collector interface.

type Config

type Config struct {
	LocalHost                  string
	ReloaderConfig             operator.ContainerConfig
	PrometheusDefaultBaseImage string
	ThanosDefaultBaseImage     string
	Annotations                operator.Map
	Labels                     operator.Map
}

Config defines the operator's parameters for the Prometheus controllers. Whenever the value of one of these parameters is changed, it triggers an update of the managed statefulsets.

type ConfigGenerator

type ConfigGenerator struct {
	// contains filtered or unexported fields
}

ConfigGenerator knows how to generate a Prometheus configuration which is compatible with a given Prometheus version.

func NewConfigGenerator added in v0.23.0

func NewConfigGenerator(
	logger *slog.Logger,
	p monitoringv1.PrometheusInterface,
	opts ...ConfigGeneratorOption,
) (*ConfigGenerator, error)

NewConfigGenerator creates a ConfigGenerator for the provided Prometheus resource.

func (*ConfigGenerator) AddHonorLabels

func (cg *ConfigGenerator) AddHonorLabels(cfg yaml.MapSlice, honorLabels bool) yaml.MapSlice

AddHonorLabels adds the honor_labels field into scrape configurations. if OverrideHonorLabels is true then honor_labels is always false.

func (*ConfigGenerator) AddHonorTimestamps

func (cg *ConfigGenerator) AddHonorTimestamps(cfg yaml.MapSlice, userHonorTimestamps *bool) yaml.MapSlice

AddHonorTimestamps adds the honor_timestamps field into scrape configurations. honor_timestamps is false only when the user specified it or when the global override applies. For backwards compatibility with Prometheus <2.9.0 we don't set honor_timestamps.

func (*ConfigGenerator) AddLimitsToYAML

func (cg *ConfigGenerator) AddLimitsToYAML(cfg yaml.MapSlice, k limitKey, limit *uint64, enforcedLimit *uint64) yaml.MapSlice

AddLimitsToYAML appends the given limit key to the configuration if supported by the Prometheus version.

func (*ConfigGenerator) AddTrackTimestampsStaleness

func (cg *ConfigGenerator) AddTrackTimestampsStaleness(cfg yaml.MapSlice, trackTimestampsStaleness *bool) yaml.MapSlice

AddTrackTimestampsStaleness adds the track_timestamps_staleness field into scrape configurations. For backwards compatibility with Prometheus <2.48.0 we don't set track_timestamps_staleness.

func (*ConfigGenerator) AppendCommandlineArgument

func (cg *ConfigGenerator) AppendCommandlineArgument(m []monitoringv1.Argument, argument monitoringv1.Argument) []monitoringv1.Argument

AppendCommandlineArgument appends the name/v argument to the given []monitoringv1.Argument and returns the updated slice.

func (*ConfigGenerator) AppendMapItem

func (cg *ConfigGenerator) AppendMapItem(m yaml.MapSlice, k string, v interface{}) yaml.MapSlice

AppendMapItem appends the k/v item to the given yaml.MapSlice and returns the updated slice.

func (*ConfigGenerator) BuildCommonPrometheusArgs

func (cg *ConfigGenerator) BuildCommonPrometheusArgs() []monitoringv1.Argument

BuildCommonPrometheusArgs builds a slice of arguments that are common between Prometheus Server and Agent.

func (*ConfigGenerator) BuildPodMetadata

func (cg *ConfigGenerator) BuildPodMetadata() (map[string]string, map[string]string)

func (*ConfigGenerator) BuildProbes

func (cg *ConfigGenerator) BuildProbes() (*v1.Probe, *v1.Probe, *v1.Probe)

BuildProbes returns a tuple of 3 probe definitions: 1. startup probe 2. readiness probe 3. liveness probe

The /-/ready handler returns OK only after the TSDB initialization has completed. The WAL replay can take a significant time for large setups hence we enable the startup probe with a generous failure threshold (15 minutes) to ensure that the readiness probe only comes into effect once Prometheus is effectively ready. We don't want to use the /-/healthy handler here because it returns OK as soon as the web server is started (irrespective of the WAL replay).

func (*ConfigGenerator) GenerateAgentConfiguration

func (cg *ConfigGenerator) GenerateAgentConfiguration(
	sMons map[string]*monitoringv1.ServiceMonitor,
	pMons map[string]*monitoringv1.PodMonitor,
	probes map[string]*monitoringv1.Probe,
	sCons map[string]*monitoringv1alpha1.ScrapeConfig,
	store *assets.StoreBuilder,
	additionalScrapeConfigs []byte,
) ([]byte, error)

GenerateAgentConfiguration creates a serialized YAML representation of a Prometheus Agent configuration using the provided resources.

func (*ConfigGenerator) GenerateRemoteWriteConfig

func (cg *ConfigGenerator) GenerateRemoteWriteConfig(rws []monitoringv1.RemoteWriteSpec, s assets.StoreGetter) yaml.MapItem

func (*ConfigGenerator) GenerateServerConfiguration

func (cg *ConfigGenerator) GenerateServerConfiguration(
	p *monitoringv1.Prometheus,
	sMons map[string]*monitoringv1.ServiceMonitor,
	pMons map[string]*monitoringv1.PodMonitor,
	probes map[string]*monitoringv1.Probe,
	sCons map[string]*monitoringv1alpha1.ScrapeConfig,
	store *assets.StoreBuilder,
	additionalScrapeConfigs []byte,
	additionalAlertRelabelConfigs []byte,
	additionalAlertManagerConfigs []byte,
	ruleConfigMapNames []string,
) ([]byte, error)

GenerateServerConfiguration creates a serialized YAML representation of a Prometheus Server configuration using the provided resources.

func (*ConfigGenerator) IsCompatible

func (cg *ConfigGenerator) IsCompatible() bool

IsCompatible return true or false depending if the version being used is compatible.

func (*ConfigGenerator) Version

func (cg *ConfigGenerator) Version() semver.Version

Version returns the currently configured Prometheus version.

func (*ConfigGenerator) Warn

func (cg *ConfigGenerator) Warn(field string)

Warn logs a warning.

func (*ConfigGenerator) WithKeyVals

func (cg *ConfigGenerator) WithKeyVals(keyvals ...interface{}) *ConfigGenerator

WithKeyVals returns a new ConfigGenerator with the same characteristics as the current object, expect that the keyvals are appended to the existing logger.

func (*ConfigGenerator) WithMaximumVersion

func (cg *ConfigGenerator) WithMaximumVersion(version string) *ConfigGenerator

WithMaximumVersion returns a new ConfigGenerator that does nothing (except logging a warning message) if the Prometheus version is greater than or equal to the given version. The method panics if version isn't a valid SemVer value.

func (*ConfigGenerator) WithMinimumVersion

func (cg *ConfigGenerator) WithMinimumVersion(version string) *ConfigGenerator

WithMinimumVersion returns a new ConfigGenerator that does nothing (except logging a warning message) if the Prometheus version is lesser than the given version. The method panics if version isn't a valid SemVer value.

type ConfigGeneratorOption

type ConfigGeneratorOption func(*ConfigGenerator)

func WithDaemonSet

func WithDaemonSet() ConfigGeneratorOption

func WithEndpointSliceSupport

func WithEndpointSliceSupport() ConfigGeneratorOption

func WithInlineTLSConfig

func WithInlineTLSConfig() ConfigGeneratorOption

func WithPrometheusTopologySharding

func WithPrometheusTopologySharding() ConfigGeneratorOption

func WithoutVersionCheck

func WithoutVersionCheck() ConfigGeneratorOption

WithoutVersionCheck returns a ConfigGenerator which doesn't perform any version check.

type LabelConfigValidator

type LabelConfigValidator struct {
	// contains filtered or unexported fields
}

func (*LabelConfigValidator) Validate

type ListAllByNamespaceFn

type ListAllByNamespaceFn func(namespace string, selector labels.Selector, appendFn cache.AppendFunc) error

type ResourceSelector

type ResourceSelector struct {
	// contains filtered or unexported fields
}

ResourceSelector knows how to select and verify scrape configuration resources that are matched by a Prometheus or PrometheusAgent object.

func NewResourceSelector

func NewResourceSelector(
	l *slog.Logger,
	p monitoringv1.PrometheusInterface,
	store *assets.StoreBuilder,
	namespaceInformers cache.SharedIndexInformer,
	metrics *operator.Metrics,
	eventRecorder record.EventRecorder,
) (*ResourceSelector, error)

func (*ResourceSelector) SelectPodMonitors

SelectPodMonitors returns the PodMonitors that match the selectors in the Prometheus custom resource. This function also populates authentication stores and performs validations against scrape intervals and relabel configs.

func (*ResourceSelector) SelectProbes

SelectProbes returns the probes matching the selectors specified in the Prometheus CR. This function also populates authentication stores and performs validations against scrape intervals, relabel configs and Probe URLs.

func (*ResourceSelector) SelectScrapeConfigs

SelectScrapeConfigs returns the ScrapeConfigs which match the selectors in the Prometheus CR and filters them returning all the configuration.

func (*ResourceSelector) SelectServiceMonitors

SelectServiceMonitors returns the ServiceMonitors that match the selectors in the Prometheus custom resource. This function also populates authentication stores and performs validations against scrape intervals and relabel configs.

func (*ResourceSelector) ValidateRelabelConfigs

func (rs *ResourceSelector) ValidateRelabelConfigs(rcs []monitoringv1.RelabelConfig) error

type ResourcesSelection

type ResourcesSelection[T configurationResource] []struct {
	// contains filtered or unexported fields
}

ResourcesSelection represents a slice of configuration resources selected by Prometheus or PrometheusAgent.

func (ResourcesSelection[T]) ValidResources

func (resources ResourcesSelection[T]) ValidResources() map[string]T

ValidResources returns only the resources which the operator considers to be valid. The keys of the returned map identify the resources using the `<namespace>/<name>` format.

type StatusReporter

type StatusReporter struct {
	Kclient         kubernetes.Interface
	Reconciliations *operator.ReconciliationTracker
	SsetInfs        *informers.ForResource
	Rr              *operator.ResourceReconciler
}

func (*StatusReporter) Process

Process will determine the Status of a Prometheus resource (server or agent) depending on its current state in the cluster.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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