Debian Codegraph @

confmap/expand.go

raw
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 "errors"
9 "fmt"
10 "regexp"
11 "strings"
12
13 "go.opentelemetry.io/collector/confmap/internal"
14 )
15
16 // schemePattern defines the regexp pattern for scheme names.
17 // Scheme name consist of a sequence of characters beginning with a letter and followed by any
18 // combination of letters, digits, plus ("+"), period ("."), or hyphen ("-").
19 const schemePattern = `[A-Za-z][A-Za-z0-9+.-]+`
20
21 var (
22 // Need to match new line as well in the OpaqueValue, so setting the "s" flag. See https://pkg.go.dev/regexp/syntax.
23 uriRegexp = regexp.MustCompile(`(?s:^(?P<Scheme>` + schemePattern + `):(?P<OpaqueValue>.*)$)`)
24
25 errTooManyRecursiveExpansions = errors.New("too many recursive expansions")
26 )
27
28 func (mr *Resolver) expandValueRecursively(ctx context.Context, value any) (any, error) {
29 for range 1000 {
30 val, changed, err := mr.expandValue(ctx, value)
31 if err != nil {
32 return nil, err
33 }
34 if !changed {
35 return val, nil
36 }
37 value = val
38 }
39 return nil, errTooManyRecursiveExpansions
40 }
41
42 func (mr *Resolver) expandValue(ctx context.Context, value any) (any, bool, error) {
43 switch v := value.(type) {
44 case internal.ExpandedValue:
45 expanded, changed, err := mr.expandValue(ctx, v.Value)
46 if err != nil {
47 return nil, false, err
48 }
49
50 switch exp := expanded.(type) {
51 case internal.ExpandedValue, string:
52 // Return expanded values or strings verbatim.
53 return exp, changed, nil
54 }
55
56 // At this point we don't know the target field type, so we need to expand the original representation as well.
57 originalExpanded, originalChanged, err := mr.expandValue(ctx, v.Original)
58 if err != nil {
59 // The original representation is not valid, return the expanded value.
60 return expanded, changed, nil
61 }
62
63 if originalExpanded, ok := originalExpanded.(string); ok {
64 // If the original representation is a string, return the expanded value with the original representation.
65 return internal.ExpandedValue{
66 Value: expanded,
67 Original: originalExpanded,
68 }, changed || originalChanged, nil
69 }
70
71 return expanded, changed, nil
72 case string:
73 if !strings.Contains(v, "${") || !strings.Contains(v, "}") {
74 // No URIs to expand.
75 return value, false, nil
76 }
77 // Embedded or nested URIs.
78 return mr.findAndExpandURI(ctx, v)
79 case []any:
80 nslice := make([]any, 0, len(v))
81 nchanged := false
82 for _, vint := range v {
83 val, changed, err := mr.expandValue(ctx, vint)
84 if err != nil {
85 return nil, false, err
86 }
87 nslice = append(nslice, val)
88 nchanged = nchanged || changed
89 }
90 return nslice, nchanged, nil
91 case map[string]any:
92 nmap := map[string]any{}
93 nchanged := false
94 for mk, mv := range v {
95 val, changed, err := mr.expandValue(ctx, mv)
96 if err != nil {
97 return nil, false, err
98 }
99 nmap[mk] = val
100 nchanged = nchanged || changed
101 }
102 return nmap, nchanged, nil
103 }
104 return value, false, nil
105 }
106
107 // findURI attempts to find the first potentially expandable URI in input. It returns a potentially expandable
108 // URI, or an empty string if none are found.
109 // Note: findURI is only called when input contains a closing bracket.
110 // We do not support escaping nested URIs (such as ${env:$${FOO}}, since that would result in an invalid outer URI (${env:${FOO}}).
111 func (mr *Resolver) findURI(input string) string {
112 closeIndex := strings.Index(input, "}")
113 remaining := input[closeIndex+1:]
114 openIndex := strings.LastIndex(input[:closeIndex+1], "${")
115
116 // if there is any of:
117 // - a missing "${"
118 // - there is no default scheme AND no scheme is detected because no `:` is found.
119 // then check the next URI.
120 if openIndex < 0 || (mr.defaultScheme == "" && !strings.Contains(input[openIndex:closeIndex+1], ":")) {
121 // if remaining does not contain "}", there are no URIs left: stop recursion.
122 if !strings.Contains(remaining, "}") {
123 return ""
124 }
125 return mr.findURI(remaining)
126 }
127
128 index := openIndex - 1
129 currentRune := '$'
130 count := 0
131 for index >= 0 && currentRune == '$' {
132 currentRune = rune(input[index])
133 if currentRune == '$' {
134 count++
135 }
136 index--
137 }
138 // if we found an odd number of immediately $ preceding ${, then the expansion is escaped
139 if count%2 == 1 {
140 return ""
141 }
142
143 return input[openIndex : closeIndex+1]
144 }
145
146 // findAndExpandURI attempts to find and expand the first occurrence of an expandable URI in input. If an expandable URI is found it
147 // returns the input with the URI expanded, true and nil. Otherwise, it returns the unchanged input, false and the expanding error.
148 // This method expects input to start with ${ and end with }
149 func (mr *Resolver) findAndExpandURI(ctx context.Context, input string) (any, bool, error) {
150 uri := mr.findURI(input)
151 if uri == "" {
152 // No URI found, return.
153 return input, false, nil
154 }
155 if uri == input {
156 // If the value is a single URI, then the return value can be anything.
157 // This is the case `foo: ${file:some_extra_config.yml}`.
158 ret, err := mr.expandURI(ctx, input)
159 if err != nil {
160 return input, false, err
161 }
162
163 val, err := ret.AsRaw()
164 if err != nil {
165 return input, false, err
166 }
167
168 if asStr, err2 := ret.AsString(); err2 == nil {
169 return internal.ExpandedValue{
170 Value: val,
171 Original: asStr,
172 }, true, nil
173 }
174
175 return val, true, nil
176 }
177 expanded, err := mr.expandURI(ctx, uri)
178 if err != nil {
179 return input, false, err
180 }
181
182 repl, err := expanded.AsString()
183 if err != nil {
184 return input, false, fmt.Errorf("expanding %v: %w", uri, err)
185 }
186 return strings.ReplaceAll(input, uri, repl), true, err
187 }
188
189 func (mr *Resolver) expandURI(ctx context.Context, input string) (*Retrieved, error) {
190 // strip ${ and }
191 uri := input[2 : len(input)-1]
192
193 if !strings.Contains(uri, ":") {
194 uri = fmt.Sprintf("%s:%s", mr.defaultScheme, uri)
195 }
196
197 lURI, err := newLocation(uri)
198 if err != nil {
199 return nil, err
200 }
201
202 if strings.Contains(lURI.opaqueValue, "$") {
203 return nil, fmt.Errorf("the uri %q contains unsupported characters ('$')", lURI.asString())
204 }
205 ret, err := mr.retrieveValue(ctx, lURI)
206 if err != nil {
207 return nil, err
208 }
209 mr.closers = append(mr.closers, ret.Close)
210 return ret, nil
211 }
212
213 type location struct {
214 scheme string
215 opaqueValue string
216 }
217
218 func (c location) asString() string {
219 return c.scheme + ":" + c.opaqueValue
220 }
221
222 func newLocation(uri string) (location, error) {
223 submatches := uriRegexp.FindStringSubmatch(uri)
224 if len(submatches) != 3 {
225 return location{}, fmt.Errorf("invalid uri: %q", uri)
226 }
227 return location{scheme: submatches[1], opaqueValue: submatches[2]}, nil
228 }