generated from crossplane/function-template-go
-
Notifications
You must be signed in to change notification settings - Fork 37
/
fn.go
309 lines (255 loc) · 10.5 KB
/
fn.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
package main
import (
"bytes"
"context"
"encoding/base64"
"io"
"io/fs"
"os"
"dario.cat/mergo"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/structpb"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/json"
"k8s.io/apimachinery/pkg/util/yaml"
"github.com/crossplane/crossplane-runtime/pkg/fieldpath"
"github.com/crossplane/crossplane-runtime/pkg/meta"
"github.com/crossplane/function-sdk-go/errors"
"github.com/crossplane/function-sdk-go/logging"
fnv1 "github.com/crossplane/function-sdk-go/proto/v1"
"github.com/crossplane/function-sdk-go/request"
"github.com/crossplane/function-sdk-go/resource"
"github.com/crossplane/function-sdk-go/response"
"github.com/crossplane-contrib/function-go-templating/input/v1beta1"
)
// osFS is a dead-simple implementation of [io/fs.FS] that just wraps around
// [os.Open].
type osFS struct{}
func (*osFS) Open(name string) (fs.File, error) {
return os.Open(name)
}
// Function uses Go templates to compose resources.
type Function struct {
fnv1.UnimplementedFunctionRunnerServiceServer
log logging.Logger
fsys fs.FS
}
const (
annotationKeyCompositionResourceName = "gotemplating.fn.crossplane.io/composition-resource-name"
annotationKeyReady = "gotemplating.fn.crossplane.io/ready"
metaApiVersion = "meta.gotemplating.fn.crossplane.io/v1alpha1"
)
// RunFunction runs the Function.
func (f *Function) RunFunction(_ context.Context, req *fnv1.RunFunctionRequest) (*fnv1.RunFunctionResponse, error) {
f.log.Info("Running Function", "tag", req.GetMeta().GetTag())
rsp := response.To(req, response.DefaultTTL)
in := &v1beta1.GoTemplate{}
if err := request.GetInput(req, in); err != nil {
response.Fatal(rsp, errors.Wrapf(err, "cannot get Function input from %T", req))
return rsp, nil
}
tg, err := NewTemplateSourceGetter(f.fsys, in)
if err != nil {
response.Fatal(rsp, errors.Wrap(err, "invalid function input"))
return rsp, nil
}
f.log.Debug("template", "template", tg.GetTemplates())
tmpl, err := GetNewTemplateWithFunctionMaps(in.Delims).Parse(tg.GetTemplates())
if err != nil {
response.Fatal(rsp, errors.Wrap(err, "invalid function input: cannot parse the provided templates"))
return rsp, nil
}
reqMap, err := convertToMap(req)
if err != nil {
response.Fatal(rsp, errors.Wrap(err, "cannot convert request to map"))
return rsp, nil
}
f.log.Debug("constructed request map", "request", reqMap)
buf := &bytes.Buffer{}
if err := tmpl.Execute(buf, reqMap); err != nil {
response.Fatal(rsp, errors.Wrap(err, "cannot execute template"))
return rsp, nil
}
f.log.Debug("rendered manifests", "manifests", buf.String())
// Parse the rendered manifests.
var objs []*unstructured.Unstructured
decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewBufferString(buf.String()), 1024)
for {
u := &unstructured.Unstructured{}
if err := decoder.Decode(&u); err != nil {
if err == io.EOF {
break
}
response.Fatal(rsp, errors.Wrap(err, "cannot decode manifest"))
return rsp, nil
}
if u == nil {
continue
}
// When decoding YAML into an Unstructured object, unquoted values like booleans or integers
// can inadvertently be set as annotations, leading to unexpected behavior in later processing
// steps that assume string-only values, such as GetAnnotations.
if _, _, err := unstructured.NestedStringMap(u.Object, "metadata", "annotations"); err != nil {
m, _, _ := unstructured.NestedMap(u.Object, "metadata", "annotations")
response.Fatal(rsp, errors.Wrapf(err, "invalid annotations in resource '%s resource-name=%v'", u.GroupVersionKind(), m[annotationKeyCompositionResourceName]))
return rsp, nil
}
objs = append(objs, u)
}
// Get the desired composite resource from the request.
desiredComposite, err := request.GetDesiredCompositeResource(req)
if err != nil {
response.Fatal(rsp, errors.Wrap(err, "cannot get desired composite resource"))
return rsp, nil
}
// Get the observed composite resource from the request.
observedComposite, err := request.GetObservedCompositeResource(req)
if err != nil {
response.Fatal(rsp, errors.Wrap(err, "cannot get observed composite resource"))
return rsp, nil
}
// Get the desired composed resources from the request.
desiredComposed, err := request.GetDesiredComposedResources(req)
if err != nil {
response.Fatal(rsp, errors.Wrap(err, "cannot get desired composed resources"))
return rsp, nil
}
// Initialize the requirements.
requirements := &fnv1.Requirements{ExtraResources: make(map[string]*fnv1.ResourceSelector)}
// Convert the rendered manifests to a list of desired composed resources.
for _, obj := range objs {
cd := resource.NewDesiredComposed()
cd.Resource.Unstructured = *obj.DeepCopy()
// TODO(ezgidemirel): Refactor to reduce cyclomatic complexity.
// Handle if the composite resource appears in the rendered template.
// Unless resource name annotation is present, update only the status of the desired composite resource.
name, nameFound := obj.GetAnnotations()[annotationKeyCompositionResourceName]
if cd.Resource.GetAPIVersion() == observedComposite.Resource.GetAPIVersion() && cd.Resource.GetKind() == observedComposite.Resource.GetKind() && !nameFound {
dst := make(map[string]any)
if err := desiredComposite.Resource.GetValueInto("status", &dst); err != nil && !fieldpath.IsNotFound(err) {
response.Fatal(rsp, errors.Wrap(err, "cannot get desired composite status"))
return rsp, nil
}
src := make(map[string]any)
if err := cd.Resource.GetValueInto("status", &src); err != nil && !fieldpath.IsNotFound(err) {
response.Fatal(rsp, errors.Wrap(err, "cannot get templated composite status"))
return rsp, nil
}
if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil {
response.Fatal(rsp, errors.Wrap(err, "cannot merge desired composite status"))
return rsp, nil
}
if err := fieldpath.Pave(desiredComposite.Resource.Object).SetValue("status", dst); err != nil {
response.Fatal(rsp, errors.Wrap(err, "cannot set desired composite status"))
return rsp, nil
}
continue
}
// TODO(ezgidemirel): Refactor to reduce cyclomatic complexity.
if cd.Resource.GetAPIVersion() == metaApiVersion {
switch obj.GetKind() {
case "CompositeConnectionDetails":
// Set composite resource's connection details.
con, _ := cd.Resource.GetStringObject("data")
for k, v := range con {
d, _ := base64.StdEncoding.DecodeString(v) //nolint:errcheck // k8s returns secret values encoded
desiredComposite.ConnectionDetails[k] = d
}
case "ClaimConditions":
var conditions []TargetedCondition
if err = cd.Resource.GetValueInto("conditions", &conditions); err != nil {
response.Fatal(rsp, errors.Wrap(err, "cannot get Conditions from input"))
return rsp, nil
}
err := UpdateClaimConditions(rsp, conditions...)
if err != nil {
return rsp, nil
}
f.log.Debug("updating ClaimConditions", "conditions", rsp.Conditions)
case "Context":
contextData := make(map[string]interface{})
if err = cd.Resource.GetValueInto("data", &contextData); err != nil {
response.Fatal(rsp, errors.Wrap(err, "cannot get Contexts from input"))
return rsp, nil
}
mergedCtx, err := f.MergeContext(req, contextData)
if err != nil {
response.Fatal(rsp, errors.Wrapf(err, "cannot merge Context"))
return rsp, nil
}
for key, v := range mergedCtx {
vv, err := structpb.NewValue(v)
if err != nil {
response.Fatal(rsp, errors.Wrap(err, "cannot convert value to structpb.Value"))
return rsp, nil
}
f.log.Debug("Updating Composition environment", "key", key, "data", v)
response.SetContextKey(rsp, key, vv)
}
case "ExtraResources":
// Set extra resources requirements.
ers := make(ExtraResourcesRequirements)
if err = cd.Resource.GetValueInto("requirements", &ers); err != nil {
response.Fatal(rsp, errors.Wrap(err, "cannot get extra resources requirements"))
return rsp, nil
}
for k, v := range ers {
if _, found := requirements.ExtraResources[k]; found {
response.Fatal(rsp, errors.Errorf("duplicate extra resource key %q", k))
return rsp, nil
}
requirements.ExtraResources[k] = v.ToResourceSelector()
}
default:
response.Fatal(rsp, errors.Errorf("invalid kind %q for apiVersion %q - must be one of CompositeConnectionDetails, Context or ExtraResources", obj.GetKind(), metaApiVersion))
return rsp, nil
}
continue
}
// TODO(ezgidemirel): Refactor to reduce cyclomatic complexity.
// Set ready state.
if v, found := cd.Resource.GetAnnotations()[annotationKeyReady]; found {
if v != string(resource.ReadyTrue) && v != string(resource.ReadyUnspecified) && v != string(resource.ReadyFalse) {
response.Fatal(rsp, errors.Errorf("invalid function input: invalid %q annotation value %q: must be True, False, or Unspecified", annotationKeyReady, v))
return rsp, nil
}
cd.Ready = resource.Ready(v)
// Remove meta annotation.
meta.RemoveAnnotations(cd.Resource, annotationKeyReady)
}
// Remove resource name annotation.
meta.RemoveAnnotations(cd.Resource, annotationKeyCompositionResourceName)
// Add resource to the desired composed resources map.
if !nameFound {
response.Fatal(rsp, errors.Errorf("%q template is missing required %q annotation", obj.GetKind(), annotationKeyCompositionResourceName))
return rsp, nil
}
desiredComposed[resource.Name(name)] = cd
}
f.log.Debug("desired composite resource", "desiredComposite:", desiredComposite)
f.log.Debug("constructed desired composed resources", "desiredComposed:", desiredComposed)
if err := response.SetDesiredComposedResources(rsp, desiredComposed); err != nil {
response.Fatal(rsp, errors.Wrap(err, "cannot desired composed resources"))
return rsp, nil
}
if err := response.SetDesiredCompositeResource(rsp, desiredComposite); err != nil {
response.Fatal(rsp, errors.Wrap(err, "cannot set desired composite resource"))
return rsp, nil
}
if len(requirements.ExtraResources) > 0 {
rsp.Requirements = requirements
}
f.log.Info("Successfully composed desired resources", "source", in.Source, "count", len(objs))
return rsp, nil
}
func convertToMap(req *fnv1.RunFunctionRequest) (map[string]any, error) {
jReq, err := protojson.Marshal(req)
if err != nil {
return nil, errors.Wrap(err, "cannot marshal request from proto to json")
}
var mReq map[string]any
if err := json.Unmarshal(jReq, &mReq); err != nil {
return nil, errors.Wrap(err, "cannot unmarshal json to map[string]any")
}
return mReq, nil
}