config

package
v3.10.7 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2021 License: Apache-2.0 Imports: 29 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"`
}

Base represents base component configuration.

type BlobConfig

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

BlobConfig is the blob store configuration.

func (BlobConfig) Bucket

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

Bucket returns the requested blob bucket using the config.

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"`
}

BlobConfigAWS is the blob store configuration for the AWS 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"`
}

func (BlobPathConfig) IsZero

func (c BlobPathConfig) IsZero() bool

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 DeviceRepositoryConfig

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

DeviceRepositoryConfig defines the source of the device repository.

func (DeviceRepositoryConfig) Fetcher

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

type Events

type Events struct {
	Backend string       `name:"backend" description:"Backend to use for events (internal, redis, cloud)"`
	Redis   redis.Config `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)"`
	Static       map[string][]byte `name:"-"`
	Directory    string            `name:"directory" description:"OS filesystem directory, which contains frequency plans"`
	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) (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"`

	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"`
}

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"`
	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"`
}

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)"`
	Directory    string         `name:"directory" description:"OS filesystem directory, which contains interoperability client configuration"`
	URL          string         `name:"url" description:"URL, which contains interoperability client configuration"`
	Blob         BlobPathConfig `name:"blob"`

	GetFallbackTLSConfig func(ctx context.Context) (*tls.Config, error) `name:"-"`
	BlobConfig           BlobConfig                                     `name:"-"`
}

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

func (InteropClient) Fetcher

func (c InteropClient) Fetcher(ctx context.Context) (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 {
	ListenTLS                string            `name:"listen-tls" description:"Address for the interop server to listen on"`
	SenderClientCA           SenderClientCA    `name:"sender-client-ca"`
	SenderClientCADeprecated map[string]string `` /* 145-byte string literal not displayed */
}

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) KeyVault

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

KeyVault returns an initialized crypto.KeyVault 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 {
	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. defaults should be a struct wiath 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

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 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)"`
	Static    map[string][]byte `name:"-"`
	Directory string            `name:"directory" description:"OS filesystem directory, which contains sender client CA configuration"`
	URL       string            `name:"url" description:"URL, which contains sender client CA configuration"`
	Blob      BlobPathConfig    `name:"blob"`

	BlobConfig BlobConfig `name:"-"`
}

func (SenderClientCA) Fetcher

func (c SenderClientCA) Fetcher(ctx context.Context) (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"`
}

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"`
	DeviceRepository DeviceRepositoryConfig `name:"device-repository" description:"Source of the device repository"`
	Rights           Rights                 `name:"rights"`
	KeyVault         KeyVault               `name:"key-vault"`
}

ServiceBase represents base service configuration.

func (ServiceBase) DeviceRepositoryFetcher

func (c ServiceBase) DeviceRepositoryFetcher(ctx context.Context) (fetch.Interface, error)

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

func (ServiceBase) FrequencyPlansFetcher

func (c ServiceBase) FrequencyPlansFetcher(ctx context.Context) (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.

Jump to

Keyboard shortcuts

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