Documentation
¶
Index ¶
- Constants
- type Bind
- type Metric
- type MetricType
- type MetricsProvider
- type Observability
- func (c *Observability) Address() string
- func (c *Observability) CoreConfigSource() ([]cf.ConfigSourceValue, error)
- func (c *Observability) GetDependencies() []string
- func (c *Observability) GetInitOrderStage() cf.Stage
- func (c *Observability) Init(ctx context.Context, fw *cf.CaerusFramework) error
- func (c *Observability) Name() string
- func (c *Observability) OnConfigReload(source string, cfg any)
- func (c *Observability) Run(ctx context.Context) error
- func (c *Observability) Shutdown(ctx context.Context) error
- func (c *Observability) TracerProvider() oteltrace.TracerProvider
- type ObservabilityConfig
- type Option
- func WithBind(addrs ...string) Option
- func WithConfig(cfg ObservabilityConfig) Option
- func WithConfigSource(name string) Option
- func WithHealthCheckTimeout(d time.Duration) Option
- func WithHealthChecks(enabled bool) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMetrics(enabled bool) Option
- func WithServiceName(name string) Option
- func WithTraceCAFile(path string) Option
- func WithTraceEndpoint(endpoint string) Option
- func WithTraceInsecure(insecure bool) Option
- func WithTraceSampleRatio(ratio float64) Option
- func WithTracing(enabled bool) Option
Constants ¶
const ComponentName = "observability"
ComponentName is the framework component name for the observability component. It is the identifier other components use in GetDependencies to require observability.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Bind ¶ added in v0.0.7
type Bind []string
Bind is one or more host:port listen addresses. JSON/YAML is a string for a single listener (":9090") or an array for several (ports may differ).
func (Bind) MarshalJSON ¶ added in v0.0.7
MarshalJSON writes a string when there is one address, otherwise an array.
func (*Bind) UnmarshalJSON ¶ added in v0.0.7
UnmarshalJSON accepts a string or an array of strings.
type Metric ¶
type Metric struct {
// Name is the metric name served on /metrics. It must not be empty for
// the sample to be emitted.
Name string
// Help describes the metric for /metrics consumers.
Help string
// Value is the sample value. State/info samples typically use 1 and carry
// their meaning in Labels.
Value float64
// Labels annotate the sample, e.g. {"format": "json", "level": "info"}.
Labels map[string]string
// Type selects how the sample is scraped. The zero value (MetricTypeGauge)
// preserves the pre-existing behavior; set MetricTypeCounter for
// monotonically increasing event counts.
Type MetricType
}
Metric is one runtime-state sample a component exposes for the /metrics endpoint. The observability component serves the sample under Name as-is (Name "logs_info" appears in /metrics as "logs_info").
type MetricType ¶
type MetricType int
MetricType distinguishes how a Metric sample is scraped. The zero value (MetricTypeGauge) preserves backward compatibility with existing samples.
const ( // MetricTypeGauge is the default. The sample is emitted as a Prometheus // gauge (current value, goes up and down). MetricTypeGauge MetricType = iota // MetricTypeCounter marks a monotonically increasing counter. The sample // is emitted as a Prometheus counter (only resets on process restart). // Components must ensure counter values only increase for the process // lifetime. MetricTypeCounter )
type MetricsProvider ¶
type MetricsProvider interface {
// Metrics returns the component's current runtime state. Return nil while
// the component is not initialized or has nothing to report.
Metrics() []Metric
}
MetricsProvider is an optional interface for components that expose runtime state as metrics. The observability component discovers components implementing it and calls Metrics on every /metrics scrape, so the values are always live: a component that is not initialized yet returns nil and is skipped until it does — a lazy pickup that needs no subscription. A component that does not implement MetricsProvider contributes nothing to /metrics.
Bootstrap components (logs, configuration) do not implement this interface to avoid import cycles; observability scrapes their state directly via cf.Get + exported state helpers.
type Observability ¶
type Observability struct {
// contains filtered or unexported fields
}
Observability is the caerus-framework-observability component. It exposes:
- Kubernetes health-check endpoints (liveness /healthz + /livez, readiness /readyz) that aggregate the health of every registered component implementing cf.HealthProvider. Components that do not implement it are simply not included, so supporting health checks is entirely optional.
- a /metrics endpoint (Prometheus text format) with Go runtime metrics plus the live state of every registered component implementing cf.MetricsProvider. State is read on every scrape, so a component that is not initialized yet returns nil and is skipped until it does (lazy pickup); components that do not implement the interface contribute nothing.
- OpenTelemetry tracing: when an OTLP endpoint is configured, the component builds a tracer provider, installs it as the global provider (components trace via otel.Tracer), and flushes it at Shutdown.
func New ¶
func New(opts ...Option) *Observability
New creates an observability component. Health checks and metrics are on by default; tracing is off until explicitly enabled with a config value or option. Init prepares collectors and the HTTP mux; Run (cf.Runnable) binds the listener when at least one of health checks or metrics is enabled. Jobs never start Runnables, so a migrate/seed process does not open the operator HTTP port.
func (*Observability) Address ¶
func (c *Observability) Address() string
Address returns the bound address of the HTTP server, or "" if neither health checks nor metrics are enabled, Init has not run, or Run has not bound yet. It is useful for building Kubernetes probe configs at runtime after the serve path has started.
func (*Observability) CoreConfigSource ¶
func (c *Observability) CoreConfigSource() ([]cf.ConfigSourceValue, error)
CoreConfigSource implements cf.CoreConfigSource. Observability imports the configuration module (Lookup at Init). Logs cannot (configuration imports logs); this package does. The framework still collects the declaration during argv absorption so ParseFlags sees --observability and OBSERVABILITY_ before Init.
func (*Observability) GetDependencies ¶
func (c *Observability) GetDependencies() []string
GetDependencies implements cf.Dependencies. The component logs through the framework logs component, and depends on configuration when WithConfigSource is set (it reads its own source through the configuration component).
func (*Observability) GetInitOrderStage ¶
func (c *Observability) GetInitOrderStage() cf.Stage
GetInitOrderStage implements cf.CaerusComponent. Observability is part of the bootstrap prefix and initializes after logs and configuration.
func (*Observability) Init ¶
func (c *Observability) Init(ctx context.Context, fw *cf.CaerusFramework) error
Init implements cf.CaerusComponent. It sets up metrics (Prometheus registry with Go runtime collectors and one collector per registered component implementing cf.MetricsProvider) and tracing (OTLP tracer provider, when an endpoint is configured and tracing is enabled). When health checks or metrics are enabled it builds the HTTP mux and discovers registered cf.HealthProvider components. It does not bind a listen address — that is Run's job, so a framework job (which never starts Runnables) does not expose /metrics or probes.
func (*Observability) Name ¶
func (c *Observability) Name() string
Name implements cf.CaerusComponent.
func (*Observability) OnConfigReload ¶
func (c *Observability) OnConfigReload(source string, cfg any)
OnConfigReload implements cf.ConfigReloader. It applies a freshly loaded ObservabilityConfig from the source named by WithConfigSource. Tracing toggle/endpoint changes take effect immediately (provider swap); HTTP endpoint changes (bind address, health-check/metrics toggles) are logged as restart-required and the last-good server keeps running. The initial value delivered by configuration before this component's Init is ignored (Init reads the source itself and must not build providers early).
func (*Observability) Run ¶ added in v0.0.5
func (c *Observability) Run(ctx context.Context) error
Run implements cf.Runnable. It binds the operator HTTP server (health probes and /metrics) and serves until ctx is canceled. Init only prepares the mux; claiming a listen address here means a job-only process — which never starts Runnables — does not expose those endpoints.
func (*Observability) Shutdown ¶
func (c *Observability) Shutdown(ctx context.Context) error
Shutdown implements cf.CaerusComponent. It stops the HTTP server if Run (or an in-flight serve) left one running, waiting for in-flight requests up to ctx, and flushes the tracer provider. Safe to call even if Init never ran or the features are disabled.
func (*Observability) TracerProvider ¶
func (c *Observability) TracerProvider() oteltrace.TracerProvider
TracerProvider returns the OpenTelemetry tracer provider configured at Init, or nil when tracing is disabled or no endpoint was configured. Components trace through otel.Tracer (the provider is installed globally); the accessor is for embedding and for building composite providers.
type ObservabilityConfig ¶
type ObservabilityConfig struct {
// HealthChecks enables the Kubernetes health-check HTTP endpoints. It is a
// *bool so an absent key is distinguishable from an explicit
// health_checks: false, which is required to turn the endpoints off (the
// component's default is enabled).
HealthChecks *bool `json:"health_checks,omitempty" yaml:"health_checks,omitempty" env:"HEALTH_CHECKS" flag:"observability-health-checks"`
// Metrics enables the /metrics endpoint (Prometheus text format; default
// enabled). It is a *bool so an explicit metrics: false is honored.
Metrics *bool `json:"metrics,omitempty" yaml:"metrics,omitempty" env:"METRICS" flag:"observability-metrics"`
// Tracing enables OpenTelemetry trace export over OTLP/gRPC (default off;
// internal tracing mechanics stay dark until enabled). It is a *bool so an
// explicit tracing: false is honored.
Tracing *bool `json:"tracing,omitempty" yaml:"tracing,omitempty" env:"TRACING" flag:"observability-tracing"`
// Bind is the operator HTTP listen address(es). A JSON string is one
// listener (":9090"); an array is multibind (ports may differ). Omit keeps
// the default ":9090".
Bind Bind `json:"bind,omitempty" yaml:"bind,omitempty" env:"BIND" flag:"observability-bind"`
// HealthCheckTimeoutSec bounds each component health check (default 2).
HealthCheckTimeoutSec int `` /* 160-byte string literal not displayed */
// TraceEndpoint is the OTLP/gRPC collector endpoint (e.g.
// "otel-collector:4317"). When set and tracing is enabled, spans are
// exported to it.
TraceEndpoint string `json:"trace_endpoint,omitempty" yaml:"trace_endpoint,omitempty" env:"TRACE_ENDPOINT" flag:"observability-trace-endpoint"`
// TraceInsecure admits cleartext OTLP. Default false (TLS). Ops must set
// true to talk to a collector without TLS.
TraceInsecure bool `json:"trace_insecure,omitempty" yaml:"trace_insecure,omitempty" env:"TRACE_INSECURE" flag:"observability-trace-insecure"`
// TraceCAFile is an optional PEM CA file for TLS OTLP (empty = system roots).
TraceCAFile string `json:"trace_ca_file,omitempty" yaml:"trace_ca_file,omitempty" env:"TRACE_CA_FILE" flag:"observability-trace-ca-file"`
// TraceSampleRatio is head sampling in this process (0–1). Nil keeps the
// default 1.0 (same as AlwaysSample). Explicit 0 means new traces are not
// sampled; children still follow a sampled parent (ParentBased).
TraceSampleRatio *float64 `` /* 136-byte string literal not displayed */
// ServiceName is the OpenTelemetry service.name attribute attached to
// exported spans (default "caerus").
ServiceName string `json:"service_name,omitempty" yaml:"service_name,omitempty" env:"SERVICE_NAME" flag:"observability-service-name"`
}
ObservabilityConfig is the file/env-drivable observability configuration. Load it through the configuration component and pass it via WithConfig; both JSON and YAML tags are provided.
type Option ¶
type Option func(*options)
Option configures the observability component at construction time.
func WithBind ¶ added in v0.0.7
WithBind sets one or more host:port listen addresses (default ":9090").
func WithConfig ¶
func WithConfig(cfg ObservabilityConfig) Option
WithConfig sets the configuration loaded from the configuration component. Non-zero fields of cfg override the values set by the convenience options, which act as in-code defaults:
cfg, _ := cf_configuration.Lookup[cf_observability.ObservabilityConfig](conf, "observability") o := cf_observability.New(cf_observability.WithConfig(*cfg))
func WithConfigSource ¶
WithConfigSource names the configuration source (caerus-framework- configuration) whose ObservabilityConfig is applied to the component at Init and again on every validated reload via OnConfigReload. Prefer this over a WithConfig snapshot when the component is framework-managed: the source stays the live options plane. The component self-registers the source during argv absorption (default file config/<name>.json, owner cf_observability); an argv --<name> file-path override wins, and the app may also register its own Source[ObservabilityConfig] for a custom default. Until the source loads, construction-time defaults apply.
func WithHealthCheckTimeout ¶
WithHealthCheckTimeout sets the deadline for each component health check (default 2s). A component that misses its deadline is reported as not ready.
func WithHealthChecks ¶
WithHealthChecks enables (default) or disables the Kubernetes health-check HTTP endpoints.
func WithLogger ¶
WithLogger overrides the logger used for component diagnostics. By default the component logs through the framework logs component (declared in GetDependencies); WithLogger is an explicit override for tests and embedded use and wins over the framework logger. slog.Default() remains the fallback only when neither is available.
func WithMetrics ¶
WithMetrics enables (default) or disables the /metrics endpoint.
func WithServiceName ¶
WithServiceName sets the OpenTelemetry service.name attribute (default "caerus").
func WithTraceCAFile ¶ added in v0.0.7
WithTraceCAFile sets an optional PEM CA path for TLS OTLP.
func WithTraceEndpoint ¶
WithTraceEndpoint sets the OTLP/gRPC collector endpoint. Only used when tracing is enabled. TLS is the default; set WithTraceInsecure(true) to admit cleartext.
func WithTraceInsecure ¶ added in v0.0.7
WithTraceInsecure admits cleartext OTLP when true. Default false (TLS).
func WithTraceSampleRatio ¶ added in v0.0.7
WithTraceSampleRatio sets head sampling for new traces (0–1, default 1.0). Invalid values fail when the tracer provider is built (Init / tracing reload).
func WithTracing ¶
WithTracing enables (default off) OpenTelemetry trace export. Tracing is off by default and only active once enabled and an endpoint is set with WithTraceEndpoint (or the loaded config's trace_endpoint).