From 1f760842e2a9f6f1340fc273ce1428a36cf0e7eb Mon Sep 17 00:00:00 2001 From: Ian Adams Date: Thu, 7 Nov 2024 17:12:35 -0500 Subject: [PATCH 1/4] [cmd/opampsupervisor] feat: Support environment variable expansion in supervisor config --- cmd/opampsupervisor/go.mod | 6 +- cmd/opampsupervisor/go.sum | 12 +- .../supervisor/config/config.go | 40 ++- .../supervisor/config/config_test.go | 244 ++++++++++++++++++ 4 files changed, 285 insertions(+), 17 deletions(-) diff --git a/cmd/opampsupervisor/go.mod b/cmd/opampsupervisor/go.mod index 356ba7acd2af..f11df8cf780c 100644 --- a/cmd/opampsupervisor/go.mod +++ b/cmd/opampsupervisor/go.mod @@ -14,6 +14,9 @@ require ( github.com/stretchr/testify v1.9.0 go.opentelemetry.io/collector/config/configopaque v1.19.0 go.opentelemetry.io/collector/config/configtls v1.19.0 + go.opentelemetry.io/collector/confmap v1.19.0 + go.opentelemetry.io/collector/confmap/provider/envprovider v1.19.0 + go.opentelemetry.io/collector/confmap/provider/fileprovider v1.19.0 go.opentelemetry.io/collector/semconv v0.113.0 go.uber.org/goleak v1.3.0 go.uber.org/zap v1.27.0 @@ -25,9 +28,10 @@ require ( require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/fsnotify/fsnotify v1.8.0 // indirect - github.com/go-viper/mapstructure/v2 v2.0.0-alpha.1 // indirect + github.com/go-viper/mapstructure/v2 v2.2.1 // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/gorilla/websocket v1.5.1 // indirect + github.com/knadh/koanf/providers/confmap v0.1.0 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect diff --git a/cmd/opampsupervisor/go.sum b/cmd/opampsupervisor/go.sum index fef440361439..859fa2cc7bee 100644 --- a/cmd/opampsupervisor/go.sum +++ b/cmd/opampsupervisor/go.sum @@ -4,8 +4,8 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1 github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M= github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= -github.com/go-viper/mapstructure/v2 v2.0.0-alpha.1 h1:TQcrn6Wq+sKGkpyPvppOz99zsMBaUOKXq6HSv655U1c= -github.com/go-viper/mapstructure/v2 v2.0.0-alpha.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss= +github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -16,6 +16,8 @@ github.com/knadh/koanf/maps v0.1.1 h1:G5TjmUh2D7G2YWf5SQQqSiHRJEjaicvU0KpypqB3NI github.com/knadh/koanf/maps v0.1.1/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI= github.com/knadh/koanf/parsers/yaml v0.1.0 h1:ZZ8/iGfRLvKSaMEECEBPM1HQslrZADk8fP1XFUxVI5w= github.com/knadh/koanf/parsers/yaml v0.1.0/go.mod h1:cvbUDC7AL23pImuQP0oRw/hPuccrNBS2bps8asS0CwY= +github.com/knadh/koanf/providers/confmap v0.1.0 h1:gOkxhHkemwG4LezxxN8DMOFopOPghxRVp7JbIvdvqzU= +github.com/knadh/koanf/providers/confmap v0.1.0/go.mod h1:2uLhxQzJnyHKfxG927awZC7+fyHFdQkd697K4MdLnIU= github.com/knadh/koanf/providers/file v1.1.2 h1:aCC36YGOgV5lTtAFz2qkgtWdeQsgfxUkxDOe+2nQY3w= github.com/knadh/koanf/providers/file v1.1.2/go.mod h1:/faSBcv2mxPVjFrXck95qeoyoZ5myJ6uxN8OOVNJJCI= github.com/knadh/koanf/providers/rawbytes v0.1.0 h1:dpzgu2KO6uf6oCb4aP05KDmKmAmI51k5pe8RYKQ0qME= @@ -42,6 +44,12 @@ go.opentelemetry.io/collector/config/configopaque v1.19.0 h1:7uvntQeAAtqCaeiS2dD go.opentelemetry.io/collector/config/configopaque v1.19.0/go.mod h1:6zlLIyOoRpJJ+0bEKrlZOZon3rOp5Jrz9fMdR4twOS4= go.opentelemetry.io/collector/config/configtls v1.19.0 h1:GQ/cF1hgNqHVBq2oSSrOFXxVCyMDyd5kq4R/RMEbL98= go.opentelemetry.io/collector/config/configtls v1.19.0/go.mod h1:1hyqnYB3JqEUlk1ME/s9HYz4oCRcxQCRxsJitFFT/cA= +go.opentelemetry.io/collector/confmap v1.19.0 h1:TQ0lZpAKqgsE0EKk+u4JA+uBbPYeFRmWP3GH43w40CY= +go.opentelemetry.io/collector/confmap v1.19.0/go.mod h1:GgNu1ElPGmLn9govqIfjaopvdspw4PJ9KeDtWC4E2Q4= +go.opentelemetry.io/collector/confmap/provider/envprovider v1.19.0 h1:f8O/I5pVRN86Gx5mHekNx92S6fGdOS4VcooRJKWe6Bs= +go.opentelemetry.io/collector/confmap/provider/envprovider v1.19.0/go.mod h1:AiaW5YW1LD0/WlZuc8eZuZPBH6PA9QqsiAYRX1iC6T0= +go.opentelemetry.io/collector/confmap/provider/fileprovider v1.19.0 h1:TYwyk4ea3U+5MYcEjrzZAaonBcLlabQu8CZeB7ekAYY= +go.opentelemetry.io/collector/confmap/provider/fileprovider v1.19.0/go.mod h1:i3mL4OSGI5JM0hnzHujhJK+LDlvO3XrJxBsuclfU/jY= go.opentelemetry.io/collector/semconv v0.113.0 h1:twenSI7M7MJMJKW8D6a/GXxPZTPbama/weywBtV2iFw= go.opentelemetry.io/collector/semconv v0.113.0/go.mod h1:zCJ5njhWpejR+A40kiEoeFm1xq1uzyZwMnRNX6/D82A= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= diff --git a/cmd/opampsupervisor/supervisor/config/config.go b/cmd/opampsupervisor/supervisor/config/config.go index 68c99fa4c755..ca4914967ae0 100644 --- a/cmd/opampsupervisor/supervisor/config/config.go +++ b/cmd/opampsupervisor/supervisor/config/config.go @@ -4,6 +4,7 @@ package config import ( + "context" "errors" "fmt" "net/http" @@ -13,18 +14,18 @@ import ( "runtime" "time" - "github.com/knadh/koanf/parsers/yaml" - "github.com/knadh/koanf/providers/file" - "github.com/knadh/koanf/v2" "github.com/open-telemetry/opamp-go/protobufs" "go.opentelemetry.io/collector/config/configtls" + "go.opentelemetry.io/collector/confmap" + "go.opentelemetry.io/collector/confmap/provider/envprovider" + "go.opentelemetry.io/collector/confmap/provider/fileprovider" "go.uber.org/zap/zapcore" ) // Supervisor is the Supervisor config file format. type Supervisor struct { - Server OpAMPServer - Agent Agent + Server OpAMPServer `mapstructure:"server"` + Agent Agent `mapstructure:"agent"` Capabilities Capabilities `mapstructure:"capabilities"` Storage Storage `mapstructure:"storage"` Telemetry Telemetry `mapstructure:"telemetry"` @@ -36,18 +37,29 @@ func Load(configFile string) (Supervisor, error) { return Supervisor{}, errors.New("path to config file cannot be empty") } - k := koanf.New("::") - if err := k.Load(file.Provider(configFile), yaml.Parser()); err != nil { + resolverSettings := &confmap.ResolverSettings{ + URIs: []string{configFile}, + ProviderFactories: []confmap.ProviderFactory{ + fileprovider.NewFactory(), + envprovider.NewFactory(), + }, + ConverterFactories: []confmap.ConverterFactory{}, + DefaultScheme: "env", + } + + resolver, err := confmap.NewResolver(*resolverSettings) + if err != nil { return Supervisor{}, err } - decodeConf := koanf.UnmarshalConf{ - Tag: "mapstructure", + conf, err := resolver.Resolve(context.Background()) + if err != nil { + return Supervisor{}, err } cfg := DefaultSupervisor() - if err := k.UnmarshalWithConf("", &cfg, decodeConf); err != nil { - return Supervisor{}, fmt.Errorf("cannot parse %s: %w", configFile, err) + if err = conf.Unmarshal(&cfg); err != nil { + return Supervisor{}, err } if err := cfg.Validate(); err != nil { @@ -120,8 +132,8 @@ func (c Capabilities) SupportedCapabilities() protobufs.AgentCapabilities { } type OpAMPServer struct { - Endpoint string - Headers http.Header + Endpoint string `mapstructure:"endpoint"` + Headers http.Header `mapstructure:"headers"` TLSSetting configtls.ClientConfig `mapstructure:"tls,omitempty"` } @@ -150,7 +162,7 @@ func (o OpAMPServer) Validate() error { } type Agent struct { - Executable string + Executable string `mapstructure:"executable"` OrphanDetectionInterval time.Duration `mapstructure:"orphan_detection_interval"` Description AgentDescription `mapstructure:"description"` ConfigApplyTimeout time.Duration `mapstructure:"config_apply_timeout"` diff --git a/cmd/opampsupervisor/supervisor/config/config_test.go b/cmd/opampsupervisor/supervisor/config/config_test.go index 83e44b7b7a32..3aacb2553490 100644 --- a/cmd/opampsupervisor/supervisor/config/config_test.go +++ b/cmd/opampsupervisor/supervisor/config/config_test.go @@ -4,6 +4,8 @@ package config import ( + "errors" + "fmt" "net/http" "os" "path/filepath" @@ -13,6 +15,7 @@ import ( "github.com/open-telemetry/opamp-go/protobufs" "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/config/configtls" + "go.uber.org/zap/zapcore" ) func TestValidate(t *testing.T) { @@ -496,3 +499,244 @@ func TestCapabilities_SupportedCapabilities(t *testing.T) { }) } } + +func TestLoad(t *testing.T) { + tmpDir, err := os.MkdirTemp(os.TempDir(), "*") + require.NoError(t, err) + + t.Cleanup(func() { + require.NoError(t, os.Chmod(tmpDir, 0o700)) + require.NoError(t, os.RemoveAll(tmpDir)) + }) + + executablePath := filepath.Join(tmpDir, "binary") + err = os.WriteFile(executablePath, []byte{}, 0o600) + require.NoError(t, err) + + testCases := []struct { + desc string + testFunc func(t *testing.T) + }{ + { + desc: "Minimal Config Supervisor", + testFunc: func(t *testing.T) { + config := ` +server: + endpoint: ws://localhost/v1/opamp + +agent: + executable: %s +` + config = fmt.Sprintf(config, executablePath) + + expected := Supervisor{ + Server: OpAMPServer{ + Endpoint: "ws://localhost/v1/opamp", + }, + Capabilities: DefaultSupervisor().Capabilities, + Storage: DefaultSupervisor().Storage, + Agent: Agent{ + Executable: executablePath, + OrphanDetectionInterval: DefaultSupervisor().Agent.OrphanDetectionInterval, + ConfigApplyTimeout: DefaultSupervisor().Agent.ConfigApplyTimeout, + BootstrapTimeout: DefaultSupervisor().Agent.BootstrapTimeout, + }, + Telemetry: DefaultSupervisor().Telemetry, + } + + cfgPath := setupSupervisorConfigFile(t, tmpDir, config) + runSupervisorConfigLoadTest(t, cfgPath, expected, nil) + }, + }, + { + desc: "Full Config Supervisor", + testFunc: func(t *testing.T) { + config := ` +server: + endpoint: ws://localhost/v1/opamp + tls: + insecure: true + +capabilities: + reports_effective_config: false + reports_own_metrics: false + reports_health: false + accepts_remote_config: true + reports_remote_config: true + accepts_restart_command: true + accepts_opamp_connection_settings: true + +storage: + directory: %s + +agent: + executable: %s + description: + identifying_attributes: + "service.name": "io.opentelemetry.collector" + non_identifying_attributes: + "os.type": darwin + orphan_detection_interval: 10s + config_apply_timeout: 8s + bootstrap_timeout: 8s + health_check_port: 8089 + opamp_server_port: 8090 + passthrough_logs: true + +telemetry: + logs: + level: warn + output_paths: ["stdout"] +` + config = fmt.Sprintf(config, filepath.Join(tmpDir, "storage"), executablePath) + + expected := Supervisor{ + Server: OpAMPServer{ + Endpoint: "ws://localhost/v1/opamp", + TLSSetting: configtls.ClientConfig{ + Insecure: true, + }, + }, + Capabilities: Capabilities{ + ReportsEffectiveConfig: false, + ReportsOwnMetrics: false, + ReportsHealth: false, + AcceptsRemoteConfig: true, + ReportsRemoteConfig: true, + AcceptsRestartCommand: true, + AcceptsOpAMPConnectionSettings: true, + }, + Storage: Storage{ + Directory: filepath.Join(tmpDir, "storage"), + }, + Agent: Agent{ + Executable: executablePath, + Description: AgentDescription{ + IdentifyingAttributes: map[string]string{ + "service.name": "io.opentelemetry.collector", + }, + NonIdentifyingAttributes: map[string]string{ + "os.type": "darwin", + }, + }, + OrphanDetectionInterval: 10 * time.Second, + ConfigApplyTimeout: 8 * time.Second, + BootstrapTimeout: 8 * time.Second, + HealthCheckPort: 8089, + OpAMPServerPort: 8090, + PassthroughLogs: true, + }, + Telemetry: Telemetry{ + Logs: Logs{ + Level: zapcore.WarnLevel, + OutputPaths: []string{"stdout"}, + }, + }, + } + + cfgPath := setupSupervisorConfigFile(t, tmpDir, config) + runSupervisorConfigLoadTest(t, cfgPath, expected, nil) + }, + }, + { + desc: "Environment Variable Config Supervisor", + testFunc: func(t *testing.T) { + config := ` +server: + endpoint: ${TEST_ENDPOINT} + +agent: + executable: ${TEST_EXECUTABLE_PATH} +` + expected := Supervisor{ + Server: OpAMPServer{ + Endpoint: "ws://localhost/v1/opamp", + }, + Capabilities: DefaultSupervisor().Capabilities, + Storage: DefaultSupervisor().Storage, + Agent: Agent{ + Executable: executablePath, + OrphanDetectionInterval: DefaultSupervisor().Agent.OrphanDetectionInterval, + ConfigApplyTimeout: DefaultSupervisor().Agent.ConfigApplyTimeout, + BootstrapTimeout: DefaultSupervisor().Agent.BootstrapTimeout, + }, + Telemetry: DefaultSupervisor().Telemetry, + } + + require.NoError(t, os.Setenv("TEST_ENDPOINT", "ws://localhost/v1/opamp")) + require.NoError(t, os.Setenv("TEST_EXECUTABLE_PATH", executablePath)) + defer func() { + require.NoError(t, os.Unsetenv("TEST_ENDPOINT")) + require.NoError(t, os.Unsetenv("TEST_EXECUTABLE_PATH")) + }() + + cfgPath := setupSupervisorConfigFile(t, tmpDir, config) + runSupervisorConfigLoadTest(t, cfgPath, expected, nil) + }, + }, + { + desc: "Empty Config Filepath", + testFunc: func(t *testing.T) { + runSupervisorConfigLoadTest(t, "", Supervisor{}, errors.New("path to config file cannot be empty")) + }, + }, + { + desc: "Nonexistent Config File", + testFunc: func(t *testing.T) { + config := ` +server: + endpoint: ws://localhost/v1/opamp + +agent: + executable: %s +` + config = fmt.Sprintf(config, executablePath) + + cfgPath := setupSupervisorConfigFile(t, tmpDir, config) + require.NoError(t, os.Remove(cfgPath)) + runSupervisorConfigLoadTest(t, cfgPath, Supervisor{}, errors.New("cannot retrieve the configuration: unable to read the file")) + }, + }, + { + desc: "Failed Validation Supervisor", + testFunc: func(t *testing.T) { + config := ` +server: + +agent: + executable: %s +` + config = fmt.Sprintf(config, executablePath) + cfgPath := setupSupervisorConfigFile(t, tmpDir, config) + runSupervisorConfigLoadTest(t, cfgPath, Supervisor{}, errors.New("cannot validate supervisor config")) + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.desc, tc.testFunc) + } +} + +func setupSupervisorConfigFile(t *testing.T, tmpDir, configString string) string { + t.Helper() + + testDir, err := os.MkdirTemp(tmpDir, "*") + require.NoError(t, err) + cfgPath := filepath.Join(testDir, "config.yaml") + err = os.WriteFile(cfgPath, []byte(configString), 0o600) + require.NoError(t, err) + return cfgPath +} + +func runSupervisorConfigLoadTest(t *testing.T, cfgPath string, expected Supervisor, expectedErr error) { + t.Helper() + + cfg, err := Load(cfgPath) + if expectedErr != nil { + require.ErrorContains(t, err, expectedErr.Error()) + return + } + require.NoError(t, err) + require.Equal(t, expected, cfg) +} From a948c519bfbd9487f6e7b76a9ef7273abc9e30fe Mon Sep 17 00:00:00 2001 From: Ian Adams Date: Thu, 7 Nov 2024 17:18:44 -0500 Subject: [PATCH 2/4] Minor pointer correction --- cmd/opampsupervisor/supervisor/config/config.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/opampsupervisor/supervisor/config/config.go b/cmd/opampsupervisor/supervisor/config/config.go index ca4914967ae0..f424964f9a4b 100644 --- a/cmd/opampsupervisor/supervisor/config/config.go +++ b/cmd/opampsupervisor/supervisor/config/config.go @@ -37,7 +37,7 @@ func Load(configFile string) (Supervisor, error) { return Supervisor{}, errors.New("path to config file cannot be empty") } - resolverSettings := &confmap.ResolverSettings{ + resolverSettings := confmap.ResolverSettings{ URIs: []string{configFile}, ProviderFactories: []confmap.ProviderFactory{ fileprovider.NewFactory(), @@ -47,7 +47,7 @@ func Load(configFile string) (Supervisor, error) { DefaultScheme: "env", } - resolver, err := confmap.NewResolver(*resolverSettings) + resolver, err := confmap.NewResolver(resolverSettings) if err != nil { return Supervisor{}, err } From 7ce6edad8f9fc4a5b51b5b61a551f177323756e0 Mon Sep 17 00:00:00 2001 From: Ian Adams Date: Fri, 8 Nov 2024 10:39:12 -0500 Subject: [PATCH 3/4] Add changelog entry --- .chloggen/opamp_supervisor_env_vars.yaml | 27 ++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .chloggen/opamp_supervisor_env_vars.yaml diff --git a/.chloggen/opamp_supervisor_env_vars.yaml b/.chloggen/opamp_supervisor_env_vars.yaml new file mode 100644 index 000000000000..71aae42860bc --- /dev/null +++ b/.chloggen/opamp_supervisor_env_vars.yaml @@ -0,0 +1,27 @@ +# Use this changelog template to create an entry for release notes. + +# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix' +change_type: enhancement + +# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver) +component: cmd/opampsupervisor + +# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`). +note: Support environment variable expansion in the OpAMP supervisor config. + +# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists. +issues: [36269] + +# (Optional) One or more lines of additional information to render under the primary note. +# These lines will be padded with 2 spaces and then inserted directly into the document. +# Use pipe (|) for multiline entries. +subtext: + +# If your change doesn't affect end users or the exported elements of any package, +# you should instead start your pull request title with [chore] or use the "Skip Changelog" label. +# Optional: The change log or logs in which this entry should be included. +# e.g. '[user]' or '[user, api]' +# Include 'user' if the change is relevant to end users. +# Include 'api' if there is a change to a library API. +# Default: '[user]' +change_logs: [user] \ No newline at end of file From f29bcae0d594f4d3a265fe5eae2f6515e4b95abd Mon Sep 17 00:00:00 2001 From: Ian Adams Date: Fri, 8 Nov 2024 10:42:56 -0500 Subject: [PATCH 4/4] Add newline to end of changelog entry --- .chloggen/opamp_supervisor_env_vars.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.chloggen/opamp_supervisor_env_vars.yaml b/.chloggen/opamp_supervisor_env_vars.yaml index 71aae42860bc..ce8ed2841ec4 100644 --- a/.chloggen/opamp_supervisor_env_vars.yaml +++ b/.chloggen/opamp_supervisor_env_vars.yaml @@ -24,4 +24,4 @@ subtext: # Include 'user' if the change is relevant to end users. # Include 'api' if there is a change to a library API. # Default: '[user]' -change_logs: [user] \ No newline at end of file +change_logs: [user]