forked from open-telemetry/opentelemetry-collector
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprovider.go
More file actions
84 lines (70 loc) · 2.38 KB
/
provider.go
File metadata and controls
84 lines (70 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package envprovider // import "go.opentelemetry.io/collector/confmap/provider/envprovider"
import (
"context"
"fmt"
"os"
"strings"
"go.uber.org/zap"
"go.opentelemetry.io/collector/confmap"
"go.opentelemetry.io/collector/confmap/internal/envvar"
)
const (
schemeName = "env"
)
type provider struct {
logger *zap.Logger
}
// NewFactory returns a factory for a confmap.Provider that reads the configuration from the given environment variable.
//
// 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)
}
func newProvider(ps confmap.ProviderSettings) confmap.Provider {
return &provider{
logger: ps.Logger,
}
}
func (emp *provider) Retrieve(_ context.Context, uri string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {
if !strings.HasPrefix(uri, schemeName+":") {
return nil, fmt.Errorf("%q uri is not supported by %q provider", uri, schemeName)
}
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 {
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))
}
return confmap.NewRetrievedFromYAML([]byte(val))
}
func (*provider) Scheme() string {
return schemeName
}
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
}