generated from crossplane/function-template-go
/
res.go
490 lines (452 loc) · 15.5 KB
/
res.go
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
package resource
import (
"encoding/base64"
"encoding/json"
"fmt"
"sort"
"strings"
"dario.cat/mergo"
"github.com/crossplane/crossplane-runtime/pkg/fieldpath"
"github.com/crossplane/crossplane-runtime/pkg/meta"
"github.com/crossplane/function-sdk-go/resource"
"github.com/crossplane/function-sdk-go/resource/composed"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
krmyaml "kcl-lang.io/krm-kcl/pkg/yaml"
)
type Target string
const (
// PatchDesired targets existing Resources on the Desired XR
PatchDesired Target = "PatchDesired"
// PatchResources targets existing KCLInput.spec.Resources
// These resources are then created similar to the Resources target
PatchResources Target = "PatchResources"
// Resources creates new resources that are added to the DesiredComposed Resources
Resources Target = "Resources"
// XR targets the existing Observed XR itself
XR Target = "XR"
// Default targets the existing all resources including XR, Desired XR,
// spec.Resources and DesiredComposed Resources.
Default Target = "Default"
)
const (
AnnotationKeyReady = "krm.kcl.dev/ready"
AnnotationKeyCompositionResourceName = "krm.kcl.dev/composition-resource-name"
MetaApiVersion = "meta.krm.kcl.dev/v1alpha1"
)
type ResourceList []Resource
type Resource struct {
// Name is a unique identifier for this entry in a ResourceList
Name string `json:"name"`
Base unstructured.Unstructured `json:"base,omitempty"`
}
func JsonByteToRawExtension(jsonByte []byte) (runtime.RawExtension, error) {
o, err := JsonByteToUnstructured(jsonByte)
if err != nil {
return runtime.RawExtension{}, err
}
return UnstructuredToRawExtension(o)
}
func JsonByteToUnstructured(jsonByte []byte) (*unstructured.Unstructured, error) {
var data map[string]interface{}
err := json.Unmarshal(jsonByte, &data)
if err != nil {
return nil, err
}
u := &unstructured.Unstructured{Object: data}
return u, nil
}
func UnstructuredToRawExtension(obj *unstructured.Unstructured) (runtime.RawExtension, error) {
if obj == nil {
return runtime.RawExtension{}, nil
}
raw, err := obj.MarshalJSON()
if err != nil {
return runtime.RawExtension{}, err
}
return runtime.RawExtension{Raw: raw}, nil
}
func ObjToRawExtension(obj interface{}) (runtime.RawExtension, error) {
if obj == nil {
return runtime.RawExtension{}, nil
}
raw, err := json.Marshal(obj)
if err != nil {
return runtime.RawExtension{}, err
}
return runtime.RawExtension{Raw: raw}, nil
}
func normalizeMap(input interface{}) (interface{}, error) {
switch in := input.(type) {
case map[interface{}]interface{}:
normalized := make(map[string]interface{})
for key, value := range in {
strKey, ok := key.(string)
if !ok {
return nil, fmt.Errorf("found non-string key in the map")
}
normalizedValue, err := normalizeMap(value)
if err != nil {
return nil, err
}
normalized[strKey] = normalizedValue
}
return normalized, nil
case []interface{}:
for i, v := range in {
normalizedValue, err := normalizeMap(v)
if err != nil {
return nil, err
}
in[i] = normalizedValue
}
return in, nil
default:
return input, nil
}
}
// DataResourcesFromYaml returns the manifests list from the YAML stream data.
func DataResourcesFromYaml(in []byte) (result []unstructured.Unstructured, err error) {
bytes, err := krmyaml.SplitDocuments(string(in))
if err != nil {
return
}
for _, b := range bytes {
var data interface{}
err = yaml.Unmarshal([]byte(b), &data)
if err != nil {
return
}
// Convert map[any]any to map[string]any
normalizedData, err := normalizeMap(data)
if err != nil {
return nil, err
}
result = append(result, unstructured.Unstructured{
Object: normalizedData.(map[string]interface{}),
})
}
return
}
// DesiredMatch matches a list of data to apply to a desired resource
// This is used when targeting PatchDesired resources
type DesiredMatch map[*resource.DesiredComposed][]map[string]interface{}
// MatchResources finds and associates the data to the desired resource
// The length of the passed data should match the total count of desired match data
func MatchResources(desired map[resource.Name]*resource.DesiredComposed, data []unstructured.Unstructured) (DesiredMatch, error) {
// Iterate over the data patches and match them to desired resources
matches := make(DesiredMatch)
count := 0
// Get total count of all the match patches to apply
// this count should match the initial count of the supplied data
// otherwise we lost something somewhere
for _, d := range data {
// PatchDesired
if found, ok := desired[resource.Name(d.GetName())]; ok {
if _, ok := matches[found]; !ok {
matches[found] = []map[string]interface{}{d.Object}
} else {
matches[found] = append(matches[found], d.Object)
}
count++
}
}
if count != len(data) {
return matches, fmt.Errorf("failed to match all resources, found %d / %d patches", count, len(data))
}
return matches, nil
}
type AddResourcesResult struct {
Target Target
Object any
MsgCount int
Msgs []string
}
// setSuccessMsgs generates the success messages for the input data
func (r *AddResourcesResult) setSuccessMsgs() {
r.Msgs = make([]string, r.MsgCount)
switch r.Target {
case Resources:
desired := r.Object.([]unstructured.Unstructured)
j := 0
for _, d := range desired {
r.Msgs[j] = fmt.Sprintf("created resource \"%s:%s\"", d.GetName(), d.GetKind())
j++
}
case PatchDesired:
desired := r.Object.([]unstructured.Unstructured)
j := 0
for _, d := range desired {
r.Msgs[j] = fmt.Sprintf("updated resource \"%s:%s\"", d.GetName(), d.GetKind())
j++
}
case PatchResources:
desired := r.Object.([]unstructured.Unstructured)
j := 0
for _, d := range desired {
r.Msgs[j] = fmt.Sprintf("created resource \"%s:%s\"", d.GetName(), d.GetKind())
j++
}
case XR:
o := r.Object.(*resource.Composite)
r.Msgs[0] = fmt.Sprintf("updated xr \"%s:%s\"", o.Resource.GetName(), o.Resource.GetKind())
}
sort.Strings(r.Msgs)
}
type AddResourcesOptions struct {
Basename string
Data []unstructured.Unstructured
Overwrite bool
}
// AddResourcesTo adds the given data to any allowed object passed
// Will return err if the object is not of a supported type
// For 'desired' composed resources, the Basename is used for the resource name
// For 'xr' resources, the Basename must match the xr name
// For 'existing' resources, the Basename must match the resource name
func AddResourcesTo(o any, opts *AddResourcesOptions) error {
// Merges data with the desired composed resource
// Values from data overwrite the desired composed resource
merged := func(data map[string]interface{}, from *resource.DesiredComposed) map[string]interface{} {
merged := make(map[string]interface{})
for k, v := range from.Resource.UnstructuredContent() {
merged[k] = v
}
// patch data overwrites existing desired composed data
for k, v := range data {
merged[k] = v
}
return merged
}
switch val := o.(type) {
case map[resource.Name]*resource.DesiredComposed:
// Resources
desired := val
for _, d := range opts.Data {
name := resource.Name(d.GetName())
// If the value exists, merge its existing value with the patches
if v, ok := desired[name]; ok {
mergedData := merged(d.Object, v)
d = unstructured.Unstructured{Object: mergedData}
}
desired[name] = &resource.DesiredComposed{
Resource: &composed.Unstructured{
Unstructured: d,
},
}
}
case DesiredMatch:
// PatchDesired
matches := val
// Set the Match data on the desired resource stored as keys
for obj, matchData := range matches {
// There may be multiple data patches to the DesiredComposed object
for _, d := range matchData {
if err := SetData(d, "", obj, opts.Overwrite); err != nil {
return errors.Wrap(err, "cannot set data existing desired composed object")
}
}
}
case *resource.Composite:
// XR
for _, d := range opts.Data {
if err := SetData(d.Object, "", o, opts.Overwrite); err != nil {
return errors.Wrap(err, "cannot set data on xr")
}
}
default:
return fmt.Errorf("cannot add configuration to %T: invalid type for obj", o)
}
return nil
}
var (
errNoSuchField = "no such field"
)
// SetData is a recursive function that is intended to build a kube fieldpath valid
// JSONPath(s) of the given object, it will then copy from 'data' at the given path
// to the passed o object - at the same path, overwrite defines if this function should
// be allowed to overwrite values or not, if not return an conflicting value error
//
// If the resource to write to 'o' contains a nil .Resource, setData will return an error
// It is expected that the resource is created via composed.New() or composite.New() prior
// to calling setData
func SetData(data any, path string, o any, overwrite bool) error {
switch val := data.(type) {
case map[string]interface{}:
// Check if the parent field is annotations or labels
// if so wrap the key in [] instead of . prefix
//
// Check if the suffix for validation, this is because there may be metadata annotations on deeper level items
isWrapped := false
if strings.HasSuffix(path, ".metadata.annotations") || strings.HasSuffix(path, ".metadata.labels") {
isWrapped = true
}
for key, value := range val {
var newKey string
if isWrapped {
newKey = fmt.Sprintf("%s[%s]", path, key)
} else {
newKey = fmt.Sprintf("%s.%v", path, key)
}
if err := SetData(value, newKey, o, overwrite); err != nil {
return err
}
}
case []interface{}:
for i, value := range val {
newPath := fmt.Sprintf("%s[%d]", path, i)
if err := SetData(value, newPath, o, overwrite); err != nil {
return err
}
}
default:
// Reached a leaf node, add the JSON path to the desired resource
switch val := o.(type) {
case *resource.DesiredComposed:
path = strings.TrimPrefix(path, ".")
// Currently do not allow overwriting apiVersion kind or name
// ignore setting these again because this will conflict with the overwrite settings
if path == "apiVersion" || path == "kind" || path == "metadata.name" {
return nil
}
r := val.Resource
if r == nil {
return errors.New("cannot set data on a nil DesiredComposed resource")
}
if curVal, err := r.GetValue(path); err != nil && !strings.Contains(err.Error(), errNoSuchField) {
return errors.Wrapf(err, "getting %s:%s in xr failed", path, data)
} else if curVal != nil && !overwrite {
return fmt.Errorf("%s: conflicting values %q and %q", path, curVal, data)
}
if err := r.SetValue(path, data); err != nil {
return errors.Wrapf(err, "setting %s:%s in dxr failed", path, data)
}
case *resource.Composite:
path = strings.TrimPrefix(path, ".")
// The composite does not do any matching to update so there is no need to skip here
// on apiVersion, kind or metadata.name
r := val.Resource
if r == nil {
return fmt.Errorf("cannot set data on a nil XR")
}
if curVal, err := r.GetValue(path); err != nil && !strings.Contains(err.Error(), errNoSuchField) {
return errors.Wrapf(err, "getting %s:%s in xr failed", path, data)
} else if curVal != nil && !overwrite {
return fmt.Errorf("%s: conflicting values %q and %q", path, curVal, data)
}
if err := r.SetValue(path, data); err != nil {
return errors.Wrapf(err, "setting %s:%s in dxr failed", path, data)
}
default:
return fmt.Errorf("cannot set data on %T: invalid type for obj", o)
}
}
return nil
}
func ProcessResources(dxr *resource.Composite, oxr *resource.Composite, desired map[resource.Name]*resource.DesiredComposed, observed map[resource.Name]resource.ObservedComposed, target Target, resources ResourceList, opts *AddResourcesOptions) (AddResourcesResult, error) {
result := AddResourcesResult{
Target: target,
}
data := opts.Data
switch target {
case XR:
if err := AddResourcesTo(dxr, opts); err != nil {
return result, err
}
result.Object = dxr
result.MsgCount = 1
case PatchDesired:
desiredMatches, err := MatchResources(desired, data)
if err != nil {
return result, err
}
if err := AddResourcesTo(desiredMatches, opts); err != nil {
return result, err
}
result.Object = data
result.MsgCount = len(data)
case PatchResources:
// Render the List of DesiredComposed resources from the input
// Update the existing desired map to be created as a base
for _, r := range resources {
desired[resource.Name(r.Name)] = &resource.DesiredComposed{Resource: &composed.Unstructured{Unstructured: r.Base}}
}
// Match the data to the desired resources
desiredMatches, err := MatchResources(desired, data)
if err != nil {
return result, err
}
if err := AddResourcesTo(desiredMatches, opts); err != nil {
return result, err
}
result.Object = data
result.MsgCount = len(data)
case Resources:
if err := AddResourcesTo(desired, opts); err != nil {
return result, err
}
// Pass data here instead of desired
// This is because there already may be desired objects
result.Object = data
result.MsgCount = len(data)
case Default:
for _, obj := range data {
cd := resource.NewDesiredComposed()
cd.Resource.Unstructured = obj
// Patch dxr
if cd.Resource.GetAPIVersion() == oxr.Resource.GetAPIVersion() && cd.Resource.GetKind() == oxr.Resource.GetKind() {
dst := make(map[string]any)
if err := dxr.Resource.GetValueInto("status", &dst); err != nil && !fieldpath.IsNotFound(err) {
return result, errors.Wrap(err, "cannot get desired composite status")
}
src := make(map[string]any)
if err := cd.Resource.GetValueInto("status", &src); err != nil && !fieldpath.IsNotFound(err) {
return result, errors.Wrap(err, "cannot get templated composite status")
}
if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil {
return result, errors.Wrap(err, "cannot merge desired composite status")
}
if err := fieldpath.Pave(dxr.Resource.Object).SetValue("status", dst); err != nil {
return result, errors.Wrap(err, "cannot set desired composite status")
}
continue
}
// Check the meta resource
if cd.Resource.GetAPIVersion() == MetaApiVersion {
switch obj.GetKind() {
case "CompositeConnectionDetails":
con, _ := cd.Resource.GetStringObject("data")
for k, v := range con {
d, _ := base64.StdEncoding.DecodeString(v) //nolint:errcheck // k8s returns secret values encoded
dxr.ConnectionDetails[k] = d
}
default:
return result, errors.Errorf("invalid kind %q for apiVersion %q - must be CompositeConnectionDetails", obj.GetKind(), MetaApiVersion)
}
continue
}
if v, found := cd.Resource.GetAnnotations()[AnnotationKeyReady]; found {
if v != string(resource.ReadyTrue) && v != string(resource.ReadyUnspecified) && v != string(resource.ReadyFalse) {
return result, errors.Errorf("invalid function input: invalid %q annotation value %q: must be True, False, or Unspecified", AnnotationKeyReady, v)
}
cd.Ready = resource.Ready(v)
// Remove meta annotation.
meta.RemoveAnnotations(cd.Resource, AnnotationKeyReady)
}
// Patch desired with custom name from annotation or default to resource meta name.
name, found := cd.Resource.GetAnnotations()[AnnotationKeyCompositionResourceName]
if !found {
name = cd.Resource.GetName()
}
meta.RemoveAnnotations(cd.Resource, AnnotationKeyCompositionResourceName)
desired[resource.Name(name)] = cd
}
result.Object = data
result.MsgCount = len(data)
result.setSuccessMsgs()
return result, nil
}
result.setSuccessMsgs()
return result, nil
}