migrate settings to the new config scheme

This commit is contained in:
A.Unger
2021-11-05 12:25:32 +01:00
parent 28b0b8fccd
commit 17dbc3d5ee
9 changed files with 227 additions and 302 deletions

View File

@@ -121,8 +121,8 @@ func New() *Config {
Proxy: proxy.DefaultConfig(),
GraphExplorer: graphExplorer.DefaultConfig(),
OCS: ocs.DefaultConfig(),
Settings: settings.DefaultConfig(),
Web: web.New(),
Settings: settings.New(),
Storage: storage.New(),
Store: store.New(),
Thumbnails: thumbnails.New(),

View File

@@ -9,7 +9,6 @@ import (
"github.com/owncloud/ocis/ocis/pkg/register"
"github.com/owncloud/ocis/settings/pkg/command"
svcconfig "github.com/owncloud/ocis/settings/pkg/config"
"github.com/owncloud/ocis/settings/pkg/flagset"
"github.com/urfave/cli/v2"
)
@@ -19,7 +18,6 @@ func SettingsCommand(cfg *config.Config) *cli.Command {
Name: "settings",
Usage: "Start settings server",
Category: "Extensions",
Flags: flagset.ServerWithConfig(cfg.Settings),
Subcommands: []*cli.Command{
command.PrintVersion(cfg.Settings),
},

View File

@@ -3,15 +3,11 @@ package command
import (
"context"
"os"
"strings"
"github.com/owncloud/ocis/ocis-pkg/sync"
ociscfg "github.com/owncloud/ocis/ocis-pkg/config"
"github.com/owncloud/ocis/ocis-pkg/log"
"github.com/owncloud/ocis/ocis-pkg/version"
"github.com/owncloud/ocis/ocs/pkg/config"
"github.com/spf13/viper"
"github.com/thejerf/suture/v4"
"github.com/urfave/cli/v2"
)
@@ -67,46 +63,18 @@ func NewLogger(cfg *config.Config) log.Logger {
)
}
// ParseConfig reads ocs configuration from fs.
// ParseConfig loads idp configuration from known paths.
func ParseConfig(c *cli.Context, cfg *config.Config) error {
sync.ParsingViperConfig.Lock()
defer sync.ParsingViperConfig.Unlock()
logger := NewLogger(cfg)
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetEnvPrefix("OCS")
viper.AutomaticEnv()
if c.IsSet("config-file") {
viper.SetConfigFile(c.String("config-file"))
} else {
viper.SetConfigName("ocs")
viper.AddConfigPath("/etc/ocis")
viper.AddConfigPath("$HOME/.ocis")
viper.AddConfigPath("./config")
conf, err := ociscfg.BindSourcesToStructs("ocs", cfg)
if err != nil {
return err
}
if err := viper.ReadInConfig(); err != nil {
switch err.(type) {
case viper.ConfigFileNotFoundError:
logger.Debug().
Msg("no config found on preconfigured location")
case viper.UnsupportedConfigError:
logger.Fatal().
Err(err).
Msg("unsupported config type")
default:
logger.Fatal().
Err(err).
Msg("failed to read config")
}
}
// load all env variables relevant to the config in the current context.
conf.LoadOSEnv(config.GetEnv(), false)
if err := viper.Unmarshal(&cfg); err != nil {
logger.Fatal().
Err(err).
Msg("failed to parse config")
if err = cfg.UnmapEnv(conf); err != nil {
return err
}
return nil

View File

@@ -8,7 +8,7 @@ import (
)
func main() {
if err := command.Execute(config.New()); err != nil {
if err := command.Execute(config.DefaultConfig()); err != nil {
os.Exit(1)
}
}

View File

@@ -3,15 +3,11 @@ package command
import (
"context"
"os"
"strings"
"github.com/owncloud/ocis/ocis-pkg/sync"
ociscfg "github.com/owncloud/ocis/ocis-pkg/config"
"github.com/owncloud/ocis/ocis-pkg/log"
"github.com/owncloud/ocis/ocis-pkg/version"
"github.com/owncloud/ocis/settings/pkg/config"
"github.com/spf13/viper"
"github.com/thejerf/suture/v4"
"github.com/urfave/cli/v2"
)
@@ -31,8 +27,6 @@ func Execute(cfg *config.Config) error {
},
},
//Flags: flagset.RootWithConfig(cfg),
Before: func(c *cli.Context) error {
cfg.Service.Version = version.String
return nil
@@ -69,46 +63,18 @@ func NewLogger(cfg *config.Config) log.Logger {
)
}
// ParseConfig loads settings configuration from Viper known paths.
// ParseConfig loads idp configuration from known paths.
func ParseConfig(c *cli.Context, cfg *config.Config) error {
sync.ParsingViperConfig.Lock()
defer sync.ParsingViperConfig.Unlock()
logger := NewLogger(cfg)
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetEnvPrefix("SETTINGS")
viper.AutomaticEnv()
if c.IsSet("config-file") {
viper.SetConfigFile(c.String("config-file"))
} else {
viper.SetConfigName("settings")
viper.AddConfigPath("/etc/ocis")
viper.AddConfigPath("$HOME/.ocis")
viper.AddConfigPath("./config")
conf, err := ociscfg.BindSourcesToStructs("settings", cfg)
if err != nil {
return err
}
if err := viper.ReadInConfig(); err != nil {
switch err.(type) {
case viper.ConfigFileNotFoundError:
logger.Debug().
Msg("no config found on preconfigured location")
case viper.UnsupportedConfigError:
logger.Fatal().
Err(err).
Msg("unsupported config type")
default:
logger.Fatal().
Err(err).
Msg("failed to read config")
}
}
// load all env variables relevant to the config in the current context.
conf.LoadOSEnv(config.GetEnv(), false)
if err := viper.Unmarshal(&cfg); err != nil {
logger.Fatal().
Err(err).
Msg("failed to parse config")
if err = cfg.UnmapEnv(conf); err != nil {
return err
}
return nil

View File

@@ -7,7 +7,6 @@ import (
"github.com/oklog/run"
"github.com/owncloud/ocis/ocis-pkg/sync"
"github.com/owncloud/ocis/settings/pkg/config"
"github.com/owncloud/ocis/settings/pkg/flagset"
"github.com/owncloud/ocis/settings/pkg/metrics"
"github.com/owncloud/ocis/settings/pkg/server/debug"
"github.com/owncloud/ocis/settings/pkg/server/grpc"
@@ -21,28 +20,15 @@ func Server(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "server",
Usage: "Start integrated server",
Flags: flagset.ServerWithConfig(cfg),
Before: func(ctx *cli.Context) error {
logger := NewLogger(cfg)
if cfg.HTTP.Root != "/" {
cfg.HTTP.Root = strings.TrimSuffix(cfg.HTTP.Root, "/")
}
// When running on single binary mode the before hook from the root command won't get called. We manually
// call this before hook from ocis command, so the configuration can be loaded.
if !cfg.Supervised {
return ParseConfig(ctx, cfg)
if err := ParseConfig(ctx, cfg); err != nil {
return err
}
if origins := ctx.StringSlice("cors-allowed-origins"); len(origins) != 0 {
cfg.HTTP.CORS.AllowedOrigins = origins
}
if methods := ctx.StringSlice("cors-allowed-methods"); len(methods) != 0 {
cfg.HTTP.CORS.AllowedMethods = methods
}
if headers := ctx.StringSlice("cors-allowed-headers"); len(headers) != 0 {
cfg.HTTP.CORS.AllowedOrigins = headers
}
logger.Debug().Str("service", "settings").Msg("ignoring config file parsing when running supervised")
return nil
},
Action: func(c *cli.Context) error {

View File

@@ -1,6 +1,15 @@
package config
import "context"
import (
"context"
"fmt"
"path"
"reflect"
gofig "github.com/gookit/config/v2"
"github.com/owncloud/ocis/ocis-pkg/config/defaults"
)
// Log defines the available logging configuration.
type Log struct {
@@ -87,3 +96,95 @@ type Config struct {
func New() *Config {
return &Config{}
}
// DefaultConfig provides sane bootstrapping defaults.
func DefaultConfig() *Config {
return &Config{
Log: Log{},
Service: Service{
Name: "settings",
DataPath: path.Join(defaults.BaseDataPath(), "settings"),
},
Debug: Debug{
Addr: "127.0.0.1:9194",
Token: "",
Pprof: false,
Zpages: false,
},
HTTP: HTTP{
Addr: "127.0.0.1:9190",
Namespace: "com.owncloud.web",
Root: "/",
CacheTTL: 604800, // 10 days
CORS: CORS{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Authorization", "Origin", "Content-Type", "Accept", "X-Requested-With"},
AllowCredentials: true,
},
},
GRPC: GRPC{
Addr: "127.0.0.1:9191",
Namespace: "com.owncloud.api",
},
Tracing: Tracing{
Enabled: false,
Type: "jaeger",
Endpoint: "",
Collector: "",
Service: "settings",
},
Asset: Asset{
Path: "",
},
TokenManager: TokenManager{
JWTSecret: "Pive-Fumkiu4",
},
}
}
// GetEnv fetches a list of known env variables for this extension. It is to be used by gookit, as it provides a list
// with all the environment variables an extension supports.
func GetEnv() []string {
var r = make([]string, len(structMappings(&Config{})))
for i := range structMappings(&Config{}) {
r = append(r, structMappings(&Config{})[i].EnvVars...)
}
return r
}
// UnmapEnv loads values from the gooconf.Config argument and sets them in the expected destination.
func (c *Config) UnmapEnv(gooconf *gofig.Config) error {
vals := structMappings(c)
for i := range vals {
for j := range vals[i].EnvVars {
// we need to guard against v != "" because this is the condition that checks that the value is set from the environment.
// the `ok` guard is not enough, apparently.
if v, ok := gooconf.GetValue(vals[i].EnvVars[j]); ok && v != "" {
// get the destination type from destination
switch reflect.ValueOf(vals[i].Destination).Type().String() {
case "*bool":
r := gooconf.Bool(vals[i].EnvVars[j])
*vals[i].Destination.(*bool) = r
case "*string":
r := gooconf.String(vals[i].EnvVars[j])
*vals[i].Destination.(*string) = r
case "*int":
r := gooconf.Int(vals[i].EnvVars[j])
*vals[i].Destination.(*int) = r
case "*float64":
// defaults to float64
r := gooconf.Float(vals[i].EnvVars[j])
*vals[i].Destination.(*float64) = r
default:
// it is unlikely we will ever get here. Let this serve more as a runtime check for when debugging.
return fmt.Errorf("invalid type for env var: `%v`", vals[i].EnvVars[j])
}
}
}
}
return nil
}

104
settings/pkg/config/env.go Normal file
View File

@@ -0,0 +1,104 @@
package config
type mapping struct {
EnvVars []string // name of the EnvVars var.
Destination interface{} // memory address of the original config value to modify.
}
// structMappings binds a set of environment variables to a destination on cfg.
func structMappings(cfg *Config) []mapping {
return []mapping{
{
EnvVars: []string{"SETTINGS_LOG_LEVEL", "OCIS_LOG_LEVEL"},
Destination: &cfg.Log.Level,
},
{
EnvVars: []string{"SETTINGS_LOG_PRETTY", "OCIS_LOG_PRETTY"},
Destination: &cfg.Log.Pretty,
},
{
EnvVars: []string{"SETTINGS_LOG_COLOR", "OCIS_LOG_COLOR"},
Destination: &cfg.Log.Color,
},
{
EnvVars: []string{"SETTINGS_CONFIG_FILE"},
Destination: &cfg.File,
},
{
EnvVars: []string{"SETTINGS_TRACING_ENABLED", "OCIS_TRACING_ENABLED"},
Destination: &cfg.Tracing.Enabled,
},
{
EnvVars: []string{"SETTINGS_TRACING_TYPE", "OCIS_TRACING_TYPE"},
Destination: &cfg.Tracing.Type,
},
{
EnvVars: []string{"SETTINGS_TRACING_ENDPOINT", "OCIS_TRACING_ENDPOINT"},
Destination: &cfg.Tracing.Endpoint,
},
{
EnvVars: []string{"SETTINGS_TRACING_COLLECTOR", "OCIS_TRACING_COLLECTOR"},
Destination: &cfg.Tracing.Collector,
},
{
EnvVars: []string{"SETTINGS_TRACING_SERVICE"},
Destination: &cfg.Tracing.Service,
},
{
EnvVars: []string{"SETTINGS_DEBUG_ADDR"},
Destination: &cfg.Debug.Addr,
},
{
EnvVars: []string{"SETTINGS_DEBUG_TOKEN"},
Destination: &cfg.Debug.Token,
},
{
EnvVars: []string{"SETTINGS_DEBUG_PPROF"},
Destination: &cfg.Debug.Pprof,
},
{
EnvVars: []string{"SETTINGS_DEBUG_ZPAGES"},
Destination: &cfg.Debug.Zpages,
},
{
EnvVars: []string{"SETTINGS_HTTP_ADDR"},
Destination: &cfg.HTTP.Addr,
},
{
EnvVars: []string{"SETTINGS_HTTP_NAMESPACE"},
Destination: &cfg.HTTP.Namespace,
},
{
EnvVars: []string{"SETTINGS_HTTP_ROOT"},
Destination: &cfg.HTTP.Root,
},
{
EnvVars: []string{"SETTINGS_CACHE_TTL"},
Destination: &cfg.HTTP.CacheTTL,
},
{
EnvVars: []string{"SETTINGS_GRPC_ADDR"},
Destination: &cfg.GRPC.Addr,
},
{
EnvVars: []string{"SETTINGS_ASSET_PATH"},
Destination: &cfg.Asset.Path,
},
{
EnvVars: []string{"SETTINGS_GRPC_NAMESPACE"},
Destination: &cfg.GRPC.Namespace,
},
{
EnvVars: []string{"SETTINGS_NAME"},
Destination: &cfg.Service.Name,
},
{
EnvVars: []string{"SETTINGS_DATA_PATH"},
Destination: &cfg.Service.DataPath,
},
{
EnvVars: []string{"SETTINGS_JWT_SECRET", "OCIS_JWT_SECRET"},
Destination: &cfg.TokenManager.JWTSecret,
},
}
}

View File

@@ -1,38 +1,11 @@
package flagset
import (
"path"
"github.com/owncloud/ocis/ocis-pkg/config/defaults"
"github.com/owncloud/ocis/ocis-pkg/flags"
"github.com/owncloud/ocis/settings/pkg/config"
"github.com/urfave/cli/v2"
)
// RootWithConfig applies cfg to the root flagset
func RootWithConfig(cfg *config.Config) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "log-level",
Usage: "Set logging level",
EnvVars: []string{"SETTINGS_LOG_LEVEL", "OCIS_LOG_LEVEL"},
Destination: &cfg.Log.Level,
},
&cli.BoolFlag{
Name: "log-pretty",
Usage: "Enable pretty logging",
EnvVars: []string{"SETTINGS_LOG_PRETTY", "OCIS_LOG_PRETTY"},
Destination: &cfg.Log.Pretty,
},
&cli.BoolFlag{
Name: "log-color",
Usage: "Enable colored logging",
EnvVars: []string{"SETTINGS_LOG_COLOR", "OCIS_LOG_COLOR"},
Destination: &cfg.Log.Color,
},
}
}
// HealthWithConfig applies cfg to the root flagset
func HealthWithConfig(cfg *config.Config) []cli.Flag {
return []cli.Flag{
@@ -46,177 +19,6 @@ func HealthWithConfig(cfg *config.Config) []cli.Flag {
}
}
// ServerWithConfig applies cfg to the root flagset
func ServerWithConfig(cfg *config.Config) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "config-file",
Value: "",
Usage: "Path to config file",
EnvVars: []string{"SETTINGS_CONFIG_FILE"},
Destination: &cfg.File,
},
&cli.BoolFlag{
Name: "tracing-enabled",
Usage: "Enable sending traces",
EnvVars: []string{"SETTINGS_TRACING_ENABLED", "OCIS_TRACING_ENABLED"},
Destination: &cfg.Tracing.Enabled,
},
&cli.StringFlag{
Name: "tracing-type",
Value: flags.OverrideDefaultString(cfg.Tracing.Type, "jaeger"),
Usage: "Tracing backend type",
EnvVars: []string{"SETTINGS_TRACING_TYPE", "OCIS_TRACING_TYPE"},
Destination: &cfg.Tracing.Type,
},
&cli.StringFlag{
Name: "tracing-endpoint",
Value: flags.OverrideDefaultString(cfg.Tracing.Endpoint, ""),
Usage: "Endpoint for the agent",
EnvVars: []string{"SETTINGS_TRACING_ENDPOINT", "OCIS_TRACING_ENDPOINT"},
Destination: &cfg.Tracing.Endpoint,
},
&cli.StringFlag{
Name: "tracing-collector",
Value: flags.OverrideDefaultString(cfg.Tracing.Collector, ""),
Usage: "Endpoint for the collector",
EnvVars: []string{"SETTINGS_TRACING_COLLECTOR", "OCIS_TRACING_COLLECTOR"},
Destination: &cfg.Tracing.Collector,
},
&cli.StringFlag{
Name: "tracing-service",
Value: flags.OverrideDefaultString(cfg.Tracing.Service, "settings"),
Usage: "Service name for tracing",
EnvVars: []string{"SETTINGS_TRACING_SERVICE"},
Destination: &cfg.Tracing.Service,
},
&cli.StringFlag{
Name: "debug-addr",
Value: flags.OverrideDefaultString(cfg.Debug.Addr, "127.0.0.1:9194"),
Usage: "Address to bind debug server",
EnvVars: []string{"SETTINGS_DEBUG_ADDR"},
Destination: &cfg.Debug.Addr,
},
&cli.StringFlag{
Name: "debug-token",
Value: flags.OverrideDefaultString(cfg.Debug.Token, ""),
Usage: "Token to grant metrics access",
EnvVars: []string{"SETTINGS_DEBUG_TOKEN"},
Destination: &cfg.Debug.Token,
},
&cli.BoolFlag{
Name: "debug-pprof",
Usage: "Enable pprof debugging",
EnvVars: []string{"SETTINGS_DEBUG_PPROF"},
Destination: &cfg.Debug.Pprof,
},
&cli.BoolFlag{
Name: "debug-zpages",
Usage: "Enable zpages debugging",
EnvVars: []string{"SETTINGS_DEBUG_ZPAGES"},
Destination: &cfg.Debug.Zpages,
},
&cli.StringFlag{
Name: "http-addr",
Value: flags.OverrideDefaultString(cfg.HTTP.Addr, "127.0.0.1:9190"),
Usage: "Address to bind http server",
EnvVars: []string{"SETTINGS_HTTP_ADDR"},
Destination: &cfg.HTTP.Addr,
},
&cli.StringFlag{
Name: "http-namespace",
Value: flags.OverrideDefaultString(cfg.HTTP.Namespace, "com.owncloud.web"),
Usage: "Set the base namespace for the http namespace",
EnvVars: []string{"SETTINGS_HTTP_NAMESPACE"},
Destination: &cfg.HTTP.Namespace,
},
&cli.StringFlag{
Name: "http-root",
Value: flags.OverrideDefaultString(cfg.HTTP.Root, "/"),
Usage: "Root path of http server",
EnvVars: []string{"SETTINGS_HTTP_ROOT"},
Destination: &cfg.HTTP.Root,
},
&cli.IntFlag{
Name: "http-cache-ttl",
Value: flags.OverrideDefaultInt(cfg.HTTP.CacheTTL, 604800), // 10 days
Usage: "Set the static assets caching duration in seconds",
EnvVars: []string{"SETTINGS_CACHE_TTL"},
Destination: &cfg.HTTP.CacheTTL,
},
&cli.StringSliceFlag{
Name: "cors-allowed-origins",
Value: cli.NewStringSlice("*"),
Usage: "Set the allowed CORS origins",
EnvVars: []string{"SETTINGS_CORS_ALLOW_ORIGINS", "OCIS_CORS_ALLOW_ORIGINS"},
},
&cli.StringSliceFlag{
Name: "cors-allowed-methods",
Value: cli.NewStringSlice("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"),
Usage: "Set the allowed CORS origins",
EnvVars: []string{"SETTINGS_CORS_ALLOW_METHODS", "OCIS_CORS_ALLOW_METHODS"},
},
&cli.StringSliceFlag{
Name: "cors-allowed-headers",
Value: cli.NewStringSlice("Authorization", "Origin", "Content-Type", "Accept", "X-Requested-With"),
Usage: "Set the allowed CORS origins",
EnvVars: []string{"SETTINGS_CORS_ALLOW_HEADERS", "OCIS_CORS_ALLOW_HEADERS"},
},
&cli.BoolFlag{
Name: "cors-allow-credentials",
Value: flags.OverrideDefaultBool(cfg.HTTP.CORS.AllowCredentials, true),
Usage: "Allow credentials for CORS",
EnvVars: []string{"SETTINGS_CORS_ALLOW_CREDENTIALS", "OCIS_CORS_ALLOW_CREDENTIALS"},
},
&cli.StringFlag{
Name: "grpc-addr",
Value: flags.OverrideDefaultString(cfg.GRPC.Addr, "127.0.0.1:9191"),
Usage: "Address to bind grpc server",
EnvVars: []string{"SETTINGS_GRPC_ADDR"},
Destination: &cfg.GRPC.Addr,
},
&cli.StringFlag{
Name: "asset-path",
Value: flags.OverrideDefaultString(cfg.Asset.Path, ""),
Usage: "Path to custom assets",
EnvVars: []string{"SETTINGS_ASSET_PATH"},
Destination: &cfg.Asset.Path,
},
&cli.StringFlag{
Name: "grpc-namespace",
Value: flags.OverrideDefaultString(cfg.GRPC.Namespace, "com.owncloud.api"),
Usage: "Set the base namespace for the grpc namespace",
EnvVars: []string{"SETTINGS_GRPC_NAMESPACE"},
Destination: &cfg.GRPC.Namespace,
},
&cli.StringFlag{
Name: "name",
Value: flags.OverrideDefaultString(cfg.Service.Name, "settings"),
Usage: "service name",
EnvVars: []string{"SETTINGS_NAME"},
Destination: &cfg.Service.Name,
},
&cli.StringFlag{
Name: "data-path",
Value: flags.OverrideDefaultString(cfg.Service.DataPath, path.Join(defaults.BaseDataPath(), "settings")),
Usage: "Mount path for the storage",
EnvVars: []string{"SETTINGS_DATA_PATH"},
Destination: &cfg.Service.DataPath,
},
&cli.StringFlag{
Name: "jwt-secret",
Value: flags.OverrideDefaultString(cfg.TokenManager.JWTSecret, "Pive-Fumkiu4"),
Usage: "Used to create JWT to talk to reva, should equal reva's jwt-secret",
EnvVars: []string{"SETTINGS_JWT_SECRET", "OCIS_JWT_SECRET"},
Destination: &cfg.TokenManager.JWTSecret,
},
&cli.StringFlag{
Name: "extensions",
Usage: "Run specific extensions during supervised mode. This flag is set by the runtime",
},
}
}
// ListSettingsWithConfig applies list command flags to cfg
func ListSettingsWithConfig(cfg *config.Config) []cli.Flag {
return []cli.Flag{