| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package confmap // import "go.opentelemetry.io/collector/confmap" |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"fmt" |
| 9 |
"time" |
| 10 |
|
| 11 |
"go.uber.org/zap" |
| 12 |
yaml "go.yaml.in/yaml/v3" |
| 13 |
) |
| 14 |
|
| 15 |
// ProviderSettings are the settings to initialize a Provider. |
| 16 |
type ProviderSettings struct { |
| 17 |
// Logger is a zap.Logger that will be passed to Providers. |
| 18 |
// Providers should be able to rely on the Logger being non-nil; |
| 19 |
// when instantiating a Provider with a ProviderFactory, |
| 20 |
// nil Logger references should be replaced with a no-op Logger. |
| 21 |
Logger *zap.Logger |
| 22 |
|
| 23 |
// prevent unkeyed literal initialization |
| 24 |
_ struct{} |
| 25 |
} |
| 26 |
|
| 27 |
// ProviderFactory defines a factory that can be used to instantiate |
| 28 |
// new instances of a Provider. |
| 29 |
type ProviderFactory = moduleFactory[Provider, ProviderSettings] |
| 30 |
|
| 31 |
// CreateProviderFunc is a function that creates a Provider instance. |
| 32 |
type CreateProviderFunc = createConfmapFunc[Provider, ProviderSettings] |
| 33 |
|
| 34 |
// NewProviderFactory can be used to create a ProviderFactory. |
| 35 |
func NewProviderFactory(f CreateProviderFunc) ProviderFactory { |
| 36 |
return newConfmapModuleFactory(f) |
| 37 |
} |
| 38 |
|
| 39 |
// Provider is an interface that helps to retrieve a config map and watch for any |
| 40 |
// changes to the config map. Implementations may load the config from a file, |
| 41 |
// a database or any other source. |
| 42 |
// |
| 43 |
// The typical usage is the following: |
| 44 |
// |
| 45 |
// r, err := provider.Retrieve("file:/path/to/config") |
| 46 |
// // Use r.Map; wait for watcher to be called. |
| 47 |
// r.Close() |
| 48 |
// r, err = provider.Retrieve("file:/path/to/config") |
| 49 |
// // Use r.Map; wait for watcher to be called. |
| 50 |
// r.Close() |
| 51 |
// // repeat retrieve/wait/close cycle until it is time to shut down the Collector process. |
| 52 |
// // ... |
| 53 |
// provider.Shutdown() |
| 54 |
type Provider interface { |
| 55 |
// Retrieve goes to the configuration source and retrieves the selected data which |
| 56 |
// contains the value to be injected in the configuration and the corresponding watcher that |
| 57 |
// will be used to monitor for updates of the retrieved value. |
| 58 |
// |
| 59 |
// `uri` must follow the "<scheme>:<opaque_data>" format. This format is compatible |
| 60 |
// with the URI definition (see https://datatracker.ietf.org/doc/html/rfc3986). The "<scheme>" |
| 61 |
// must be always included in the `uri`. The "<scheme>" supported by any provider: |
| 62 |
// - MUST consist of a sequence of characters beginning with a letter and followed by any |
| 63 |
// combination of letters, digits, plus ("+"), period ("."), or hyphen ("-"). |
| 64 |
// See https://datatracker.ietf.org/doc/html/rfc3986#section-3.1. |
| 65 |
// - MUST be at least 2 characters long to avoid conflicting with a driver-letter identifier as specified |
| 66 |
// in https://tools.ietf.org/id/draft-kerwin-file-scheme-07.html#syntax. |
| 67 |
// - For testing, all implementation MUST check that confmaptest.ValidateProviderScheme returns no error. |
| 68 |
// |
| 69 |
// `watcher` callback is called when the config changes. watcher may be called from |
| 70 |
// a different go routine. After watcher is called, Provider.Retrieve should be called |
| 71 |
// to get the new config. See description of Retrieved for more details. |
| 72 |
// watcher may be nil, which indicates that the caller is not interested in |
| 73 |
// knowing about the changes. |
| 74 |
// |
| 75 |
// If ctx is cancelled should return immediately with an error. |
| 76 |
// Should never be called concurrently with itself or with Shutdown. |
| 77 |
Retrieve(ctx context.Context, uri string, watcher WatcherFunc) (*Retrieved, error) |
| 78 |
|
| 79 |
// Scheme returns the location scheme used by Retrieve. |
| 80 |
Scheme() string |
| 81 |
|
| 82 |
// Shutdown signals that the configuration for which this Provider was used to |
| 83 |
// retrieve values is no longer in use and the Provider should close and release |
| 84 |
// any resources that it may have created. |
| 85 |
// |
| 86 |
// This method must be called when the Collector service ends, either in case of |
| 87 |
// success or error. Retrieve cannot be called after Shutdown. |
| 88 |
// |
| 89 |
// Provider MUST shutdown and wait for any goroutine(s) that were created to call `watcher`, if any. |
| 90 |
// |
| 91 |
// Should never be called concurrently with itself or with Retrieve. |
| 92 |
// If ctx is cancelled should return immediately with an error. |
| 93 |
Shutdown(ctx context.Context) error |
| 94 |
} |
| 95 |
|
| 96 |
type WatcherFunc func(*ChangeEvent) |
| 97 |
|
| 98 |
// ChangeEvent describes the particular change event that happened with the config. |
| 99 |
type ChangeEvent struct { |
| 100 |
// Error is nil if the config is changed and needs to be re-fetched. |
| 101 |
// Any non-nil error indicates that there was a problem with watching the config changes. |
| 102 |
Error error |
| 103 |
// prevent unkeyed literal initialization |
| 104 |
_ struct{} |
| 105 |
} |
| 106 |
|
| 107 |
// Retrieved holds the result of a call to the Retrieve method of a Provider object. |
| 108 |
type Retrieved struct { |
| 109 |
rawConf any |
| 110 |
errorHint error |
| 111 |
closeFunc CloseFunc |
| 112 |
|
| 113 |
stringRepresentation string |
| 114 |
isSetString bool |
| 115 |
} |
| 116 |
|
| 117 |
type retrievedSettings struct { |
| 118 |
errorHint error |
| 119 |
stringRepresentation string |
| 120 |
isSetString bool |
| 121 |
closeFunc CloseFunc |
| 122 |
} |
| 123 |
|
| 124 |
// RetrievedOption options to customize Retrieved values. |
| 125 |
type RetrievedOption interface { |
| 126 |
apply(*retrievedSettings) |
| 127 |
} |
| 128 |
|
| 129 |
type retrievedOptionFunc func(*retrievedSettings) |
| 130 |
|
| 131 |
func (of retrievedOptionFunc) apply(e *retrievedSettings) { |
| 132 |
of(e) |
| 133 |
} |
| 134 |
|
| 135 |
// WithRetrievedClose overrides the default Retrieved.Close function. |
| 136 |
// The default Retrieved.Close function does nothing and always returns nil. |
| 137 |
func WithRetrievedClose(closeFunc CloseFunc) RetrievedOption { |
| 138 |
return retrievedOptionFunc(func(settings *retrievedSettings) { |
| 139 |
settings.closeFunc = closeFunc |
| 140 |
}) |
| 141 |
} |
| 142 |
|
| 143 |
func withStringRepresentation(stringRepresentation string) RetrievedOption { |
| 144 |
return retrievedOptionFunc(func(settings *retrievedSettings) { |
| 145 |
settings.stringRepresentation = stringRepresentation |
| 146 |
settings.isSetString = true |
| 147 |
}) |
| 148 |
} |
| 149 |
|
| 150 |
func withErrorHint(errorHint error) RetrievedOption { |
| 151 |
return retrievedOptionFunc(func(settings *retrievedSettings) { |
| 152 |
settings.errorHint = errorHint |
| 153 |
}) |
| 154 |
} |
| 155 |
|
| 156 |
// NewRetrievedFromYAML returns a new Retrieved instance that contains the deserialized data from the yaml bytes. |
| 157 |
// * yamlBytes the yaml bytes that will be deserialized. |
| 158 |
// * opts specifies options associated with this Retrieved value, such as CloseFunc. |
| 159 |
func NewRetrievedFromYAML(yamlBytes []byte, opts ...RetrievedOption) (*Retrieved, error) { |
| 160 |
var rawConf any |
| 161 |
if err := yaml.Unmarshal(yamlBytes, &rawConf); err != nil { |
| 162 |
// If the string is not valid YAML, we try to use it verbatim as a string. |
| 163 |
strRep := string(yamlBytes) |
| 164 |
return NewRetrieved(strRep, append(opts, |
| 165 |
withStringRepresentation(strRep), |
| 166 |
withErrorHint(fmt.Errorf("assuming string type since contents are not valid YAML: %w", err)), |
| 167 |
)...) |
| 168 |
} |
| 169 |
|
| 170 |
switch rawConf.(type) { |
| 171 |
case string: |
| 172 |
val := string(yamlBytes) |
| 173 |
return NewRetrieved(val, append(opts, withStringRepresentation(val))...) |
| 174 |
default: |
| 175 |
opts = append(opts, withStringRepresentation(string(yamlBytes))) |
| 176 |
} |
| 177 |
|
| 178 |
return NewRetrieved(rawConf, opts...) |
| 179 |
} |
| 180 |
|
| 181 |
// NewRetrieved returns a new Retrieved instance that contains the data from the raw deserialized config. |
| 182 |
// The rawConf can be one of the following types: |
| 183 |
// - Primitives: int, int32, int64, float32, float64, bool, string; |
| 184 |
// - []any; |
| 185 |
// - map[string]any; |
| 186 |
func NewRetrieved(rawConf any, opts ...RetrievedOption) (*Retrieved, error) { |
| 187 |
if err := checkRawConfType(rawConf); err != nil { |
| 188 |
return nil, err |
| 189 |
} |
| 190 |
set := retrievedSettings{} |
| 191 |
for _, opt := range opts { |
| 192 |
opt.apply(&set) |
| 193 |
} |
| 194 |
return &Retrieved{ |
| 195 |
rawConf: rawConf, |
| 196 |
errorHint: set.errorHint, |
| 197 |
closeFunc: set.closeFunc, |
| 198 |
stringRepresentation: set.stringRepresentation, |
| 199 |
isSetString: set.isSetString, |
| 200 |
}, nil |
| 201 |
} |
| 202 |
|
| 203 |
// AsConf returns the retrieved configuration parsed as a Conf. |
| 204 |
func (r *Retrieved) AsConf() (*Conf, error) { |
| 205 |
if r.rawConf == nil { |
| 206 |
return New(), nil |
| 207 |
} |
| 208 |
val, ok := r.rawConf.(map[string]any) |
| 209 |
if !ok { |
| 210 |
if r.errorHint != nil { |
| 211 |
return nil, fmt.Errorf("retrieved value (type=%T) cannot be used as a Conf: %w", r.rawConf, r.errorHint) |
| 212 |
} |
| 213 |
return nil, fmt.Errorf("retrieved value (type=%T) cannot be used as a Conf", r.rawConf) |
| 214 |
} |
| 215 |
return NewFromStringMap(val), nil |
| 216 |
} |
| 217 |
|
| 218 |
// AsRaw returns the retrieved configuration parsed as an any which can be one of the following types: |
| 219 |
// - Primitives: int, int32, int64, float32, float64, bool, string; |
| 220 |
// - []any - every member follows the same rules as the given any; |
| 221 |
// - map[string]any - every value follows the same rules as the given any; |
| 222 |
func (r *Retrieved) AsRaw() (any, error) { |
| 223 |
return r.rawConf, nil |
| 224 |
} |
| 225 |
|
| 226 |
// AsString returns the retrieved configuration as a string. |
| 227 |
// If the retrieved configuration is not convertible to a string unambiguously, an error is returned. |
| 228 |
// If the retrieved configuration is a string, the string is returned. |
| 229 |
// This method is used to resolve ${} references in inline position. |
| 230 |
func (r *Retrieved) AsString() (string, error) { |
| 231 |
if !r.isSetString { |
| 232 |
if str, ok := r.rawConf.(string); ok { |
| 233 |
return str, nil |
| 234 |
} |
| 235 |
return "", fmt.Errorf("retrieved value does not have unambiguous string representation: %v", r.rawConf) |
| 236 |
} |
| 237 |
return r.stringRepresentation, nil |
| 238 |
} |
| 239 |
|
| 240 |
// Close and release any watchers that Provider.Retrieve may have created. |
| 241 |
// |
| 242 |
// Should block until all resources are closed, and guarantee that `onChange` is not |
| 243 |
// going to be called after it returns except when `ctx` is cancelled. |
| 244 |
// |
| 245 |
// Should never be called concurrently with itself. |
| 246 |
func (r *Retrieved) Close(ctx context.Context) error { |
| 247 |
if r.closeFunc == nil { |
| 248 |
return nil |
| 249 |
} |
| 250 |
return r.closeFunc(ctx) |
| 251 |
} |
| 252 |
|
| 253 |
// CloseFunc a function equivalent to Retrieved.Close. |
| 254 |
type CloseFunc func(context.Context) error |
| 255 |
|
| 256 |
func checkRawConfType(rawConf any) error { |
| 257 |
if rawConf == nil { |
| 258 |
return nil |
| 259 |
} |
| 260 |
switch rawConf.(type) { |
| 261 |
case int, int32, int64, float32, float64, bool, string, []any, map[string]any, time.Time: |
| 262 |
return nil |
| 263 |
default: |
| 264 |
return fmt.Errorf( |
| 265 |
"unsupported type=%T for retrieved config,"+ |
| 266 |
" ensure that values are wrapped in quotes", rawConf) |
| 267 |
} |
| 268 |
} |