Documentation
¶
Overview ¶
Package commoncfg defines the necessary types to configure the application. This minimal configuration is tailored for logging.
Index ¶
- Constants
- Variables
- func ExtractValueFromSourceRef(cred *SourceRef) ([]byte, error)
- func LoadCACertPool(certRef *SourceRef) (*x509.CertPool, error)
- func LoadCAsCertPool(certRefs []SourceRef) (*x509.CertPool, error)
- func LoadClientCertificate(certRef, keyRef *SourceRef) (*tls.Certificate, error)
- func LoadConfig[T any | BaseConfig](cfg T, defaults map[string]any, paths ...string) error
- func LoadMTLSCACertPool(cfg *MTLS) (*x509.CertPool, error)
- func LoadMTLSClientCertificate(cfg *MTLS) (*tls.Certificate, error)
- func LoadMTLSConfig(cfg *MTLS) (*tls.Config, error)
- func LoadValueFromSourceRef(cred SourceRef) ([]byte, error)
- func UpdateComponentsOfBuildInfo(cfg *BaseConfig, components ...string) error
- func UpdateConfigVersion(cfg *BaseConfig, buildInfo string) error
- type Application
- type Audit
- type BaseConfig
- type BasicAuth
- type BuildInfo
- type Component
- type CredentialFile
- type FeatureGates
- type FileFormat
- type Flags
- type GRPCClient
- type GRPCClientAttributes
- type GRPCPool
- type GRPCServer
- type GRPCServerAttributes
- type HTTPClient
- type HTTPTransportAttributes
- type Loader
- type Log
- type Logger
- type LoggerFields
- type LoggerFieldsMasking
- type LoggerFormat
- type LoggerFormatter
- type LoggerOTel
- type LoggerTime
- type LoggerTimeType
- type MTLS
- type Metric
- type OAuth2
- type OAuth2ClientAuthMethod
- type OAuth2Credentials
- type Option
- type Prometheus
- type Protocol
- type SecretRef
- type SecretType
- type SourceRef
- type SourceValueType
- type Status
- type TLSAttributes
- type Telemetry
- type Trace
Constants ¶
const ( AttrService = "service" AttrLabels = "labels" AttrName = "name" AttrServiceName = "serviceName" AttrRequestID = "requestId" AttrOperation = "operation" AttrEnvironment = "environment" )
const ( JSONLoggerFormat LoggerFormat = "json" TextLoggerFormat LoggerFormat = "text" 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" YAMLFileFormat FileFormat = "yaml" BinaryFileFormat FileFormat = "binary" OAuth2ClientSecretBasic OAuth2ClientAuthMethod = "basic" // Basic auth header OAuth2ClientSecretPost OAuth2ClientAuthMethod = "post" // POST body OAuth2ClientSecretJWT OAuth2ClientAuthMethod = "jwt" // JWT signed w/ HMAC(secret) OAuth2PrivateKeyJWT OAuth2ClientAuthMethod = "private" // JWT signed w/ private key OAuth2None OAuth2ClientAuthMethod = "none" // PKCE public clients )
const ( DefaultFileName = "config" DefaultFileFormat = YAMLFileFormat )
Variables ¶
var ( ErrMTLSIsNil = errors.New("missing mTLS configuration: value is nil") ErrCertificateIsNil = errors.New("missing certificate configuration: value is nil") ErrKeyCertificateIsNil = errors.New("missing key certificate configuration: value is nil") )
var ErrFeatureNotFound = errors.New("feature not found")
Functions ¶
func ExtractValueFromSourceRef ¶ added in v1.2.4
func LoadCACertPool ¶ added in v1.5.0
func LoadCAsCertPool ¶ added in v1.13.0
func LoadClientCertificate ¶ added in v1.5.0
func LoadClientCertificate(certRef, keyRef *SourceRef) (*tls.Certificate, error)
func LoadConfig ¶
LoadConfig is a convenience function to load the config file from the specified paths
func LoadMTLSCACertPool ¶ added in v1.2.0
func LoadMTLSClientCertificate ¶ added in v1.2.0
func LoadMTLSClientCertificate(cfg *MTLS) (*tls.Certificate, error)
func LoadValueFromSourceRef ¶
func UpdateComponentsOfBuildInfo ¶ added in v1.6.1
func UpdateComponentsOfBuildInfo(cfg *BaseConfig, components ...string) 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"`
HTTPClient HTTPClient `yaml:"httpClient" json:"httpClient"`
// 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 {
Component `mapstructure:",squash" yaml:",inline"`
Components []Component `json:"components,omitempty"`
}
BuildInfo holds metadata about the build
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
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 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 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 HTTPClient ¶ added in v1.5.0
type HTTPClient struct {
Timeout time.Duration `yaml:"timeout" json:"timeout" default:"10s"`
//Deprecated [to be replaced by using MTLS]
RootCAs *SourceRef `yaml:"rootCAs" json:"rootCAs"`
//Deprecated [to be replaced by using MTLS]
InsecureSkipVerify bool `yaml:"insecureSkipVerify" json:"insecureSkipVerify"`
//Deprecated [to be replaced by using MTLS]
MinVersion uint16 `yaml:"minVersion" json:"minVersion"`
//Deprecated [to be replaced by using MTLS]
Cert *SourceRef `yaml:"cert" json:"cert"`
//Deprecated [to be replaced by using MTLS]
CertKey *SourceRef `yaml:"certKey" json:"certKey"`
APIToken *SourceRef `yaml:"apiToken" json:"apiToken"`
BasicAuth *BasicAuth `yaml:"basicAuth" json:"basicAuth"`
OAuth2Auth *OAuth2 `yaml:"oauth2Auth" json:"oauth2Auth"`
MTLS *MTLS `yaml:"mtls" json:"mtls"`
TransportAttributes *HTTPTransportAttributes `yaml:"transportAttributes" json:"transportAttributes"`
}
type HTTPTransportAttributes ¶ added in v1.13.0
type HTTPTransportAttributes struct {
// TLSHandshakeTimeout specifies the maximum amount of time to
// wait for a TLS handshake. Zero means no timeout.
TLSHandshakeTimeout time.Duration `yaml:"tlsHandshakeTimeout" json:"tlsHandshakeTimeout" default:"0s"`
// DisableKeepAlives, if true, disables HTTP keep-alives and
// will only use the connection to the server for a single
// HTTP request.
//
// This is unrelated to the similarly named TCP keep-alives.
DisableKeepAlives bool `yaml:"disableKeepAlives" json:"disableKeepAlives"`
// DisableCompression, if true, prevents the Transport from
// requesting compression with an "Accept-Encoding: gzip"
// request header when the Request contains no existing
// Accept-Encoding value. If the Transport requests gzip on
// its own and gets a gzipped response, it's transparently
// decoded in the Response.Body. However, if the user
// explicitly requested gzip it is not automatically
// uncompressed.
DisableCompression bool `yaml:"disableCompression" json:"disableCompression"`
// MaxIdleConns controls the maximum number of idle (keep-alive)
// connections across all hosts. Zero means no limit.
MaxIdleConns int `yaml:"maxIdleConns" json:"maxIdleConns" default:"0"`
// MaxIdleConnsPerHost, if non-zero, controls the maximum idle
// (keep-alive) connections to keep per-host. If zero,
// DefaultMaxIdleConnsPerHost is used.
MaxIdleConnsPerHost int `yaml:"maxIdleConnsPerHost" json:"maxIdleConnsPerHost" default:"0"`
// MaxConnsPerHost optionally limits the total number of
// connections per host, including connections in the dialing,
// active, and idle states. On limit violation, dials will block.
//
// Zero means no limit.
MaxConnsPerHost int `yaml:"maxConnsPerHost" json:"maxConnsPerHost" default:"0"`
// IdleConnTimeout is the maximum amount of time an idle
// (keep-alive) connection will remain idle before closing
// itself.
// Zero means no limit.
IdleConnTimeout time.Duration `yaml:"idleConnTimeout" json:"idleConnTimeout" default:"0s"`
// ResponseHeaderTimeout, if non-zero, specifies the amount of
// time to wait for a server's response headers after fully
// writing the request (including its body, if any). This
// time does not include the time to read the response body.
ResponseHeaderTimeout time.Duration `yaml:"responseHeaderTimeout" json:"responseHeaderTimeout" default:"0s"`
// ExpectContinueTimeout, if non-zero, specifies the amount of
// time to wait for a server's first response headers after fully
// writing the request headers if the request has an
// "Expect: 100-continue" header. Zero means no timeout and
// causes the body to be sent immediately, without
// waiting for the server to approve.
// This time does not include the time to send the request header.
ExpectContinueTimeout time.Duration `yaml:"expectContinueTimeout" json:"expectContinueTimeout" default:"0s"`
}
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 (*Loader) LoadConfig ¶
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 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"`
RootCAs []SourceRef `yaml:"rootCAs,omitempty" json:"rootCAs,omitempty"`
Attributes *TLSAttributes `yaml:"attributes" json:"attributes"`
}
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 OAuth2ClientAuthMethod ¶ added in v1.6.2
type OAuth2ClientAuthMethod string
All supported OAuth2 client authentication methods. Based on OAuth2 RFC6749, JWT RFC7523 and OIDC specs.
type OAuth2Credentials ¶ added in v1.2.3
type OAuth2Credentials struct {
ClientID SourceRef `yaml:"clientID" json:"clientID"`
AuthMethod OAuth2ClientAuthMethod `yaml:"authMethod" json:"authMethod" default:"post"`
// Option A: client_secret authentication
ClientSecret *SourceRef `yaml:"clientSecret,omitempty" json:"clientSecret,omitempty"`
// Option B: private_key_jwt authentication (RFC 7523)
ClientAssertionType *SourceRef `yaml:"clientAssertionType,omitempty" json:"clientAssertionType,omitempty"`
ClientAssertion *SourceRef `yaml:"clientAssertion,omitempty" json:"clientAssertion,omitempty"`
}
type Option ¶
type Option func(*Loader)
func WithDefaults ¶
WithDefaults sets the default values for the config loader
func WithEnvOverride ¶
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 WithFile ¶ added in v1.4.6
func WithFile(name string, extension FileFormat) Option
WithFile sets the file name and type of the config file
type Prometheus ¶
type Prometheus struct {
Enabled bool `yaml:"enabled" json:"enabled"`
}
Prometheus defines configuration for Prometheus integration.
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" default:"embedded"`
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"`
// Timeout defines a timeout duration for all checks
Timeout time.Duration `yaml:"timeout" json:"timeout" default:"10s"`
// Status.Profiling enables profiling on the status server
Profiling bool `yaml:"profiling" json:"profiling"`
}
type TLSAttributes ¶ added in v1.13.0
type TLSAttributes struct {
// InsecureSkipVerify controls whether a client verifies the server's
// certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
// accepts any certificate presented by the server and any host name in that
// certificate. In this mode, TLS is susceptible to machine-in-the-middle
// attacks unless custom verification is used. This should be used only for
// testing or in combination with VerifyConnection or VerifyPeerCertificate.
InsecureSkipVerify bool `yaml:"insecureSkipVerify" json:"insecureSkipVerify"`
// ServerName is used to verify the hostname on the returned
// certificates unless InsecureSkipVerify is given. It is also included
// in the client's handshake to support virtual hosting unless it is
// an IP address.
ServerName string `yaml:"serverName" json:"serverName"`
// SessionTicketsDisabled may be set to true to disable session ticket and
// PSK (resumption) support. Note that on clients, session ticket support is
// also disabled if ClientSessionCache is nil.
SessionTicketsDisabled bool `yaml:"sessionTicketsDisabled" json:"sessionTicketsDisabled"`
// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
// When true, the largest possible TLS record size is always used. When
// false, the size of TLS records may be adjusted in an attempt to
// improve latency.
DynamicRecordSizingDisabled bool `yaml:"dynamicRecordSizingDisabled" json:"dynamicRecordSizingDisabled"`
}
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.