config

package
v3.24.0 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2023 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Overview

Package config wraps Viper. It also allows to set a struct with defaults and generates pflags

Index

Constants

View Source
const TimeFormat = time.RFC3339Nano

TimeFormat is the format to parse times in.

Variables

View Source
var DefaultOptions = []Option{
	EnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_")),
	WithConfigFileFlag("config"),
}

DefaultOptions are the default options.

Functions

This section is empty.

Types

type Base

type Base struct {
	Config       []string            `name:"config" shorthand:"c" description:"Location of the config files"`
	Log          Log                 `name:"log"`
	Experimental experimental.Config `name:"experimental"`
}

Base represents base component configuration.

type BlobConfig

type BlobConfig struct {
	Provider string          `name:"provider" description:"Blob store provider (local, aws, gcp, azure)"`
	Local    BlobConfigLocal `name:"local"`
	AWS      BlobConfigAWS   `name:"aws"`
	GCP      BlobConfigGCP   `name:"gcp"`
	Azure    BlobConfigAzure `name:"azure" description:"Azure Storage configuration (EXPERIMENTAL)"`
}

BlobConfig is the blob store configuration.

func (BlobConfig) Bucket

func (c BlobConfig) Bucket(
	ctx context.Context, bucket string, httpClientProvider httpclient.Provider,
) (*blob.Bucket, error)

Bucket returns the requested blob bucket using the config.

func (BlobConfig) IsZero added in v3.12.0

func (c BlobConfig) IsZero() bool

IsZero returns whether conf is empty.

type BlobConfigAWS

type BlobConfigAWS struct {
	Endpoint         string `name:"endpoint" description:"S3 endpoint"`
	Region           string `name:"region" description:"S3 region"`
	AccessKeyID      string `name:"access-key-id" description:"Access key ID"`
	SecretAccessKey  string `name:"secret-access-key" description:"Secret access key"`
	SessionToken     string `name:"session-token" description:"Session token"`
	S3ForcePathStyle *bool  `name:"s3-force-path-style" description:"Force the AWS SDK to use path-style (s3://) addressing for calls to S3"` //nolint:lll
}

BlobConfigAWS is the blob store configuration for the AWS provider.

type BlobConfigAzure added in v3.16.2

type BlobConfigAzure struct {
	AccountName string `name:"account-name" description:"Azure storage account name"`
}

BlobConfigAzure is the blob store configuration for the Azure provider.

type BlobConfigGCP

type BlobConfigGCP struct {
	CredentialsFile string `name:"credentials-file" description:"Path to the GCP credentials JSON file"`
	Credentials     string `name:"credentials" description:"JSON data of the GCP credentials, if not using JSON file"`
}

BlobConfigGCP is the blob store configuration for the GCP provider.

type BlobConfigLocal

type BlobConfigLocal struct {
	Directory string `name:"directory" description:"OS filesystem directory, which contains buckets"`
}

BlobConfigLocal is the blob store configuration for the local filesystem provider.

type BlobPathConfig

type BlobPathConfig struct {
	Bucket string `name:"bucket" description:"Bucket to use"`
	Path   string `name:"path" description:"Path to use"`
}

BlobPathConfig configures the blob bucket and path.

func (BlobPathConfig) IsZero

func (c BlobPathConfig) IsZero() bool

IsZero returns whether conf is empty.

type Cache

type Cache struct {
	Service string       `name:"service" description:"Service used for caching (redis)"`
	Redis   redis.Config `name:"redis"`
}

Cache represents configuration for a caching system.

type CloudEvents

type CloudEvents struct {
	PublishURL   string `name:"publish-url" description:"URL for the topic to send events"`
	SubscribeURL string `name:"subscribe-url" description:"URL for the subscription to receiving events"`
}

CloudEvents represents configuration for the cloud events backend.

type Configurable

type Configurable interface {
	// UnmarshalConfigString parses a string into the config variable
	UnmarshalConfigString(string) error
}

Configurable is the interface for things that can be configured. Implement the interface to add custom parsing to config variables from strings. For instance, to parse a log level from the strings "fatal", "error", etc into a custom enum for log levels.

type Cookie struct {
	HashKey  []byte `name:"hash-key" description:"Key for cookie contents verification (32 or 64 bytes)"`
	BlockKey []byte `name:"block-key" description:"Key for cookie contents encryption (16, 24 or 32 bytes)"`
}

Cookie represents cookie configuration. These 128, 192 or 256 bit keys are used to verify and encrypt cookies set by the web server. Make sure that all instances of a cluster use the same keys. Changing these keys will result in all sessions being invalidated.

type Events

type Events struct {
	Backend string      `name:"backend" description:"Backend to use for events (internal, redis, cloud)"`
	Redis   RedisEvents `name:"redis"`
	Cloud   CloudEvents `name:"cloud"`
}

Events represents configuration for the events system.

type FrequencyPlansConfig

type FrequencyPlansConfig struct {
	ConfigSource string            `name:"config-source" description:"Source of the frequency plans (static, directory, url, blob)"` //nolint:lll
	Static       map[string][]byte `name:"-"`
	Directory    string            `name:"directory" description:"OS filesystem directory, which contains frequency plans"` //nolint:lll
	URL          string            `name:"url" description:"URL, which contains frequency plans"`
	Blob         BlobPathConfig    `name:"blob"`
}

FrequencyPlansConfig contains the source of the frequency plans.

func (FrequencyPlansConfig) Fetcher

func (c FrequencyPlansConfig) Fetcher(
	ctx context.Context, blobConf BlobConfig, httpClientProvider httpclient.Provider,
) (fetch.Interface, error)

Fetcher returns a fetch.Interface based on the configuration. If no configuration source is set, this method returns nil, nil.

type GRPC

type GRPC struct {
	AllowInsecureForCredentials bool `name:"allow-insecure-for-credentials" description:"Allow transmission of credentials over insecure transport"` //nolint:lll

	Listen    string `name:"listen" description:"Address for the TCP gRPC server to listen on"`
	ListenTLS string `name:"listen-tls" description:"Address for the TLS gRPC server to listen on"`

	TrustedProxies []string `name:"trusted-proxies" description:"CIDRs of trusted reverse proxies"`

	LogIgnoreMethods []string `name:"log-ignore-methods" description:"List of paths for which successful requests will not be logged"` //nolint:lll
}

GRPC represents gRPC listener configuration.

type HTTP

type HTTP struct {
	Listen          string           `name:"listen" description:"Address for the HTTP server to listen on"`
	ListenTLS       string           `name:"listen-tls" description:"Address for the HTTPS server to listen on"`
	TrustedProxies  []string         `name:"trusted-proxies" description:"CIDRs of trusted reverse proxies"`
	RedirectToHost  string           `name:"redirect-to-host" description:"Redirect all requests to one host"`
	RedirectToHTTPS bool             `name:"redirect-to-tls" description:"Redirect HTTP requests to HTTPS"`
	LogIgnorePaths  []string         `name:"log-ignore-paths" description:"List of paths for which successful requests will not be logged"` //nolint:lll
	Static          HTTPStaticConfig `name:"static"`
	Cookie          Cookie           `name:"cookie"`
	PProf           PProf            `name:"pprof"`
	Metrics         Metrics          `name:"metrics"`
	Health          Health           `name:"health"`
}

HTTP represents the HTTP and HTTPS server configuration.

type HTTPStaticConfig

type HTTPStaticConfig struct {
	Mount      string   `name:"mount" description:"Path on the server where static assets will be served"`
	SearchPath []string `name:"search-path" description:"List of paths for finding the directory to serve static assets from"` //nolint:lll
}

HTTPStaticConfig represents the HTTP static file server configuration.

type Health

type Health struct {
	Enable   bool   `name:"enable" description:"Enable health check endpoint on HTTP server"`
	Password string `name:"password" description:"Password to protect health endpoint (username is health)"`
}

Health represents the health checks configuration.

type InteropClient

type InteropClient struct {
	ConfigSource string         `name:"config-source" description:"Source of the interoperability client configuration (directory, url, blob)"` //nolint:lll
	Directory    string         `name:"directory" description:"OS filesystem directory, which contains interoperability client configuration"`  //nolint:lll
	URL          string         `name:"url" description:"URL, which contains interoperability client configuration"`
	Blob         BlobPathConfig `name:"blob"`

	BlobConfig BlobConfig `name:"-"`
}

InteropClient represents the client-side interoperability through LoRaWAN Backend Interfaces configuration.

func (InteropClient) Fetcher

func (c InteropClient) Fetcher(ctx context.Context, httpClientProvider httpclient.Provider) (fetch.Interface, error)

Fetcher returns fetch.Interface defined by conf. If no configuration source is set, this method returns nil, nil.

func (InteropClient) IsZero

func (c InteropClient) IsZero() bool

IsZero returns whether conf is empty.

type InteropServer

type InteropServer struct {
	Listen           string `name:"listen" description:"Address for the interop server for LoRaWAN Backend Interfaces to listen on"`         //nolint:lll
	ListenTLS        string `name:"listen-tls" description:"TLS address for the interop server for LoRaWAN Backend Interfaces to listen on"` //nolint:lll
	PublicTLSAddress string `name:"public-tls-address" description:"Public address of the interop server for LoRaWAN Backend Interfaces"`    //nolint:lll

	SenderClientCA           SenderClientCA    `name:"sender-client-ca" description:"Client CAs for sender IDs to trust (DEPRECATED)"`                               //nolint:lll
	SenderClientCADeprecated map[string]string `name:"sender-client-cas" description:"Path to PEM encoded file with client CAs of sender IDs to trust (DEPRECATED)"` //nolint:lll

	PacketBroker PacketBrokerInteropAuth `name:"packet-broker"`
}

InteropServer represents the server-side interoperability through LoRaWAN Backend Interfaces configuration.

type KeyVault

type KeyVault struct {
	Provider string            `name:"provider" description:"Provider (static)"`
	Cache    KeyVaultCache     `name:"cache"`
	Static   map[string][]byte `name:"static"`
}

KeyVault represents configuration for key vaults.

func (KeyVault) ComponentKEKLabeler added in v3.24.0

func (v KeyVault) ComponentKEKLabeler() (crypto.ComponentKEKLabeler, error)

ComponentKEKLabeler returns an initialized crypto.ComponentKEKLabeler based on the configuration.

func (KeyVault) KeyService added in v3.24.0

func (v KeyVault) KeyService(ctx context.Context, httpClientProvider httpclient.Provider) (crypto.KeyService, error)

KeyService returns an initialized crypto.KeyService based on the configuration.

type KeyVaultCache added in v3.9.0

type KeyVaultCache struct {
	Size int           `name:"size" description:"Cache size. Caching is disabled if size is 0"`
	TTL  time.Duration `name:"ttl" description:"Cache elements time to live. No expiration mechanism is used if TTL is 0"`
}

KeyVaultCache represents the configuration for key vault caching.

type Log

type Log struct {
	Format string    `name:"format" description:"Log format to write (console, json)"`
	Level  log.Level `name:"level" description:"The minimum level log messages must have to be shown"`
}

Log represents configuration for the logger.

type MQTT

type MQTT struct {
	Listen           string `name:"listen" description:"Address for the MQTT frontend to listen on"`
	ListenTLS        string `name:"listen-tls" description:"Address for the MQTTS frontend to listen on"`
	PublicAddress    string `name:"public-address" description:"Public address of the MQTT frontend"`
	PublicTLSAddress string `name:"public-tls-address" description:"Public address of the MQTTs frontend"`
}

MQTT contains the listen and public addresses of an MQTT frontend.

type MQTTConfigProvider

type MQTTConfigProvider interface {
	GetMQTTConfig(context.Context) (*MQTT, error)
}

MQTTConfigProvider provides contextual access to MQTT configuration.

type MQTTConfigProviderFunc

type MQTTConfigProviderFunc func(context.Context) (*MQTT, error)

MQTTConfigProviderFunc is a functional MQTTConfigProvider.

func (MQTTConfigProviderFunc) GetMQTTConfig

func (f MQTTConfigProviderFunc) GetMQTTConfig(ctx context.Context) (*MQTT, error)

GetMQTTConfig implements MQTTConfigProvider.

type Manager

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

Manager is a manager for the configuration.

func Initialize

func Initialize(name, envPrefix string, defaults interface{}, opts ...Option) *Manager

Initialize a new config manager with the given name and defaults.

The defaults should be a struct with fields that define the possible config flags by setting the struct tags.

Possible struct tags are:

  • `name:"<name>"`: Defines the name of the config flag, in the environment, on the command line and in the config files.
  • `shorthand:"<n>"`: Defines a shorthand name for use on the command line.
  • `description:"<description>"`: Add a description that will be printed in the command's help message.
  • `file-only:"<true|false>"` Denotes wether or not to attempt to parse this variable from the command line and environment or only from the config file. This can be used to allow complicated types to exist in the config file but not on the command line.

The type of the struct fields also defines their type when parsing the config file, command line arguments or environment variables. Currently, the following types are supported:

  • `bool`
  • `int`, `int8`, `int16`, `int32`, `int64`
  • `uint`, `uint8`, `uint16`, `uint32`, `uint64`
  • `float32`, `float64`
  • `string`
  • `time.Time`: Parsed according to the TimeFormat variable set in this package
  • `time.Duration`: Parsed by `time.ParseDuration`
  • `[]string`: Parsed by splitting on whitespace or by passing multiple flags VAR="a b c" or --var a --var b --var c
  • `map[string]string`: Parsed by key=val pairs VAR="k=v q=r" or --var k=v --var q=r
  • `map[string][]byte`: Parsed by key=val pairs, val must be hex VAR="k=0x01 q=0x02" or --var k=0x01 --var q=0x02
  • `map[string][]string`: Parsed by key=val pairs where keys are repeated VAR="k=v1 k=v2 q=r" or --var k=v1 --var k=v2 --var q=r
  • `Configurable`: Parsed by the UnmarshalConfigString method
  • structs with fields of these types: The nested config names will be prefixed by the name of this struct, unless it is `name:",squash"` in which case the names are merged into the parent struct.

func InitializeWithDefaults

func InitializeWithDefaults(name, envPrefix string, defaults interface{}, opts ...Option) *Manager

InitializeWithDefaults is the same as Initialize but it sets some sane default options (see DefaultOptions) alongside the passed in options.

func (*Manager) AllEnvironment

func (m *Manager) AllEnvironment() []string

AllEnvironment returns all environment variables.

func (*Manager) AllKeys

func (m *Manager) AllKeys() []string

AllKeys returns all keys holding a value, regardless of where they are set. Nested keys are returned with a "." separator.

func (*Manager) EnvironmentForKey

func (m *Manager) EnvironmentForKey(key string) string

EnvironmentForKey returns the name of the environment variable for the given config key.

func (*Manager) Flags

func (m *Manager) Flags() *pflag.FlagSet

Flags to be used in the command.

func (*Manager) Get

func (m *Manager) Get(key string) interface{}

Get returns the current value of the given config key.

func (*Manager) Parse

func (m *Manager) Parse(flags ...string) error

Parse parses the command line arguments.

func (*Manager) ReadInConfig

func (m *Manager) ReadInConfig() error

ReadInConfig will read in all defined config files (according to the config file flag set by WithConfigFileFlag). The parsed config files will be merged into the config struct.

func (*Manager) Unmarshal

func (m *Manager) Unmarshal(result interface{}) error

Unmarshal unmarshals the available config keys into the result. It matches the names of fields based on the name struct tag.

func (*Manager) UnmarshalKey

func (m *Manager) UnmarshalKey(key string, raw interface{}) error

UnmarshalKey unmarshals a specific key into a destination, which must have a matching type. This is useful for fields which have the `file-only:"true"` tag set and so are ignored when Unmarshalling them to a struct.

func (*Manager) WithConfig

func (m *Manager) WithConfig(defaults interface{}) *pflag.FlagSet

WithConfig returns a new flagset with has the flags of the Manager as well as the additional flags defined from the defaults passed along. Use this to build derived flagsets with a shared base config (for instance with cobra).

type Metrics

type Metrics struct {
	Enable   bool   `name:"enable" description:"Enable metrics endpoint on HTTP server"`
	Password string `name:"password" description:"Password to protect metrics endpoint (username is metrics)"`
}

Metrics represents the metrics endpoint configuration.

type Option

type Option func(m *Manager)

Option is the type of an option for the manager.

func EnvKeyReplacer

func EnvKeyReplacer(r *strings.Replacer) Option

EnvKeyReplacer sets the strings.Replacer for mapping mapping an environment variables to a key that does not match them.

func WithConfigFileFlag

func WithConfigFileFlag(flag string) Option

WithConfigFileFlag is an option for the manager that automatically enables the config file flag and tries to infer it from the working directory, user home directory and user configuration directory. The Option can only be used once.

func WithDeprecatedFlag

func WithDeprecatedFlag(name, usageMessage string) Option

WithDeprecatedFlag marks a flag as deprecated with the given message.

type PProf

type PProf struct {
	Enable   bool   `name:"enable" description:"Enable pprof endpoint on HTTP server"`
	Password string `name:"password" description:"Password to protect pprof endpoint (username is pprof)"`
}

PProf represents the pprof endpoint configuration.

type PacketBrokerInteropAuth added in v3.15.2

type PacketBrokerInteropAuth struct {
	Enabled     bool   `name:"enabled" description:"Enable Packet Broker to authenticate"`
	TokenIssuer string `name:"token-issuer" description:"Required issuer of Packet Broker tokens"`
}

PacketBrokerInteropAuth respresents Packet Broker authentication configuration.

type RateLimiting added in v3.13.0

type RateLimiting struct {
	ConfigSource string         `name:"config-source" description:"Source of rate-limiting.yml (directory, url, blob)"`
	Directory    string         `name:"directory" description:"OS filesystem directory, which contains rate limiting configuration"` //nolint:lll
	URL          string         `name:"url" description:"URL, which contains rate limiting configuration"`
	Blob         BlobPathConfig `name:"blob"`

	Memory   RateLimitingMemory    `name:"memory" description:"In-memory rate limiting store configuration"`
	Profiles []RateLimitingProfile `name:"profiles" description:"Rate limiting profiles"`
}

RateLimiting represents configuration for rate limiting.

func (RateLimiting) Fetcher added in v3.13.0

func (c RateLimiting) Fetcher(
	ctx context.Context, blobConf BlobConfig, httpClientProvider httpclient.Provider,
) (fetch.Interface, error)

Fetcher returns fetch.Interface defined by conf. If no configuration source is set, this method returns nil, nil.

type RateLimitingMemory added in v3.13.0

type RateLimitingMemory struct {
	MaxSize uint `name:"max-size" description:"Maximum store size for the rate limiter"`
}

RateLimitingMemory represents configuration for the in-memory rate limiting store.

type RateLimitingProfile added in v3.13.0

type RateLimitingProfile struct {
	Name         string   `name:"name" description:"Rate limiting class name"`
	MaxPerMin    uint     `name:"max-per-min" yaml:"max-per-min" description:"Maximum allowed rate (per minute)"`
	MaxBurst     uint     `name:"max-burst" yaml:"max-burst" description:"Maximum rate allowed for short bursts"`
	Associations []string `name:"associations" description:"List of classes to apply this profile on"`
}

RateLimitingProfile represents configuration for a rate limiting class.

type RedisEvents added in v3.13.0

type RedisEvents struct {
	redis.Config `name:",squash"`
	Store        struct {
		Enable              bool          `name:"enable" description:"Enable events store"`
		TTL                 time.Duration `name:"ttl" description:"How long event payloads are retained"`
		EntityCount         int           `name:"entity-count" description:"How many events are indexed for a entity ID"`
		EntityTTL           time.Duration `name:"entity-ttl" description:"How long events are indexed for a entity ID"`
		CorrelationIDCount  int           `name:"correlation-id-count" description:"How many events are indexed for a correlation ID"`     //nolint:lll
		StreamPartitionSize int           `name:"stream-partition-size" description:"How many streams to listen to in a single partition"` //nolint:lll
	} `name:"store"`
	Workers int `name:"workers"`
	Publish struct {
		QueueSize  int `name:"queue-size" description:"The maximum number of events which may be queued for publication"`
		MaxWorkers int `name:"max-workers" description:"The maximum number of workers which may publish events asynchronously"` //nolint:lll
	} `name:"publish"`
}

RedisEvents represents configuration for the Redis events backend.

type Rights

type Rights struct {
	// TTL is the duration that entries will remain in the cache before being
	// garbage collected.
	TTL time.Duration `name:"ttl" description:"Validity of Identity Server responses"`
}

Rights represents the configuration to apply when fetching entity rights.

type SenderClientCA

type SenderClientCA struct {
	Source    string            `name:"source" description:"Source of the sender client CA configuration (static, directory, url, blob)"` //nolint:lll
	Static    map[string][]byte `name:"-"`
	Directory string            `name:"directory" description:"OS filesystem directory, which contains sender client CA configuration"` //nolint:lll
	URL       string            `name:"url" description:"URL, which contains sender client CA configuration"`
	Blob      BlobPathConfig    `name:"blob"`

	BlobConfig BlobConfig `name:"-"`
}

SenderClientCA is the sender client CA configuration.

func (SenderClientCA) Fetcher

func (c SenderClientCA) Fetcher(ctx context.Context, httpClientProvider httpclient.Provider) (fetch.Interface, error)

Fetcher returns fetch.Interface defined by conf. If no configuration source is set, this method returns nil, nil.

type Sentry

type Sentry struct {
	DSN         string `name:"dsn" description:"Sentry Data Source Name"`
	Environment string `name:"environment" description:"Environment to report to Sentry"`
}

Sentry represents configuration for error tracking using Sentry.

type ServiceBase

type ServiceBase struct {
	Base             `name:",squash"`
	Cluster          cluster.Config       `name:"cluster"`
	Cache            Cache                `name:"cache"`
	Redis            redis.Config         `name:"redis"`
	Events           Events               `name:"events"`
	GRPC             GRPC                 `name:"grpc"`
	HTTP             HTTP                 `name:"http"`
	Interop          InteropServer        `name:"interop"`
	TLS              tlsconfig.Config     `name:"tls"`
	Sentry           Sentry               `name:"sentry"`
	Blob             BlobConfig           `name:"blob"`
	FrequencyPlans   FrequencyPlansConfig `name:"frequency-plans" description:"Source of the frequency plans"`
	Rights           Rights               `name:"rights"`
	KeyVault         KeyVault             `name:"key-vault"`
	RateLimiting     RateLimiting         `name:"rate-limiting" description:"Rate limiting configuration"`
	SkipVersionCheck bool                 `name:"skip-version-check" yaml:"skip-version-check" description:"Skip version checks"` //nolint:lll
}

ServiceBase represents base service configuration.

func (ServiceBase) FrequencyPlansFetcher

func (c ServiceBase) FrequencyPlansFetcher(
	ctx context.Context, httpClientProvider httpclient.Provider,
) (fetch.Interface, error)

FrequencyPlansFetcher returns a fetch.Interface based on the frequency plans configuration. If no configuration source is set, this method returns nil, nil.

type Stringer

type Stringer interface {
	// ConfigString returns the config string representation of type
	ConfigString() string
}

Stringer is the interface for config variables that have a custom string representation. Implement next to Configurable if you want custom parsing and formatting for a type, and if the formatting needs to be different from fmt.String for some reason.

Directories

Path Synopsis
example cobra command with config.
example cobra command with config.
Package tlsconfig provides configuration for TLS clients and servers.
Package tlsconfig provides configuration for TLS clients and servers.

Jump to

Keyboard shortcuts

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