-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathvalues.go
More file actions
301 lines (272 loc) · 9.7 KB
/
Copy pathvalues.go
File metadata and controls
301 lines (272 loc) · 9.7 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/*
Copyright 2024 The Flux authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package chartutil
import (
"context"
"errors"
"fmt"
"strings"
"github.com/go-logr/logr"
"helm.sh/helm/v4/pkg/chart/common"
"helm.sh/helm/v4/pkg/strvals"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
kubeclient "sigs.k8s.io/controller-runtime/pkg/client"
"github.com/fluxcd/pkg/apis/meta"
)
// ErrValuesRefReason is the descriptive reason for an ErrValuesReference.
type ErrValuesRefReason error
var (
// ErrResourceNotFound signals the referenced values resource could not be
// found.
ErrResourceNotFound = errors.New("resource not found")
// ErrKeyNotFound signals the key could not be found in the referenced
// values resource.
ErrKeyNotFound = errors.New("key not found")
// ErrUnsupportedRefKind signals the values reference kind is not
// supported.
ErrUnsupportedRefKind = errors.New("unsupported values reference kind")
// ErrValuesDataRead signals the referenced resource's values data could
// not be read.
ErrValuesDataRead = errors.New("failed to read values data")
// ErrValueMerge signals a single value could not be merged into the
// values.
ErrValueMerge = errors.New("failed to merge value")
// ErrUnknown signals the reason an error occurred is unknown.
ErrUnknown = errors.New("unknown error")
)
// ErrValuesReference is returned by ChartValuesFromReferences
type ErrValuesReference struct {
// Reason for the values reference error. Nil equals ErrUnknown.
// Can be used with Is to reason about a returned error:
// err := &ErrValuesReference{Reason: ErrResourceNotFound, ...}
// errors.Is(err, ErrResourceNotFound)
Reason ErrValuesRefReason
// Kind of the values reference the error is being reported for.
Kind string
// Name of the values reference the error is being reported for.
Name types.NamespacedName
// Key of the values reference the error is being reported for.
Key string
// Optional indicates if the error is being reported for an optional values
// reference.
Optional bool
// Err contains the further error chain leading to this error, it can be
// nil.
Err error
}
// Error returns an error string constructed out of the state of
// ErrValuesReference.
func (e *ErrValuesReference) Error() string {
b := strings.Builder{}
b.WriteString("could not resolve")
if e.Optional {
b.WriteString(" optional")
}
if kind := e.Kind; kind != "" {
b.WriteString(" " + kind)
}
b.WriteString(" chart values reference")
if name := e.Name.String(); name != "" {
b.WriteString(fmt.Sprintf(" '%s'", name))
}
if key := e.Key; key != "" {
b.WriteString(fmt.Sprintf(" with key '%s'", key))
}
reason := e.Reason.Error()
if reason == "" && e.Err == nil {
reason = ErrUnknown.Error()
}
if e.Err != nil {
reason = e.Err.Error()
}
b.WriteString(": " + reason)
return b.String()
}
// Is returns if target == Reason, or target == Err.
// Can be used to Reason about a returned error:
//
// err := &ErrValuesReference{Reason: ErrResourceNotFound, ...}
// errors.Is(err, ErrResourceNotFound)
func (e *ErrValuesReference) Is(target error) bool {
reason := e.Reason
if reason == nil {
reason = ErrUnknown
}
if reason == target {
return true
}
return errors.Is(e.Err, target)
}
// Unwrap returns the wrapped Err.
func (e *ErrValuesReference) Unwrap() error {
return e.Err
}
// NewErrValuesReference returns a new ErrValuesReference constructed from the
// provided values.
func NewErrValuesReference(name types.NamespacedName, ref meta.ValuesReference, reason ErrValuesRefReason, err error) *ErrValuesReference {
return &ErrValuesReference{
Reason: reason,
Kind: ref.Kind,
Name: name,
Key: ref.GetValuesKey(),
Optional: ref.Optional,
Err: err,
}
}
const (
kindConfigMap = "ConfigMap"
kindSecret = "Secret"
)
// ChartValuesFromReferences attempts to construct new chart values by resolving
// the provided references using the client, merging them in the order given.
// If provided, the values map is merged in last overwriting values from references,
// unless a reference has a targetPath specified, in which case it will overwrite all.
// It returns the merged values, or an ErrValuesReference error.
func ChartValuesFromReferences(ctx context.Context, log logr.Logger, client kubeclient.Client, namespace string,
values map[string]interface{}, refs ...meta.ValuesReference) (common.Values, error) {
result := common.Values{}
resources := make(map[string]kubeclient.Object)
for _, ref := range refs {
namespacedName := types.NamespacedName{Namespace: namespace, Name: ref.Name}
var valuesData []byte
switch ref.Kind {
case kindConfigMap, kindSecret:
index := ref.Kind + namespacedName.String()
resource, ok := resources[index]
if !ok {
// The resource may not exist, but we want to act on a single version
// of the resource in case the values reference is marked as optional.
resources[index] = nil
switch ref.Kind {
case kindSecret:
resource = &corev1.Secret{}
case kindConfigMap:
resource = &corev1.ConfigMap{}
}
if resource != nil {
if err := client.Get(ctx, namespacedName, resource); err != nil {
if apierrors.IsNotFound(err) {
err := NewErrValuesReference(namespacedName, ref, ErrResourceNotFound, err)
if err.Optional {
log.Info(err.Error())
continue
}
return nil, err
}
return nil, err
}
resources[index] = resource
}
}
if resource == nil {
if ref.Optional {
continue
}
return nil, NewErrValuesReference(namespacedName, ref, ErrResourceNotFound, nil)
}
switch typedRes := resource.(type) {
case *corev1.Secret:
data, ok := typedRes.Data[ref.GetValuesKey()]
if !ok {
err := NewErrValuesReference(namespacedName, ref, ErrKeyNotFound, nil)
if ref.Optional {
log.Info(err.Error())
continue
}
return nil, NewErrValuesReference(namespacedName, ref, ErrKeyNotFound, nil)
}
valuesData = data
case *corev1.ConfigMap:
data, ok := typedRes.Data[ref.GetValuesKey()]
if !ok {
err := NewErrValuesReference(namespacedName, ref, ErrKeyNotFound, nil)
if ref.Optional {
log.Info(err.Error())
continue
}
return nil, err
}
valuesData = []byte(data)
default:
return nil, NewErrValuesReference(namespacedName, ref, ErrUnsupportedRefKind, nil)
}
default:
return nil, NewErrValuesReference(namespacedName, ref, ErrUnsupportedRefKind, nil)
}
if ref.TargetPath != "" {
result = MergeMaps(result, values)
// TODO(hidde): this is a bit of hack, as it mimics the way the option string is passed
// to Helm from a CLI perspective. Given the parser is however not publicly accessible
// while it contains all logic around parsing the target path, it is a fair trade-off.
merger := ReplacePathValue
if ref.Literal {
merger = ReplacePathLiteralValue
}
if err := merger(result, ref.TargetPath, string(valuesData)); err != nil {
return nil, NewErrValuesReference(namespacedName, ref, ErrValueMerge, err)
}
continue
}
values, err := common.ReadValues(valuesData)
if err != nil {
return nil, NewErrValuesReference(namespacedName, ref, ErrValuesDataRead, err)
}
result = MergeMaps(result, values)
}
return MergeMaps(result, values), nil
}
// ReplacePathValue replaces the value at the dot notation path with the given
// value using Helm's string value parser using strvals.ParseInto. Single or
// double-quoted values are merged using strvals.ParseIntoString.
func ReplacePathValue(values common.Values, path string, value string) error {
const (
singleQuote = "'"
doubleQuote = `"`
)
isSingleQuoted := strings.HasPrefix(value, singleQuote) && strings.HasSuffix(value, singleQuote)
isDoubleQuoted := strings.HasPrefix(value, doubleQuote) && strings.HasSuffix(value, doubleQuote)
if isSingleQuoted || isDoubleQuoted {
value = strings.Trim(value, singleQuote+doubleQuote)
value = path + "=" + value
return strvals.ParseIntoString(value, values)
}
value = path + "=" + value
return strvals.ParseInto(value, values)
}
// ReplacePathLiteralValue replaces the value at the dot notation path with the
// given value, treating the value as a literal string. The value is consumed
// verbatim: commas, brackets, braces, equal signs and backslashes that `--set`
// would interpret as syntax are preserved as part of the value. This is the
// only safe way to inject arbitrary file content (config files, JSON blobs,
// multi-line strings containing special characters) at a target path.
//
// Mirrors the behavior of `helm --set-literal` for the value, while keeping
// `\.` escape support in the path (which `helm --set-literal` itself does
// not). Implemented by pre-escaping strvals metacharacters in the value and
// then delegating to strvals.ParseIntoString — that combination yields a
// verbatim value AND escape-aware path parsing.
func ReplacePathLiteralValue(values common.Values, path string, value string) error {
// Order matters: backslash must be escaped first so subsequent escapes
// don't get re-escaped.
escaper := strings.NewReplacer(
`\`, `\\`,
`,`, `\,`,
`[`, `\[`,
`]`, `\]`,
`{`, `\{`,
`}`, `\}`,
)
return strvals.ParseIntoString(path+"="+escaper.Replace(value), values)
}