From f52cbcd984fde1c65c74c86ec347e68729a1201d Mon Sep 17 00:00:00 2001 From: Yuri Shkuro Date: Tue, 10 Sep 2024 04:29:30 -0300 Subject: [PATCH] Support default values and erorrs for env var expansion (#10907) #### Description Support shell-style default value and error message for env var expansion. ``` // A default value for unset variable can be provided after :- suffix, for example: // `env:NAME_OF_ENVIRONMENT_VARIABLE:-default_value` ``` #### Link to tracking issue Fixes #5228 #### Testing Unit tests #### Documentation * [x] Provider Go docs * [ ] Probably needs some other docs changes? --------- Signed-off-by: Yuri Shkuro --- .chloggen/envprovider-default-value.yaml | 25 +++++++++++++ confmap/provider/envprovider/provider.go | 25 +++++++++++-- confmap/provider/envprovider/provider_test.go | 36 +++++++++++++++++++ 3 files changed, 83 insertions(+), 3 deletions(-) create mode 100644 .chloggen/envprovider-default-value.yaml diff --git a/.chloggen/envprovider-default-value.yaml b/.chloggen/envprovider-default-value.yaml new file mode 100644 index 00000000000..9528a2a41d0 --- /dev/null +++ b/.chloggen/envprovider-default-value.yaml @@ -0,0 +1,25 @@ +# 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. otlpreceiver) +component: confmap/provider/envprovider + +# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`). +note: Support default values when env var is empty + +# One or more tracking issues or pull requests related to the change +issues: [5228] + +# (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: + +# 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'] diff --git a/confmap/provider/envprovider/provider.go b/confmap/provider/envprovider/provider.go index 4db1cb7601a..8a0b87a9174 100644 --- a/confmap/provider/envprovider/provider.go +++ b/confmap/provider/envprovider/provider.go @@ -27,6 +27,11 @@ type provider struct { // // This Provider supports "env" scheme, and can be called with a selector: // `env:NAME_OF_ENVIRONMENT_VARIABLE` +// +// A default value for unset variable can be provided after :- suffix, for example: +// `env:NAME_OF_ENVIRONMENT_VARIABLE:-default_value` +// +// See also: https://opentelemetry.io/docs/specs/otel/configuration/file-configuration/#environment-variable-substitution func NewFactory() confmap.ProviderFactory { return confmap.NewProviderFactory(newProvider) } @@ -41,14 +46,18 @@ func (emp *provider) Retrieve(_ context.Context, uri string, _ confmap.WatcherFu if !strings.HasPrefix(uri, schemeName+":") { return nil, fmt.Errorf("%q uri is not supported by %q provider", uri, schemeName) } - envVarName := uri[len(schemeName)+1:] + envVarName, defaultValuePtr := parseEnvVarURI(uri[len(schemeName)+1:]) if !envvar.ValidationRegexp.MatchString(envVarName) { return nil, fmt.Errorf("environment variable %q has invalid name: must match regex %s", envVarName, envvar.ValidationPattern) - } + val, exists := os.LookupEnv(envVarName) if !exists { - emp.logger.Warn("Configuration references unset environment variable", zap.String("name", envVarName)) + if defaultValuePtr != nil { + val = *defaultValuePtr + } else { + emp.logger.Warn("Configuration references unset environment variable", zap.String("name", envVarName)) + } } else if len(val) == 0 { emp.logger.Info("Configuration references empty environment variable", zap.String("name", envVarName)) } @@ -63,3 +72,13 @@ func (*provider) Scheme() string { func (*provider) Shutdown(context.Context) error { return nil } + +// returns (var name, default value) +func parseEnvVarURI(uri string) (string, *string) { + const defaultSuffix = ":-" + if strings.Contains(uri, defaultSuffix) { + parts := strings.SplitN(uri, defaultSuffix, 2) + return parts[0], &parts[1] + } + return uri, nil +} diff --git a/confmap/provider/envprovider/provider_test.go b/confmap/provider/envprovider/provider_test.go index 1f4b99c8318..482c7c03431 100644 --- a/confmap/provider/envprovider/provider_test.go +++ b/confmap/provider/envprovider/provider_test.go @@ -154,6 +154,42 @@ func TestEmptyEnvWithLoggerWarn(t *testing.T) { assert.Equal(t, envName, logLine.Context[0].String) } +func TestEnvWithDefaultValue(t *testing.T) { + env := createProvider() + tests := []struct { + name string + unset bool + value string + uri string + expectedVal string + expectedErr string + }{ + {name: "unset", unset: true, uri: "env:MY_VAR:-default % value", expectedVal: "default % value"}, + {name: "unset2", unset: true, uri: "env:MY_VAR:-", expectedVal: ""}, // empty default still applies + {name: "empty", value: "", uri: "env:MY_VAR:-foo", expectedVal: ""}, + {name: "not empty", value: "value", uri: "env:MY_VAR:-", expectedVal: "value"}, + {name: "syntax1", unset: true, uri: "env:-MY_VAR", expectedErr: "invalid name"}, + {name: "syntax2", unset: true, uri: "env:MY_VAR:-test:-test", expectedVal: "test:-test"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if !test.unset { + t.Setenv("MY_VAR", test.value) + } + ret, err := env.Retrieve(context.Background(), test.uri, nil) + if test.expectedErr != "" { + require.ErrorContains(t, err, test.expectedErr) + return + } + require.NoError(t, err) + str, err := ret.AsString() + require.NoError(t, err) + assert.Equal(t, test.expectedVal, str) + }) + } + assert.NoError(t, env.Shutdown(context.Background())) +} + func createProvider() confmap.Provider { return NewFactory().Create(confmaptest.NewNopProviderSettings()) }