config

package
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2025 License: AGPL-3.0 Imports: 20 Imported by: 60

Documentation

Overview

Package config , actually copied from github.com/elastic/beats

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddPathToWatch

func AddPathToWatch(path string, callback CallbackFunc)

AddPathToWatch should only be called for configuration paths

func EnableWatcher

func EnableWatcher(path string)

func GetVariable

func GetVariable(runtimeKV util.MapStr, key string) (string, bool)

func LoadEnvVariables

func LoadEnvVariables(path string) (map[string]interface{}, error)

func LoadEnvVariablesFromConfig

func LoadEnvVariablesFromConfig(configObject *Config) (map[string]interface{}, error)

func LoadFiles

func LoadFiles(paths ...string) (*ucfg.Config, error)

LoadFiles will load configs from specify files

func LoadPath

func LoadPath(folder string) (*ucfg.Config, error)

func LoadPathWithFilter

func LoadPathWithFilter(folder string, filters ...PathFilter) (*ucfg.Config, error)

func NestedRenderingTemplate

func NestedRenderingTemplate(temp string, runKv util.MapStr) string

func NewFlagOverwrite

func NewFlagOverwrite(
	set *flag.FlagSet,
	config *Config,
	name, path, def, usage string,
) *string

NewFlagOverwrite will use flags which specified

func NewTemplateVariables

func NewTemplateVariables(path string) (util.MapStr, error)

func NewTemplateVariablesFromConfig

func NewTemplateVariablesFromConfig(configObject *Config) (util.MapStr, error)

func NotifyOnConfigChange

func NotifyOnConfigChange(f func(fsnotify.Event))

NotifyOnConfigChange will trigger callback when any configuration file change detected

func NotifyOnConfigSectionChange

func NotifyOnConfigSectionChange(configKey string, f func(pCfg, cCfg *Config))

NotifyOnConfigSectionChange will trigger callback when any configuration file change detected and configKey present in the changed file

func OwnerHasExclusiveWritePerms

func OwnerHasExclusiveWritePerms(name string) error

OwnerHasExclusiveWritePerms asserts that the current user or root is the owner of the config file and that the config file is (at most) writable by the owner or root (e.g. group and other cannot have write access).

func RegisterOption

func RegisterOption(name string, option ucfg.Option)

func RegisterPathFilter

func RegisterPathFilter(f PathFilter)

func SetValidExtension

func SetValidExtension(v []string)

func StopWatchers

func StopWatchers()

Types

type APIConfig

type APIConfig struct {
	Enabled       bool          `config:"enabled"`
	TLSConfig     TLSConfig     `config:"tls"`
	NetworkConfig NetworkConfig `config:"network"`

	Security APISecurityConfig `config:"security"`

	CrossDomain struct {
		AllowedOrigins []string `config:"allowed_origins"`
	} `config:"cors"`
	WebsocketConfig WebsocketConfig `config:"websocket"`

	VerboseErrorRootCause bool   `config:"verbose_error_root_cause"` //return root_cause in api response
	APIDirectoryPath      string `config:"api_directory_path"`
	DisableAPIDirectory   bool   `config:"disable_api_directory"`
}

func (*APIConfig) GetEndpoint

func (config *APIConfig) GetEndpoint() string

func (*APIConfig) GetSchema

func (config *APIConfig) GetSchema() string

type APISecurityConfig

type APISecurityConfig struct {
	Enabled  bool   `config:"enabled"`
	Username string `json:"username,omitempty" config:"username" elastic_mapping:"username:{type:keyword}"`
	Password string `json:"password,omitempty" config:"password" elastic_mapping:"password:{type:keyword}"`
}

type AuthConfig

type AuthConfig struct {
	Enabled       bool   `config:"enabled"`
	OAuthProvider string `config:"oauth_provider"`

	AuthorizedAdmins []string `config:"authorized_admin"`
	ClientSecret     string   `config:"client_secret"`
	ClientID         string   `config:"client_id"`
	// contains filtered or unexported fields
}

type AutoIssue

type AutoIssue struct {
	Enabled              bool     `config:"enabled" json:"enabled,omitempty" elastic_mapping:"enabled: { type: boolean }"`
	Email                string   `config:"email" json:"email,omitempty" elastic_mapping:"email: { type: keyword }"`
	Path                 string   `config:"path" json:"path,omitempty" elastic_mapping:"path: { type: keyword }"`
	IncludeDefaultDomain bool     `` /* 131-byte string literal not displayed */
	SkipInvalidDomain    bool     `config:"skip_invalid_domain" json:"skip_invalid_domain,omitempty" elastic_mapping:"skip_invalid_domain: { type: boolean }"`
	Domains              []string `config:"domains" json:"domains,omitempty" elastic_mapping:"domains: { type: keyword }"`

	Provider struct {
		TencentDNS struct {
			SecretID  string `config:"secret_id" json:"secret_id,omitempty" elastic_mapping:"secret_id: { type: keyword }"`
			SecretKey string `config:"secret_key" json:"secret_key,omitempty" elastic_mapping:"secret_key: { type: keyword }"`
		} `config:"tencent_dns" json:"tencent_dns,omitempty" elastic_mapping:"tencent_dns: { type: object }"`
	} `config:"provider" json:"provider,omitempty" elastic_mapping:"provider: { type: object }"`
}

type CallbackFunc

type CallbackFunc func(file string, op fsnotify.Op)

type ClusterConfig

type ClusterConfig struct {
	Enabled                        bool          `config:"enabled"`
	Name                           string        `config:"name"`
	MinimumNodes                   int           `config:"minimum_nodes"`
	Seeds                          []string      `config:"seeds"`
	RPCConfig                      RPCConfig     `config:"rpc"`
	BoradcastConfig                NetworkConfig `config:"broadcast"`
	DiscoveryTimeoutInMilliseconds int64         `config:"discovery_timeout_ms"`
	HealthCheckInMilliseconds      int64         `config:"health_check_ms"`
}

ClusterConfig stores cluster settings

func (ClusterConfig) GetSeeds

func (cfg ClusterConfig) GetSeeds() []string

type Config

type Config ucfg.Config

Config object to store hierarchical configurations into. See https://godoc.org/github.com/elastic/go-ucfg#Config

func FromConfig

func FromConfig(in *ucfg.Config) *Config

func LoadFile

func LoadFile(path string) (*Config, error)

func MergeConfigs

func MergeConfigs(cfgs ...*Config) (*Config, error)

MergeConfigs just merge configs together

func NewConfig

func NewConfig() *Config

NewConfig create a pretty new config

func NewConfigFrom

func NewConfigFrom(from interface{}) (*Config, error)

NewConfigFrom get config instance

func NewConfigWithTemplate

func NewConfigWithTemplate(v ConfigTemplate) (*Config, error)

func NewConfigWithYAML

func NewConfigWithYAML(in []byte, source string) (*Config, error)

NewConfigWithYAML load config from yaml

func NewFlagConfig

func NewFlagConfig(
	set *flag.FlagSet,
	def *Config,
	name string,
	usage string,
) *Config

NewFlagConfig will use flags

func (*Config) Bool

func (c *Config) Bool(name string, idx int) (bool, error)

Bool reads a boolean setting returning an error if the setting has no boolean value.

func (*Config) Child

func (c *Config) Child(name string, idx int) (*Config, error)

Child returns a child configuration or an error if the setting requested is a primitive value only.

func (*Config) CountField

func (c *Config) CountField(name string) (int, error)

CountField returns number of entries in a table or 1 if entry is a primitive value. Primitives settings can be handled like a list with 1 entry.

func (*Config) Enabled

func (c *Config) Enabled(defaultV bool) bool

Enabled was a predefined config, enabled by default if no config was found

func (*Config) Float

func (c *Config) Float(name string, idx int) (float64, error)

Float reads a float64 value returning an error if the setting is not a float value or the primitive value is not convertible to float.

func (*Config) GetFields

func (c *Config) GetFields() []string

GetFields returns a list of all top-level named keys in c.

func (*Config) HasField

func (c *Config) HasField(name string) bool

HasField checks if c has a top-level named key name.

func (*Config) Int

func (c *Config) Int(name string, idx int) (int64, error)

Int reads an int64 value returning an error if the setting is not integer value, the primitive value is not convertible to int or a conversion would create an integer overflow.

func (*Config) IsArray

func (c *Config) IsArray() bool

IsArray checks if c has index only accessible settings.

func (*Config) IsDict

func (c *Config) IsDict() bool

IsDict checks if c has named keys.

func (*Config) Merge

func (c *Config) Merge(from interface{}) error

Merge a map, a slice, a struct or another Config object into c.

func (*Config) Path

func (c *Config) Path() string

Path gets the absolute path of c separated by sep. If c is a root-Config an empty string will be returned.

func (*Config) PathOf

func (c *Config) PathOf(field string) string

PathOf gets the absolute path of a potential setting field in c with name separated by sep.

func (*Config) SetBool

func (c *Config) SetBool(name string, idx int, value bool) error

SetBool sets a boolean primitive value. An error is returned if the new name is invalid.

func (*Config) SetChild

func (c *Config) SetChild(name string, idx int, value *Config) error

SetChild adds a sub-configuration. An error is returned if the name is invalid.

func (*Config) SetFloat

func (c *Config) SetFloat(name string, idx int, value float64) error

SetFloat sets an floating point primitive value. An error is returned if the name is invalid.

func (*Config) SetInt

func (c *Config) SetInt(name string, idx int, value int64) error

SetInt sets an integer primitive value. An error is returned if the new name is invalid.

func (*Config) SetString

func (c *Config) SetString(name string, idx int, value string) error

SetString sets string value. An error is returned if the name is invalid.

func (*Config) String

func (c *Config) String(name string, idx int) (string, error)

Strings reads a string setting returning an error if the setting has no string or primitive value convertible to string.

func (*Config) Unpack

func (c *Config) Unpack(to interface{}, options ...ucfg.Option) error

Unpack unpacks c into a struct, a map, or a slice allocating maps, slices, and pointers as necessary.

type ConfigTemplate

type ConfigTemplate struct {
	Name     string      `config:"name"`
	Path     string      `config:"path"`
	Variable util.MapStr `config:"variable"`
}

type ConfigsConfig

type ConfigsConfig struct {
	AutoReload                 bool      `config:"auto_reload"`                    //auto reload local files
	Managed                    bool      `config:"managed"`                        //managed by remote config center
	ConfigFileManagedByDefault bool      `config:"config_file_managed_by_default"` //config file managed by default
	Servers                    []string  `config:"servers"`                        //remote config center servers
	ScheduledTask              bool      `config:"scheduled_task"`                 //use dedicated schedule task or background, use background task will save one goroutine
	Interval                   string    `config:"interval"`                       //sync interval in seconds
	SoftDelete                 bool      `config:"soft_delete"`                    //soft delete config
	PanicOnConfigError         bool      `config:"panic_on_config_error"`          //panic on config error
	MaxBackupFiles             int       `config:"max_backup_files"`               //keep max num of file backup
	ValidConfigsExtensions     []string  `config:"valid_config_extensions"`
	TLSConfig                  TLSConfig `config:"tls"` //server or client's certs
	ManagerConfig              struct {
		LocalConfigsRepoPath string `config:"local_configs_repo_path"`
	} `config:"manager"`
	AlwaysRegisterAfterRestart bool     `config:"always_register_after_restart"`
	AllowGeneratedMetricsTasks bool     `config:"allow_generated_metrics_tasks"`
	IgnoredPath                []string `config:"ignored_path"`
}

type CookieConfig

type CookieConfig struct {
	Secret string `config:"secret"`
	Domain string `config:"domain"`
}

type EnvConfig

type EnvConfig struct {
	Environments map[string]interface{} `config:"env"`
}

type GzipConfig

type GzipConfig struct {
	Enabled bool `config:"enabled"`
	Level   int  `config:"level"`
}

type HTTPClientConfig

type HTTPClientConfig struct {
	Proxy struct {
		Enabled             bool                   `config:"enabled"`
		DefaultProxyConfig  ProxyConfig            `config:"default_config"`
		Permitted           []string               `config:"permitted"`
		Denied              []string               `config:"denied"`
		Domains             map[string]ProxyConfig `config:"domains"` //proxy settings per domain
		OverrideSystemProxy bool                   `config:"override_system_proxy_env"`
	} `config:"proxy"`

	Timeout              string    `config:"timeout"`
	DialTimeout          string    `config:"dial_timeout"`
	ReadTimeout          string    `config:"read_timeout"`
	WriteTimeout         string    `config:"write_timeout"`
	ReadBufferSize       int       `config:"read_buffer_size"`
	WriteBufferSize      int       `config:"write_buffer_size"`
	TLSConfig            TLSConfig `config:"tls"` //server or client's certs
	MaxConnectionPerHost int       `config:"max_connection_per_host"`
	// contains filtered or unexported fields
}

func (*HTTPClientConfig) ValidateProxy added in v1.1.0

func (c *HTTPClientConfig) ValidateProxy(addr string) (bool, *ProxyConfig)

type LoggingConfig

type LoggingConfig struct {
	DisableFileOutput bool   `json:"disable_file_output" config:"disable_file_output"`
	LogLevel          string `json:"level" config:"level"`
	LogFormat         string `json:"format" config:"format"`

	RealtimePushEnabled  bool   `json:"realtime"`
	PushLogLevel         string `json:"push_log_level"`
	FuncFilterPattern    string `json:"func_pattern"`
	FileFilterPattern    string `json:"file_pattern"`
	MessageFilterPattern string `json:"message_pattern"`

	IsDebug bool `json:"debug"  config:"debug"`
}

LoggingConfig object to store logging related settings

type Namespace

type Namespace struct {
	C map[string]*Config `config:",inline"`
}

Namespace storing at most one configuration section by name and sub-section.

func (*Namespace) Config

func (ns *Namespace) Config() *Config

Config return the sub-configuration section if a section has been set.

func (*Namespace) IsSet

func (ns *Namespace) IsSet() bool

IsSet returns true if a sub-configuration section has been set.

func (*Namespace) Name

func (ns *Namespace) Name() string

Name returns the configuration sections it's name if a section has been set.

func (*Namespace) Validate

func (ns *Namespace) Validate() error

Validate checks at most one sub-namespace being set.

type NetworkConfig

type NetworkConfig struct {
	Host             string `config:"host" json:"host,omitempty" elastic_mapping:"host: { type: keyword }"`
	Port             int    `config:"port" json:"port,omitempty" elastic_mapping:"port: { type: keyword }"`
	Binding          string `config:"binding" json:"binding,omitempty" elastic_mapping:"binding: { type: keyword }"`
	Publish          string `config:"publish" json:"publish,omitempty" elastic_mapping:"publish: { type: keyword }"`
	SkipOccupiedPort bool   `config:"skip_occupied_port" json:"skip_occupied_port,omitempty" elastic_mapping:"skip_occupied_port: { type: boolean }"`
	ReusePort        bool   `config:"reuse_port" json:"reuse_port,omitempty" elastic_mapping:"reuse_port: { type: boolean }"`
}

NetworkConfig stores network settings

func (NetworkConfig) GetBindingAddr

func (cfg NetworkConfig) GetBindingAddr() string

func (NetworkConfig) GetBindingPort

func (cfg NetworkConfig) GetBindingPort() int

func (NetworkConfig) GetPublishAddr

func (cfg NetworkConfig) GetPublishAddr() string

type NodeConfig

type NodeConfig struct {
	ID   string `json:"id,omitempty" config:"id"`
	Name string `json:"name,omitempty" config:"name"`
	IP   string `json:"ip,omitempty" config:"ip"`

	//tagging for node
	MajorIpPattern string            `config:"major_ip_pattern"`
	Labels         map[string]string `config:"labels"`
	Tags           []string          `config:"tags"`
}

NodeConfig stores node settings

func (*NodeConfig) ToString

func (config *NodeConfig) ToString() string

type PathConfig

type PathConfig struct {
	Plugin string `config:"plugins"`
	Config string `config:"configs"`
	Data   string `config:"data"`
	Log    string `config:"logs"`
}

PathConfig stores path settings

type PathFilter

type PathFilter func(fpath string) bool

func GenerateWildcardPathFilter

func GenerateWildcardPathFilter(patterns []string) PathFilter

type ProxyConfig added in v1.1.0

type ProxyConfig struct {
	HTTPProxy                     string `config:"http_proxy"` //export HTTP_PROXY=http://username:password@proxy-url:port
	Socket5Proxy                  string `config:"socket5_proxy"`
	UsingEnvironmentProxySettings bool   `config:"using_proxy_env"` //using the the env(HTTP_PROXY, HTTPS_PROXY and NO_PROXY) configured HTTP proxy
}

type RPCConfig

type RPCConfig struct {
	TLSConfig     TLSConfig     `config:"tls"`
	NetworkConfig NetworkConfig `config:"network"`
}

type ResourceLimit

type ResourceLimit struct {
	CPU struct {
		CPUAffinityList    string `config:"affinity_list"`
		MaxCPUPercentUsage int    `config:"max_percent_usage"`
		MaxNumOfCPUs       int    `config:"max_num_of_cpus"`
	} `config:"cpu"`

	Mem struct {
		MaxMemoryInBytes int `config:"max_in_bytes"`
	} `config:"memory"`
}

type Rule

type Rule struct {
	Contain  []string `config:"contain"`
	Prefix   []string `config:"prefix"`
	Suffix   []string `config:"suffix"`
	Wildcard []string `config:"wildcard"`
	Regex    []string `config:"regex"`
}

Rule is container of rules

type Rules

type Rules struct {
	Should  *Rule `config:"should"`
	Must    *Rule `config:"must"`
	MustNot *Rule `config:"must_not"`
}

Rules defines two fields, Should means any of the rules matched will be work Must means some rule must match MustNot means some rule must not match

type S3BucketConfig

type S3BucketConfig struct {
	Async    bool   `config:"async"`
	Server   string `config:"server"`
	Location string `config:"location"`
	Bucket   string `config:"bucket"`
}

type S3Config

type S3Config struct {
	Endpoint           string `config:"endpoint" json:"endpoint,omitempty"`
	AccessKey          string `config:"access_key" json:"access_key,omitempty"`
	AccessSecret       string `config:"access_secret" json:"access_secret,omitempty"`
	Token              string `config:"token" json:"token,omitempty"`
	SSL                bool   `config:"ssl" json:"ssl,omitempty"`
	SkipInsecureVerify bool   `config:"skip_insecure_verify" json:"skip_insecure_verify,omitempty"`
}

type SystemConfig

type SystemConfig struct {

	//reserved config
	ClusterConfig ClusterConfig `config:"cluster"`

	APIConfig APIConfig `config:"api"`

	WebAppConfig WebAppConfig `config:"web"`

	NodeConfig NodeConfig `config:"node"`

	PathConfig PathConfig `config:"path"`

	LoggingConfig LoggingConfig `config:"log"`

	Cookie CookieConfig `config:"cookie"`

	AllowMultiInstance bool `config:"allow_multi_instance"`
	SkipInstanceDetect bool `config:"skip_instance_detect"`

	MaxNumOfInstance int `config:"max_num_of_instances"`

	ResourceLimit *ResourceLimit `config:"resource_limit"`

	Configs ConfigsConfig `config:"configs"`

	//dynamic config enabled
	Modules []*Config `config:"modules"`

	Plugins []*Config `config:"plugins"`

	HTTPClientConfig map[string]HTTPClientConfig `config:"http_client"`
}

SystemConfig is a high priority config, init from the environment or startup, can't be changed on the fly, need to restart to make config apply

type TLSConfig

type TLSConfig struct {
	TLSEnabled            bool   `config:"enabled" json:"enabled,omitempty" elastic_mapping:"enabled: { type: boolean }"`
	TLSCertFile           string `config:"cert_file" json:"cert_file,omitempty" elastic_mapping:"cert_file: { type: keyword }"`
	TLSKeyFile            string `config:"key_file" json:"key_file,omitempty" elastic_mapping:"key_file: { type: keyword }"`
	TLSCACertFile         string `config:"ca_file" json:"ca_file,omitempty" elastic_mapping:"ca_file: { type: keyword }"`
	TLSInsecureSkipVerify bool   `config:"skip_insecure_verify" json:"skip_insecure_verify,omitempty" elastic_mapping:"skip_insecure_verify: { type: boolean }"`

	//use for auto generate cert
	DefaultDomain    string `config:"default_domain" json:"default_domain,omitempty" elastic_mapping:"default_domain: { type: keyword }"`
	SkipDomainVerify bool   `config:"skip_domain_verify" json:"skip_domain_verify,omitempty" elastic_mapping:"skip_domain_verify: { type: boolean }"`

	//auto issue public TLS cert
	AutoIssue AutoIssue `config:"auto_issue" json:"auto_issue,omitempty" elastic_mapping:"auto_issue: { type: object }"`

	ClientSessionCacheSize int `config:"client_session_cache_size" json:"client_session_cache_size,omitempty"`
}

type TemplateConfigs

type TemplateConfigs struct {
	Templates []ConfigTemplate `config:"configs.template"`
}

type UIConfig

type UIConfig struct {
	LocalPath    string `config:"path"`
	LocalEnabled bool   `config:"local"`
	VFSEnabled   bool   `config:"vfs"`
}

type Watcher

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

type WebAppConfig

type WebAppConfig struct {

	//same with API Config
	Enabled       bool              `config:"enabled"`
	TLSConfig     TLSConfig         `config:"tls"`
	NetworkConfig NetworkConfig     `config:"network"`
	Security      APISecurityConfig `config:"security"`
	CrossDomain   struct {
		AllowedOrigins []string `config:"allowed_origins"`
	} `config:"cors"`
	WebsocketConfig WebsocketConfig `config:"websocket"`

	AuthConfig   AuthConfig     `config:"auth"` //enable access control for UI or not
	UI           UIConfig       `config:"ui"`
	BasePath     string         `config:"base_path"`
	Domain       string         `config:"domain"`
	EmbeddingAPI bool           `config:"embedding_api"`
	Gzip         GzipConfig     `config:"gzip"`
	S3Config     S3BucketConfig `config:"s3"`
}

func (*WebAppConfig) GetEndpoint

func (config *WebAppConfig) GetEndpoint() string

func (*WebAppConfig) GetSchema

func (config *WebAppConfig) GetSchema() string

type WebsocketConfig

type WebsocketConfig struct {
	Enabled        bool     `config:"enabled"`
	BasePath       string   `config:"base_path"`
	PermittedHosts []string `config:"permitted_hosts"`
	SkipHostVerify bool     `config:"skip_host_verify"`
}

Jump to

Keyboard shortcuts

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