| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package internal // import "go.opentelemetry.io/collector/confmap/internal" |
| 5 |
|
| 6 |
import ( |
| 7 |
"encoding" |
| 8 |
"errors" |
| 9 |
"fmt" |
| 10 |
"maps" |
| 11 |
"reflect" |
| 12 |
"slices" |
| 13 |
"strings" |
| 14 |
|
| 15 |
"github.com/go-viper/mapstructure/v2" |
| 16 |
|
| 17 |
"go.opentelemetry.io/collector/confmap/internal/third_party/composehook" |
| 18 |
) |
| 19 |
|
| 20 |
const ( |
| 21 |
// MapstructureTag is the struct field tag used to record marshaling/unmarshaling settings. |
| 22 |
// See https://pkg.go.dev/github.com/go-viper/mapstructure/v2 for supported values. |
| 23 |
MapstructureTag = "mapstructure" |
| 24 |
) |
| 25 |
|
| 26 |
// WithIgnoreUnused sets an option to ignore errors if existing |
| 27 |
// keys in the original Conf were unused in the decoding process |
| 28 |
// (extra keys). |
| 29 |
func WithIgnoreUnused() UnmarshalOption { |
| 30 |
return UnmarshalOptionFunc(func(uo *UnmarshalOptions) { |
| 31 |
uo.IgnoreUnused = true |
| 32 |
}) |
| 33 |
} |
| 34 |
|
| 35 |
// Decode decodes the contents of the Conf into the result argument, using a |
| 36 |
// mapstructure decoder with the following notable behaviors. Ensures that maps whose |
| 37 |
// values are nil pointer structs resolved to the zero value of the target struct (see |
| 38 |
// expandNilStructPointers). Converts string to []string by splitting on ','. Ensures |
| 39 |
// uniqueness of component IDs (see mapKeyStringToMapKeyTextUnmarshalerHookFunc). |
| 40 |
// Decodes time.Duration from strings. Allows custom unmarshaling for structs implementing |
| 41 |
// encoding.TextUnmarshaler. Allows custom unmarshaling for structs implementing confmap.Unmarshaler. |
| 42 |
func Decode(input, result any, settings UnmarshalOptions, skipTopLevelUnmarshaler bool) error { |
| 43 |
dc := &mapstructure.DecoderConfig{ |
| 44 |
ErrorUnused: !settings.IgnoreUnused, |
| 45 |
Result: result, |
| 46 |
TagName: MapstructureTag, |
| 47 |
WeaklyTypedInput: false, |
| 48 |
MatchName: caseSensitiveMatchName, |
| 49 |
DecodeNil: true, |
| 50 |
DecodeHook: composehook.ComposeDecodeHookFunc( |
| 51 |
useExpandValue(), |
| 52 |
expandNilStructPointersHookFunc(), |
| 53 |
mapstructure.StringToSliceHookFunc(","), |
| 54 |
mapKeyStringToMapKeyTextUnmarshalerHookFunc(), |
| 55 |
mapstructure.StringToTimeDurationHookFunc(), |
| 56 |
mapstructure.TextUnmarshallerHookFunc(), |
| 57 |
unmarshalerHookFunc(result, skipTopLevelUnmarshaler), |
| 58 |
// after the main unmarshaler hook is called, |
| 59 |
// we unmarshal the embedded structs if present to merge with the result: |
| 60 |
unmarshalerEmbeddedStructsHookFunc(), |
| 61 |
zeroSliceAndMapHookFunc(), |
| 62 |
), |
| 63 |
} |
| 64 |
decoder, err := mapstructure.NewDecoder(dc) |
| 65 |
if err != nil { |
| 66 |
return err |
| 67 |
} |
| 68 |
if err = decoder.Decode(input); err != nil { |
| 69 |
if strings.HasPrefix(err.Error(), "error decoding ''") { |
| 70 |
return errors.Unwrap(err) |
| 71 |
} |
| 72 |
return err |
| 73 |
} |
| 74 |
return nil |
| 75 |
} |
| 76 |
|
| 77 |
// When a value has been loaded from an external source via a provider, we keep both the |
| 78 |
// parsed value and the original string value. This allows us to expand the value to its |
| 79 |
// original string representation when decoding into a string field, and use the original otherwise. |
| 80 |
func useExpandValue() mapstructure.DecodeHookFuncType { |
| 81 |
return func( |
| 82 |
_ reflect.Type, |
| 83 |
to reflect.Type, |
| 84 |
data any, |
| 85 |
) (any, error) { |
| 86 |
if exp, ok := data.(ExpandedValue); ok { |
| 87 |
v := castTo(exp, to.Kind() == reflect.String) |
| 88 |
// See https://github.com/open-telemetry/opentelemetry-collector/issues/10949 |
| 89 |
// If the `to.Kind` is not a string, then expandValue's original value is useless and |
| 90 |
// the casted-to value will be nil. In that scenario, we need to use the default value of `to`'s kind. |
| 91 |
if v == nil { |
| 92 |
return reflect.Zero(to).Interface(), nil |
| 93 |
} |
| 94 |
return v, nil |
| 95 |
} |
| 96 |
|
| 97 |
switch to.Kind() { |
| 98 |
case reflect.Array, reflect.Slice, reflect.Map: |
| 99 |
if isStringyStructure(to) { |
| 100 |
// If the target field is a stringy structure, sanitize to use the original string value everywhere. |
| 101 |
return sanitizeToStr(data), nil |
| 102 |
} |
| 103 |
// Otherwise, sanitize to use the parsed value everywhere. |
| 104 |
return sanitize(data), nil |
| 105 |
} |
| 106 |
return data, nil |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
// In cases where a config has a mapping of something to a struct pointers |
| 111 |
// we want nil values to resolve to a pointer to the zero value of the |
| 112 |
// underlying struct just as we want nil values of a mapping of something |
| 113 |
// to a struct to resolve to the zero value of that struct. |
| 114 |
// |
| 115 |
// e.g. given a config type: |
| 116 |
// type Config struct { Thing *SomeStruct `mapstructure:"thing"` } |
| 117 |
// |
| 118 |
// and yaml of: |
| 119 |
// config: |
| 120 |
// |
| 121 |
// thing: |
| 122 |
// |
| 123 |
// we want an unmarshaled Config to be equivalent to |
| 124 |
// Config{Thing: &SomeStruct{}} instead of Config{Thing: nil} |
| 125 |
func expandNilStructPointersHookFunc() mapstructure.DecodeHookFuncValue { |
| 126 |
return safeWrapDecodeHookFunc(func(from, to reflect.Value) (any, error) { |
| 127 |
// ensure we are dealing with map to map comparison |
| 128 |
if from.Kind() == reflect.Map && to.Kind() == reflect.Map { |
| 129 |
toElem := to.Type().Elem() |
| 130 |
// ensure that map values are pointers to a struct |
| 131 |
// (that may be nil and require manual setting w/ zero value) |
| 132 |
if toElem.Kind() == reflect.Ptr && toElem.Elem().Kind() == reflect.Struct { |
| 133 |
fromRange := from.MapRange() |
| 134 |
for fromRange.Next() { |
| 135 |
fromKey := fromRange.Key() |
| 136 |
fromValue := fromRange.Value() |
| 137 |
// ensure that we've run into a nil pointer instance |
| 138 |
if fromValue.IsNil() { |
| 139 |
newFromValue := reflect.New(toElem.Elem()) |
| 140 |
from.SetMapIndex(fromKey, newFromValue) |
| 141 |
} |
| 142 |
} |
| 143 |
} |
| 144 |
} |
| 145 |
return from.Interface(), nil |
| 146 |
}) |
| 147 |
} |
| 148 |
|
| 149 |
// mapKeyStringToMapKeyTextUnmarshalerHookFunc returns a DecodeHookFuncType that checks that a conversion from |
| 150 |
// map[string]any to map[encoding.TextUnmarshaler]any does not overwrite keys, |
| 151 |
// when UnmarshalText produces equal elements from different strings (e.g. trims whitespaces). |
| 152 |
// |
| 153 |
// This is needed in combination with ComponentID, which may produce equal IDs for different strings, |
| 154 |
// and an error needs to be returned in that case, otherwise the last equivalent ID overwrites the previous one. |
| 155 |
func mapKeyStringToMapKeyTextUnmarshalerHookFunc() mapstructure.DecodeHookFuncType { |
| 156 |
return func(from, to reflect.Type, data any) (any, error) { |
| 157 |
if from.Kind() != reflect.Map || from.Key().Kind() != reflect.String { |
| 158 |
return data, nil |
| 159 |
} |
| 160 |
|
| 161 |
if to.Kind() != reflect.Map { |
| 162 |
return data, nil |
| 163 |
} |
| 164 |
|
| 165 |
// Checks that the key type of to implements the TextUnmarshaler interface. |
| 166 |
if _, ok := reflect.New(to.Key()).Interface().(encoding.TextUnmarshaler); !ok { |
| 167 |
return data, nil |
| 168 |
} |
| 169 |
|
| 170 |
// Create a map with key value of to's key to bool. |
| 171 |
fieldNameSet := reflect.MakeMap(reflect.MapOf(to.Key(), reflect.TypeFor[bool]())) |
| 172 |
for k := range data.(map[string]any) { |
| 173 |
// Create a new value of the to's key type. |
| 174 |
tKey := reflect.New(to.Key()) |
| 175 |
|
| 176 |
// Use tKey to unmarshal the key of the map. |
| 177 |
if err := tKey.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(k)); err != nil { |
| 178 |
return nil, err |
| 179 |
} |
| 180 |
// Checks if the key has already been decoded in a previous iteration. |
| 181 |
if fieldNameSet.MapIndex(reflect.Indirect(tKey)).IsValid() { |
| 182 |
return nil, fmt.Errorf("duplicate name %q after unmarshaling %v", k, tKey) |
| 183 |
} |
| 184 |
fieldNameSet.SetMapIndex(reflect.Indirect(tKey), reflect.ValueOf(true)) |
| 185 |
} |
| 186 |
return data, nil |
| 187 |
} |
| 188 |
} |
| 189 |
|
| 190 |
// unmarshalerEmbeddedStructsHookFunc provides a mechanism for embedded structs to define their own unmarshal logic, |
| 191 |
// by implementing the Unmarshaler interface. |
| 192 |
func unmarshalerEmbeddedStructsHookFunc() mapstructure.DecodeHookFuncValue { |
| 193 |
return safeWrapDecodeHookFunc(func(from, to reflect.Value) (any, error) { |
| 194 |
if to.Type().Kind() != reflect.Struct { |
| 195 |
return from.Interface(), nil |
| 196 |
} |
| 197 |
fromAsMap, ok := from.Interface().(map[string]any) |
| 198 |
if !ok { |
| 199 |
return from.Interface(), nil |
| 200 |
} |
| 201 |
for i := 0; i < to.Type().NumField(); i++ { |
| 202 |
// embedded structs passed in via `squash` cannot be pointers. We just check if they are structs: |
| 203 |
f := to.Type().Field(i) |
| 204 |
if f.IsExported() && slices.Contains(strings.Split(f.Tag.Get(MapstructureTag), ","), "squash") { |
| 205 |
if unmarshaler, ok := to.Field(i).Addr().Interface().(Unmarshaler); ok { |
| 206 |
c := NewFromStringMap(fromAsMap) |
| 207 |
c.skipTopLevelUnmarshaler = true |
| 208 |
if err := unmarshaler.Unmarshal(c); err != nil { |
| 209 |
return nil, err |
| 210 |
} |
| 211 |
// the struct we receive from this unmarshaling only contains fields related to the embedded struct. |
| 212 |
// we merge this partially unmarshaled struct with the rest of the result. |
| 213 |
// note we already unmarshaled the main struct earlier, and therefore merge with it. |
| 214 |
conf := New() |
| 215 |
if err := conf.Marshal(unmarshaler); err != nil { |
| 216 |
return nil, err |
| 217 |
} |
| 218 |
resultMap := conf.ToStringMap() |
| 219 |
if fromAsMap == nil && len(resultMap) > 0 { |
| 220 |
fromAsMap = make(map[string]any, len(resultMap)) |
| 221 |
} |
| 222 |
maps.Copy(fromAsMap, resultMap) |
| 223 |
} |
| 224 |
} |
| 225 |
} |
| 226 |
return fromAsMap, nil |
| 227 |
}) |
| 228 |
} |
| 229 |
|
| 230 |
// Provides a mechanism for individual structs to define their own unmarshal logic, |
| 231 |
// by implementing the Unmarshaler interface, unless skipTopLevelUnmarshaler is |
| 232 |
// true and the struct matches the top level object being unmarshaled. |
| 233 |
func unmarshalerHookFunc(result any, skipTopLevelUnmarshaler bool) mapstructure.DecodeHookFuncValue { |
| 234 |
return safeWrapDecodeHookFunc(func(from, to reflect.Value) (any, error) { |
| 235 |
if !to.CanAddr() { |
| 236 |
return from.Interface(), nil |
| 237 |
} |
| 238 |
|
| 239 |
toPtr := to.Addr().Interface() |
| 240 |
// Need to ignore the top structure to avoid running into an infinite recursion |
| 241 |
// where Unmarshaler.Unmarshal and Conf.Unmarshal would call each other. |
| 242 |
if toPtr == result && skipTopLevelUnmarshaler { |
| 243 |
return from.Interface(), nil |
| 244 |
} |
| 245 |
|
| 246 |
unmarshaler, ok := toPtr.(Unmarshaler) |
| 247 |
if !ok { |
| 248 |
return from.Interface(), nil |
| 249 |
} |
| 250 |
|
| 251 |
if _, ok = from.Interface().(map[string]any); !ok { |
| 252 |
return from.Interface(), nil |
| 253 |
} |
| 254 |
|
| 255 |
// Use the current object if not nil (to preserve other configs in the object), otherwise zero initialize. |
| 256 |
if to.Addr().IsNil() { |
| 257 |
unmarshaler = reflect.New(to.Type()).Interface().(Unmarshaler) |
| 258 |
} |
| 259 |
|
| 260 |
c := NewFromStringMap(from.Interface().(map[string]any)) |
| 261 |
c.skipTopLevelUnmarshaler = true |
| 262 |
if err := unmarshaler.Unmarshal(c); err != nil { |
| 263 |
return nil, err |
| 264 |
} |
| 265 |
|
| 266 |
return unmarshaler, nil |
| 267 |
}) |
| 268 |
} |
| 269 |
|
| 270 |
// safeWrapDecodeHookFunc wraps a DecodeHookFuncValue to ensure fromVal is a valid `reflect.Value` |
| 271 |
// object and therefore it is safe to call `reflect.Value` methods on fromVal. |
| 272 |
// |
| 273 |
// Use this only if the hook does not need to be called on untyped nil values. |
| 274 |
// Typed nil values are safe to call and will be passed to the hook. |
| 275 |
// See https://github.com/golang/go/issues/51649 |
| 276 |
func safeWrapDecodeHookFunc( |
| 277 |
f mapstructure.DecodeHookFuncValue, |
| 278 |
) mapstructure.DecodeHookFuncValue { |
| 279 |
return func(fromVal, toVal reflect.Value) (any, error) { |
| 280 |
if !fromVal.IsValid() { |
| 281 |
return nil, nil |
| 282 |
} |
| 283 |
return f(fromVal, toVal) |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
// This hook is used to solve the issue: https://github.com/open-telemetry/opentelemetry-collector/issues/4001 |
| 288 |
// We adopt the suggestion provided in this issue: https://github.com/mitchellh/mapstructure/issues/74#issuecomment-279886492 |
| 289 |
// We should empty every slice before unmarshalling unless user provided slice is nil. |
| 290 |
// Assume that we had a struct with a field of type slice called `keys`, which has default values of ["a", "b"] |
| 291 |
// |
| 292 |
// type Config struct { |
| 293 |
// Keys []string `mapstructure:"keys"` |
| 294 |
// } |
| 295 |
// |
| 296 |
// The configuration provided by users may have following cases |
| 297 |
// 1. configuration have `keys` field and have a non-nil values for this key, the output should be overridden |
| 298 |
// - for example, input is {"keys", ["c"]}, then output is Config{ Keys: ["c"]} |
| 299 |
// |
| 300 |
// 2. configuration have `keys` field and have an empty slice for this key, the output should be overridden by empty slices |
| 301 |
// - for example, input is {"keys", []}, then output is Config{ Keys: []} |
| 302 |
// |
| 303 |
// 3. configuration have `keys` field and have nil value for this key, the output should be default config |
| 304 |
// - for example, input is {"keys": nil}, then output is Config{ Keys: ["a", "b"]} |
| 305 |
// |
| 306 |
// 4. configuration have no `keys` field specified, the output should be default config |
| 307 |
// - for example, input is {}, then output is Config{ Keys: ["a", "b"]} |
| 308 |
// |
| 309 |
// This hook is also used to solve https://github.com/open-telemetry/opentelemetry-collector/issues/13117. |
| 310 |
// Since v0.127.0, we decode nil values to avoid creating empty map objects. |
| 311 |
// The nil value is not well understood when layered on top of a default map non-nil value. |
| 312 |
// The fix is to avoid the assignment and return the previous value. |
| 313 |
func zeroSliceAndMapHookFunc() mapstructure.DecodeHookFuncValue { |
| 314 |
return safeWrapDecodeHookFunc(func(from, to reflect.Value) (any, error) { |
| 315 |
if to.CanSet() && to.Kind() == reflect.Slice && from.Kind() == reflect.Slice { |
| 316 |
if !from.IsNil() { |
| 317 |
// input slice is not nil, set the output slice to a new slice of the same type. |
| 318 |
to.Set(reflect.MakeSlice(to.Type(), from.Len(), from.Cap())) |
| 319 |
} |
| 320 |
} |
| 321 |
if to.CanSet() && to.Kind() == reflect.Map && from.Kind() == reflect.Map { |
| 322 |
if from.IsNil() { |
| 323 |
return to.Interface(), nil |
| 324 |
} |
| 325 |
} |
| 326 |
|
| 327 |
return from.Interface(), nil |
| 328 |
}) |
| 329 |
} |
| 330 |
|
| 331 |
// case-sensitive version of the callback to be used in the MatchName property |
| 332 |
// of the DecoderConfig. The default for MatchEqual is to use strings.EqualFold, |
| 333 |
// which is case-insensitive. |
| 334 |
func caseSensitiveMatchName(a, b string) bool { |
| 335 |
return a == b |
| 336 |
} |
| 337 |
|
| 338 |
func castTo(exp ExpandedValue, useOriginal bool) any { |
| 339 |
// If the target field is a string, use `exp.Original` or fail if not available. |
| 340 |
if useOriginal { |
| 341 |
return exp.Original |
| 342 |
} |
| 343 |
// Otherwise, use the parsed value (previous behavior). |
| 344 |
return exp.Value |
| 345 |
} |
| 346 |
|
| 347 |
// Check if a reflect.Type is of the form T, where: |
| 348 |
// X is any type or interface |
| 349 |
// T = string | map[X]T | []T | [n]T |
| 350 |
func isStringyStructure(t reflect.Type) bool { |
| 351 |
if t.Kind() == reflect.String { |
| 352 |
return true |
| 353 |
} |
| 354 |
if t.Kind() == reflect.Map { |
| 355 |
return isStringyStructure(t.Elem()) |
| 356 |
} |
| 357 |
if t.Kind() == reflect.Slice || t.Kind() == reflect.Array { |
| 358 |
return isStringyStructure(t.Elem()) |
| 359 |
} |
| 360 |
return false |
| 361 |
} |