commoncfg

package
v1.4.5 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2025 License: Apache-2.0 Imports: 14 Imported by: 7

Documentation

Overview

Package common defines the necessary types to configure the application. This minimal configuration is tailored for logging.

Index

Constants

View Source
const (
	AttrService     = "service"
	AttrLabels      = "labels"
	AttrName        = "name"
	AttrServiceName = "serviceName"
	AttrRequestID   = "requestId"
	AttrOperation   = "operation"
	AttrEnvironment = "environment"
)
View Source
const (
	// Logger format types.
	JSONLoggerFormat LoggerFormat = "json"
	TextLoggerFormat LoggerFormat = "text"

	// Logger time types.
	UnixTimeLogger    LoggerTimeType = "unix"
	PatternTimeLogger LoggerTimeType = "pattern"

	GRPCProtocol Protocol = "grpc"
	HTTPProtocol Protocol = "http"

	InsecureSecretType SecretType = "insecure"
	MTLSSecretType     SecretType = "mtls"
	ApiTokenSecretType SecretType = "api-token"
	BasicSecretType    SecretType = "basic"
	OAuth2SecretType   SecretType = "oauth2"

	EmbeddedSourceValue SourceValueType = "embedded"
	EnvSourceValue      SourceValueType = "env"
	FileSourceValue     SourceValueType = "file"

	JSONFileFormat   FileFormat = "json"
	BinaryFileFormat FileFormat = "binary"
)

Variables

View Source
var (
	ErrFeatureNotFound = errors.New("feature not found")
)

Functions

func ExtractValueFromSourceRef added in v1.2.4

func ExtractValueFromSourceRef(cred *SourceRef) ([]byte, error)

func LoadConfig

func LoadConfig[T any | BaseConfig](cfg T, defaults map[string]any, paths ...string) error

LoadConfig is a convenience function to load the config file from the specified paths

func LoadMTLSCACertPool added in v1.2.0

func LoadMTLSCACertPool(cfg *MTLS) (*x509.CertPool, error)

func LoadMTLSClientCertificate added in v1.2.0

func LoadMTLSClientCertificate(cfg *MTLS) (*tls.Certificate, error)

func LoadMTLSConfig added in v1.3.0

func LoadMTLSConfig(cfg *MTLS) (*tls.Config, error)

func LoadValueFromSourceRef

func LoadValueFromSourceRef(cred SourceRef) ([]byte, error)

func UpdateConfigVersion

func UpdateConfigVersion(cfg *BaseConfig, buildInfo string) error

Types

type Application

type Application struct {
	Name             string            `yaml:"name" json:"name"`
	Environment      string            `yaml:"environment" json:"environment"`
	Labels           map[string]string `yaml:"labels" json:"labels"`
	BuildInfo        BuildInfo
	RuntimeBuildInfo *debug.BuildInfo
}

Application holds minimal application configuration.

type Audit

type Audit struct {
	Endpoint string `yaml:"endpoint" json:"endpoint"`
	// Potential mTLS for the endpoint.
	MTLS *MTLS `yaml:"mtls" json:"mtls"`
	// Potential BasicAuth for the endpoint.
	BasicAuth *BasicAuth `yaml:"basicAuth" json:"basicAuth"`
	// Optional set of additional properties to be added to OTLP log object. Must be added as a literal string to maintain casing.
	AdditionalProperties string `yaml:"additionalProperties" json:"additionalProperties"`
}

Audit holds the audit log library configuration.

type BaseConfig

type BaseConfig struct {
	Application  Application  `yaml:"application" json:"application"`
	FeatureGates FeatureGates `yaml:"featureGates" json:"featureGates"`
	Status       Status       `yaml:"status" json:"status"`
	Logger       Logger       `yaml:"logger" json:"logger"`
	Telemetry    Telemetry    `yaml:"telemetry" json:"telemetry"`
	Audit        Audit        `yaml:"audit" json:"audit"`
}

type BasicAuth

type BasicAuth struct {
	Username SourceRef `yaml:"username" json:"username"`
	Password SourceRef `yaml:"password" json:"password"`
}

BasicAuth holds basic auth configuration for audit library.

type BuildInfo

type BuildInfo struct {
	Branch    string `json:"branch"`
	Org       string `json:"org"`
	Product   string `json:"product"`
	Repo      string `json:"repo"`
	SHA       string `json:"sha"`
	Version   string `json:"version"`
	BuildTime string `json:"buildTime"`
	// contains filtered or unexported fields
}

BuildInfo holds metadata about the build

func (*BuildInfo) String

func (bi *BuildInfo) String() string

type CredentialFile

type CredentialFile struct {
	Path     string     `yaml:"path" json:"path"`
	Format   FileFormat `yaml:"format" json:"format"`
	JSONPath string     `yaml:"jsonPath" json:"jsonPath"`
}

CredentialFile describes a file-based credential.

type FeatureGates added in v1.1.1

type FeatureGates map[string]bool

FeatureGates are a set of key=value pairs that describe service features.

func (FeatureGates) Feature added in v1.1.1

func (fg FeatureGates) Feature(feature string) (bool, error)

func (FeatureGates) IsFeatureEnabled added in v1.1.1

func (fg FeatureGates) IsFeatureEnabled(feature string) bool

type FileFormat

type FileFormat string

FileFormat represents the format of a file.

type Flags added in v1.0.0

type Flags struct {
	// Reflection is a protocol that gRPC servers can use to declare the protobuf-defined APIs.
	// Reflection is used by debugging tools like grpcurl or grpcui.
	// See https://grpc.io/docs/guides/reflection/.
	Reflection bool `yaml:"reflection" json:"reflection"`
	Health     bool `yaml:"health" json:"health"`
}

type GRPCClient

type GRPCClient struct {
	Enabled    bool                 `yaml:"enabled" json:"enabled"`
	Address    string               `yaml:"address" json:"address"`
	Attributes GRPCClientAttributes `yaml:"attributes" json:"attributes"`
	Pool       GRPCPool             `yaml:"pool" json:"pool"`
	SecretRef  *SecretRef           `yaml:"secretRef" json:"secretRef"`
}

GRPCClient specifies the gRPC client configuration e.g. used by the gRPC health check client.

type GRPCClientAttributes

type GRPCClientAttributes struct {
	//  GRPC KeepaliveTime option
	KeepaliveTime time.Duration `yaml:"keepaliveTime" json:"keepaliveTime" default:"80s"`
	//  GRPC KeepaliveTimeout option
	KeepaliveTimeout time.Duration `yaml:"keepaliveTimeout" json:"keepaliveTimeout" default:"40s"`
}

type GRPCPool added in v1.0.0

type GRPCPool struct {
	InitialCapacity int           `yaml:"initialCapacity" json:"initialCapacity" default:"1"`
	MaxCapacity     int           `yaml:"maxCapacity" json:"maxCapacity" default:"1"`
	IdleTimeout     time.Duration `yaml:"idleTimeout" json:"idleTimeout" default:"5s"`
	MaxLifeDuration time.Duration `yaml:"maxLifeDuration" json:"maxLifeDuration" default:"60s"`
}

type GRPCServer

type GRPCServer struct {
	Enabled bool   `yaml:"enabled" json:"enabled"`
	Address string `yaml:"address" json:"address" default:":9092"`
	Flags   Flags  `yaml:"flags" json:"flags"`
	// MaxSendMsgSize returns a ServerOption to set the max message size in bytes the server can send.
	// If this is not set, gRPC uses the default `2147483647`.
	MaxSendMsgSize int `yaml:"maxSendMsgSize" json:"maxSendMsgSize" default:"2147483647"`
	// MaxRecvMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
	// If this is not set, gRPC uses the default 4MB.
	MaxRecvMsgSize int `yaml:"maxRecvMsgSize" json:"maxRecvMsgSize" default:"125829120"`
	// MinTime is the minimum amount of time a client should wait before sending
	// a keepalive ping.
	EfPolMinTime time.Duration `yaml:"efPolMinTime" json:"efPolMinTime" default:"180s"` // The current default value is 5 minutes.
	// If true, server allows keepalive pings even when there are no active
	// streams(RPCs). If false, and client sends ping when there are no active
	// streams, server will send GOAWAY and close the connection.
	EfPolPermitWithoutStream bool                 `yaml:"efPolPermitWithoutStream" json:"efPolPermitWithoutStream"` // false by default.
	Attributes               GRPCServerAttributes `yaml:"attributes" json:"attributes"`
}

GRPCServer specifies the gRPC server configuration e.g. used by the business gRPC server if any.

type GRPCServerAttributes

type GRPCServerAttributes struct {
	// MaxConnectionIdle is a duration for the amount of time after which an
	// idle connection would be closed by sending a GoAway. Idleness duration is
	// defined since the most recent time the number of outstanding RPCs became
	// zero or the connection establishment.
	MaxConnectionIdle time.Duration `yaml:"maxConnectionIdle" json:"maxConnectionIdle" default:"1800s"` // The current default value is infinity.
	// MaxConnectionAge is a duration for the maximum amount of time a
	// connection may exist before it will be closed by sending a GoAway. A
	// random jitter of +/-10% will be added to MaxConnectionAge to spread out
	// connection storms.
	MaxConnectionAge time.Duration `yaml:"maxConnectionAge" json:"maxConnectionAge" default:"1800s"` // The current default value is infinity.
	// MaxConnectionAgeGrace is an additive period after MaxConnectionAge after
	// which the connection will be forcibly closed.
	MaxConnectionAgeGrace time.Duration `yaml:"maxConnectionAgeGrace" json:"maxConnectionAgeGrace" default:"300s"` // The current default value is infinity.
	// After a duration of this time if the server doesn't see any activity it
	// pings the client to see if the transport is still alive.
	// If set below 1s, a minimum value of 1s will be used instead.
	Time time.Duration `yaml:"time" json:"time" default:"120m"` // The current default value is 2 hours.
	// After having pinged for keepalive check, the server waits for a duration
	// of Timeout and if no activity is seen even after that the connection is
	// closed.
	Timeout time.Duration `yaml:"timeout" json:"timeout" default:"20s"` // The current default value is 20 seconds.
}

type Loader

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

Loader is used to load configuration from a `config.yaml` file. It supports loading from multiple paths and can override values with environment variables. It is instantiated by using the NewLoader function that supports multiple options.

func NewLoader

func NewLoader(cfg any, options ...Option) *Loader

NewLoader creates a new config loader

func (*Loader) LoadConfig

func (l *Loader) LoadConfig() error

LoadConfig loads the config from the specified paths and environment variables

type Log

type Log struct {
	Enabled   bool      `yaml:"enabled" json:"enabled"`
	Protocol  Protocol  `yaml:"protocol" json:"protocol"`
	Host      SourceRef `yaml:"host" json:"host"`
	URL       string    `yaml:"url" json:"url"`
	SecretRef SecretRef `yaml:"secretRef" json:"secretRef"`
}

Log defines settings for structured logging export.

type Logger

type Logger struct {
	Source    bool            `yaml:"source" json:"source"`
	Format    LoggerFormat    `yaml:"format" json:"format" default:"json"`
	Level     string          `yaml:"level" json:"level" default:"info"`
	Formatter LoggerFormatter `yaml:"formatter" json:"formatter"`
}

Logger holds the configuration for logging.

type LoggerFields

type LoggerFields struct {
	Time    string              `yaml:"time" json:"time" default:"time"`
	Error   string              `yaml:"error" json:"error" default:"error"`
	Level   string              `yaml:"level" json:"level" default:"info"`
	Message string              `yaml:"message" json:"message" default:"msg"`
	OTel    LoggerOTel          `yaml:"otel" json:"otel"`
	Masking LoggerFieldsMasking `yaml:"masking" json:"masking"`
}

LoggerFields holds the mapping of log attributes.

type LoggerFieldsMasking

type LoggerFieldsMasking struct {
	PII   []string          `yaml:"pii" json:"pii"`
	Other map[string]string `yaml:"other" json:"other"`
}

LoggerFieldsMasking holds configuration for masking log fields.

type LoggerFormat

type LoggerFormat string

LoggerFormat is used to specify the logging format.

type LoggerFormatter

type LoggerFormatter struct {
	Time   LoggerTime   `yaml:"time" json:"time"`
	Fields LoggerFields `yaml:"fields" json:"fields"`
}

LoggerFormatter holds the logger formatter configuration.

type LoggerOTel

type LoggerOTel struct {
	TraceID string `yaml:"traceId" json:"traceId" default:"traceId"`
	SpanID  string `yaml:"spanId" json:"spanId" default:"spanId"`
}

LoggerOtel holds configuration for the OpenTelemetry fields.

type LoggerTime

type LoggerTime struct {
	Type      LoggerTimeType `yaml:"type" json:"type" default:"unix"`
	Pattern   string         `yaml:"pattern" json:"pattern" default:"Mon Jan 02 15:04:05 -0700 2006"`
	Precision string         `yaml:"precision" json:"precision" default:"1us"`
}

LoggerTime holds configuration for the time formatting in logs.

type LoggerTimeType

type LoggerTimeType string

LoggerTimeType is used to specify the type of time formatting.

type MTLS

type MTLS struct {
	Cert     SourceRef `yaml:"cert" json:"cert"`
	CertKey  SourceRef `yaml:"certKey" json:"certKey"`
	ServerCA SourceRef `yaml:"serverCa" json:"serverCa"`
}

MTLS holds mTLS configuration for audit library.

type Metric

type Metric struct {
	Enabled    bool       `yaml:"enabled" json:"enabled"`
	Protocol   Protocol   `yaml:"protocol" json:"protocol"`
	Host       SourceRef  `yaml:"host" json:"host"`
	URL        string     `yaml:"url" json:"url"`
	SecretRef  SecretRef  `yaml:"secretRef" json:"secretRef"`
	Prometheus Prometheus `yaml:"prometheus" json:"prometheus"`
}

Metric defines settings for metrics export and Prometheus.

type OAuth2 added in v1.2.0

type OAuth2 struct {
	URL         SourceRef         `yaml:"url" json:"url"`
	Credentials OAuth2Credentials `yaml:"credentials" json:"credentials"`
	MTLS        *MTLS             `yaml:"mtls" json:"mtls"`
}

OAuth2 holds client id and secret auth configuration

type OAuth2Credentials added in v1.2.3

type OAuth2Credentials struct {
	ClientID     SourceRef  `yaml:"clientID" json:"clientID"`
	ClientSecret *SourceRef `yaml:"clientSecret" json:"clientSecret"`
}

type Option

type Option func(*Loader)

func WithDefaults

func WithDefaults(defaults map[string]any) Option

WithDefaults sets the default values for the config loader

func WithEnvOverride

func WithEnvOverride(prefix string) Option

WithEnvOverride activates the environment variable override option with an optional prefix To override a config value, the environment variable should be named as: <ENVPREFIX>_<KEY1>_<KEY2>_<KEY3>_... (all uppercase) If the prefix is not set, the environment variable should be named as: <KEY1>_<KEY2>_<KEY3>_... (all uppercase)

func WithPaths

func WithPaths(paths ...string) Option

WithPaths sets the paths where the Loader looks for the config file

type Prometheus

type Prometheus struct {
	Enabled bool `yaml:"enabled" json:"enabled"`
}

Prometheus defines configuration for Prometheus integration.

type Protocol

type Protocol string

Protocol represents the communication protocol.

type SecretRef

type SecretRef struct {
	Type     SecretType `yaml:"type" json:"type"`
	MTLS     MTLS       `yaml:"mtls" json:"mtls"`
	APIToken SourceRef  `yaml:"apiToken" json:"apiToken"`
	OAuth2   OAuth2     `yaml:"oauth2" json:"oauth2"`
	Basic    BasicAuth  `yaml:"basic" json:"basic"`
}

SecretRef defines how credentials or certificates are provided.

type SecretType

type SecretType string

SecretType defines the type of secret used for authentication.

type SourceRef

type SourceRef struct {
	Source SourceValueType `yaml:"source" json:"source"`
	Env    string          `yaml:"env" json:"env"`
	File   CredentialFile  `yaml:"file" json:"file"`
	Value  string          `yaml:"value" json:"value"`
}

SourceRef defines a reference to a source for retrieving a value.

type SourceValueType

type SourceValueType string

SourceValueType represents the source type for retrieving configuration values.

type Status

type Status struct {
	Enabled bool `yaml:"enabled" json:"enabled"`
	// Status.Address is the address to listen on for status reporting
	Address string `yaml:"address" json:"address" default:":8888"`
	// Status.Profiling enables profiling on the status server
	Profiling bool `yaml:"profiling" json:"profiling"`
}

type Telemetry

type Telemetry struct {
	DynatraceOneAgent bool   `yaml:"dynatraceOneAgent" json:"dynatraceOneAgent"`
	Traces            Trace  `yaml:"traces" json:"traces"`
	Metrics           Metric `yaml:"metrics" json:"metrics"`
	Logs              Log    `yaml:"logs" json:"logs"`
}

Telemetry defines the configuration for telemetry components.

type Trace

type Trace struct {
	Enabled   bool      `yaml:"enabled" json:"enabled"`
	Protocol  Protocol  `yaml:"protocol" json:"protocol"`
	Host      SourceRef `yaml:"host" json:"host"`
	URL       string    `yaml:"url" json:"url"`
	SecretRef SecretRef `yaml:"secretRef" json:"secretRef"`
}

Trace defines settings for distributed tracing.

Jump to

Keyboard shortcuts

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