Debian Codegraph @

confmap/internal/conf.go

raw
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 "errors"
8 "fmt"
9 "reflect"
10
11 "github.com/knadh/koanf/maps"
12 "github.com/knadh/koanf/providers/confmap"
13 "github.com/knadh/koanf/v2"
14
15 encoder "go.opentelemetry.io/collector/confmap/internal/mapstructure"
16 )
17
18 const (
19 // KeyDelimiter is used as the default key delimiter in the default koanf instance.
20 KeyDelimiter = "::"
21 )
22
23 // Conf represents the raw configuration map for the OpenTelemetry Collector.
24 // The confmap.Conf can be unmarshalled into the Collector's config using the "service" package.
25 type Conf struct {
26 k *koanf.Koanf
27 // If true, upon unmarshaling do not call the Unmarshal function on the struct
28 // if it implements Unmarshaler and is the top-level struct.
29 // This avoids running into an infinite recursion where Unmarshaler.Unmarshal and
30 // Conf.Unmarshal would call each other.
31 skipTopLevelUnmarshaler bool
32 // isNil is true if this Conf was created from a nil field, as opposed to an empty map.
33 // AllKeys must return an empty slice if this is true.
34 isNil bool
35 }
36
37 // New creates a new empty confmap.Conf instance.
38 func New() *Conf {
39 return &Conf{k: koanf.New(KeyDelimiter), isNil: false}
40 }
41
42 // NewFromStringMap creates a confmap.Conf from a map[string]any.
43 func NewFromStringMap(data map[string]any) *Conf {
44 p := New()
45 if data == nil {
46 p.isNil = true
47 } else {
48 // Cannot return error because the koanf instance is empty.
49 _ = p.k.Load(confmap.Provider(data, KeyDelimiter), nil)
50 }
51 return p
52 }
53
54 // Unmarshal unmarshalls the config into a struct using the given options.
55 // Tags on the fields of the structure must be properly set.
56 func (l *Conf) Unmarshal(result any, opts ...UnmarshalOption) error {
57 set := UnmarshalOptions{}
58 for _, opt := range opts {
59 opt.apply(&set)
60 }
61 return Decode(l.toStringMapWithExpand(), result, set, l.skipTopLevelUnmarshaler)
62 }
63
64 // Marshal encodes the config and merges it into the Conf.
65 func (l *Conf) Marshal(rawVal any, opts ...MarshalOption) error {
66 set := MarshalOptions{}
67 for _, opt := range opts {
68 opt.apply(&set)
69 }
70 enc := encoder.New(EncoderConfig(rawVal, set))
71 data, err := enc.Encode(rawVal)
72 if err != nil {
73 return err
74 }
75 out, ok := data.(map[string]any)
76 if !ok {
77 return errors.New("invalid config encoding")
78 }
79 return l.Merge(NewFromStringMap(out))
80 }
81
82 // AllKeys returns all keys holding a value, regardless of where they are set.
83 // Nested keys are returned with a KeyDelimiter separator.
84 func (l *Conf) AllKeys() []string {
85 return l.k.Keys()
86 }
87
88 // Get can retrieve any value given the key to use.
89 func (l *Conf) Get(key string) any {
90 val := l.unsanitizedGet(key)
91 return sanitizeExpanded(val, false)
92 }
93
94 // IsSet checks to see if the key has been set in any of the data locations.
95 func (l *Conf) IsSet(key string) bool {
96 return l.k.Exists(key)
97 }
98
99 // Merge merges the input given configuration into the existing config.
100 // Note that the given map may be modified.
101 func (l *Conf) Merge(in *Conf) error {
102 if EnableMergeAppendOption.IsEnabled() {
103 // only use MergeAppend when EnableMergeAppendOption featuregate is enabled.
104 return l.mergeAppend(in)
105 }
106 l.isNil = l.isNil && in.isNil
107 return l.k.Merge(in.k)
108 }
109
110 // Delete a path from the Conf.
111 // If the path exists, deletes it and returns true.
112 // If the path does not exist, does nothing and returns false.
113 func (l *Conf) Delete(key string) bool {
114 wasSet := l.IsSet(key)
115 l.k.Delete(key)
116 return wasSet
117 }
118
119 // mergeAppend merges the input given configuration into the existing config.
120 // Note that the given map may be modified.
121 // Additionally, mergeAppend performs deduplication when merging lists.
122 // For example, if listA = [extension1, extension2] and listB = [extension1, extension3],
123 // the resulting list will be [extension1, extension2, extension3].
124 func (l *Conf) mergeAppend(in *Conf) error {
125 err := l.k.Load(confmap.Provider(in.ToStringMap(), ""), nil, koanf.WithMergeFunc(mergeAppend))
126 if err != nil {
127 return err
128 }
129 l.isNil = l.isNil && in.isNil
130 return nil
131 }
132
133 // Sub returns new Conf instance representing a sub-config of this instance.
134 // It returns an error is the sub-config is not a map[string]any (use Get()), and an empty Map if none exists.
135 func (l *Conf) Sub(key string) (*Conf, error) {
136 // Code inspired by the koanf "Cut" func, but returns an error instead of empty map for unsupported sub-config type.
137 data := l.unsanitizedGet(key)
138 if data == nil {
139 c := New()
140 c.isNil = true
141 return c, nil
142 }
143
144 switch v := data.(type) {
145 case map[string]any:
146 return NewFromStringMap(v), nil
147 case ExpandedValue:
148 if m, ok := v.Value.(map[string]any); ok {
149 return NewFromStringMap(m), nil
150 } else if v.Value == nil {
151 // If the value is nil, return a new empty Conf.
152 c := New()
153 c.isNil = true
154 return c, nil
155 }
156 // override data with the original value to make the error message more informative.
157 data = v.Value
158 }
159
160 return nil, fmt.Errorf("unexpected sub-config value kind for key:%s value:%v kind:%v", key, data, reflect.TypeOf(data).Kind())
161 }
162
163 func (l *Conf) toStringMapWithExpand() map[string]any {
164 if l.isNil {
165 return nil
166 }
167 m := maps.Unflatten(l.k.All(), KeyDelimiter)
168 return m
169 }
170
171 // ToStringMap creates a map[string]any from a Conf.
172 // Values with multiple representations
173 // are normalized with the YAML parsed representation.
174 //
175 // For example, for a Conf created from `foo: ${env:FOO}` and `FOO=123`
176 // ToStringMap will return `map[string]any{"foo": 123}`.
177 //
178 // For any map `m`, `NewFromStringMap(m).ToStringMap() == m`.
179 // In particular, if the Conf was created from a nil value,
180 // ToStringMap will return map[string]any(nil).
181 func (l *Conf) ToStringMap() map[string]any {
182 return sanitize(l.toStringMapWithExpand()).(map[string]any)
183 }
184
185 func (l *Conf) unsanitizedGet(key string) any {
186 return l.k.Get(key)
187 }
188
189 // sanitize recursively removes expandedValue references from the given data.
190 // It uses the expandedValue.Value field to replace the expandedValue references.
191 func sanitize(a any) any {
192 return sanitizeExpanded(a, false)
193 }
194
195 // sanitizeToStringMap recursively removes expandedValue references from the given data.
196 // It uses the expandedValue.Original field to replace the expandedValue references.
197 func sanitizeToStr(a any) any {
198 return sanitizeExpanded(a, true)
199 }
200
201 func sanitizeExpanded(a any, useOriginal bool) any {
202 switch m := a.(type) {
203 case map[string]any:
204 c := maps.Copy(m)
205 for k, v := range m {
206 c[k] = sanitizeExpanded(v, useOriginal)
207 }
208 return c
209 case []any:
210 // If the value is nil, return nil.
211 var newSlice []any
212 if m == nil {
213 return newSlice
214 }
215 newSlice = make([]any, 0, len(m))
216 for _, e := range m {
217 newSlice = append(newSlice, sanitizeExpanded(e, useOriginal))
218 }
219 return newSlice
220 case ExpandedValue:
221 if useOriginal {
222 return m.Original
223 }
224 return m.Value
225 }
226 return a
227 }
228
229 type UnsanitizedGetter struct {
230 Conf *Conf
231 }
232
233 func (ug *UnsanitizedGetter) UnsanitizedGet(key string) any {
234 return ug.Conf.unsanitizedGet(key)
235 }