-
Notifications
You must be signed in to change notification settings - Fork 1
/
fn.go
443 lines (383 loc) · 13.1 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
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
package main
import (
"bytes"
"context"
"fmt"
"regexp"
"text/template"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/ptr"
xpv1 "github.com/crossplane/crossplane-runtime/apis/common/v1"
"github.com/crossplane/crossplane-runtime/pkg/errors"
"github.com/crossplane/crossplane-runtime/pkg/logging"
"github.com/crossplane/crossplane-runtime/pkg/resource"
fnv1 "github.com/crossplane/function-sdk-go/proto/v1"
"github.com/crossplane/function-sdk-go/request"
sdkresource "github.com/crossplane/function-sdk-go/resource"
"github.com/crossplane/function-sdk-go/resource/composed"
"github.com/crossplane/function-sdk-go/response"
"github.com/crossplane/function-status-transformer/input/v1beta1"
)
type contextKey string
const (
// Condition types.
typeFunctionSuccess = "StatusTransformationSuccess"
// Condition reasons.
reasonAvailable = "Available"
reasonInputFailure = "InputFailure"
reasonObservedCompositeFailure = "ObservedCompositeFailure"
reasonMatchFailure = "MatchFailure"
reasonSetConditionFailure = "SetConditionFailure"
reasonObjectConversionFailure = "ObjectConversionFailure"
// Context keys.
logKey contextKey = "log"
// Reserved keys.
reservedKeyPrefix = "function-status-transformer.reserved-keys."
compositeResourceKey = reservedKeyPrefix + "composite-resource"
)
// Function returns whatever response you ask it to.
type Function struct {
fnv1.UnimplementedFunctionRunnerServiceServer
log logging.Logger
}
// RunFunction runs the Function.
func (f *Function) RunFunction(ctx context.Context, req *fnv1.RunFunctionRequest) (*fnv1.RunFunctionResponse, error) {
log := f.log.WithValues("tag", req.GetMeta().GetTag())
log.Debug("running function")
rsp := response.To(req, response.DefaultTTL)
in := &v1beta1.StatusTransformation{}
if err := request.GetInput(req, in); err != nil {
msg := fmt.Sprintf("cannot get Function input from %T", req)
log.Info(msg, "error", err)
response.ConditionFalse(rsp, typeFunctionSuccess, reasonInputFailure).
WithMessage(errors.Wrap(err, msg).Error())
return rsp, nil
}
xr, err := request.GetObservedCompositeResource(req)
if err != nil {
msg := fmt.Sprintf("cannot get observed XR from %T", req)
log.Info(msg, "error", err)
response.ConditionFalse(rsp, typeFunctionSuccess, reasonInputFailure).
WithMessage(errors.Wrap(err, msg).Error())
return rsp, nil
}
log = log.WithValues(
"xr-apiversion", xr.Resource.GetAPIVersion(),
"xr-kind", xr.Resource.GetKind(),
"xr-name", xr.Resource.GetName(),
)
log.Info("running function")
observed := map[string]*fnv1.Resource{}
if req.GetObserved() != nil && req.GetObserved().GetResources() != nil {
observed = req.GetObserved().GetResources()
}
errored := false
conditionsSet := map[string]bool{}
for shi, sh := range in.StatusConditionHooks {
log := log.WithValues("statusConditionHookIndex", shi)
// The regular expression groups found in the matches.
scGroups := map[string]string{}
allMatched := false
for mci, mc := range sh.Matchers {
log := log.WithValues("matchConditionIndex", mci)
ctx := context.WithValue(ctx, logKey, log)
matched, mcGroups, err := matchResources(ctx, mc, observed, xr)
if err != nil {
log.Info("cannot match resources", "error", err)
response.ConditionFalse(rsp, typeFunctionSuccess, reasonMatchFailure).
WithMessage(errors.Wrapf(err, "cannot match resources, statusConditionHookIndex: %d, matchConditionIndex: %d", shi, mci).Error())
matched = false
errored = true
}
if !matched {
// All matchConditions must match.
allMatched = false
break
}
allMatched = true
// All matches were successful, copy over any regex groups.
for k, v := range mcGroups {
scGroups[k] = v
}
}
if !allMatched {
// This hook did not match; do not set conditions.
continue
}
// All matchConditions matched, set the desired conditions.
for sci, cs := range sh.SetConditions {
log := log.WithValues("setConditionIndex", sci)
if conditionsSet[cs.Condition.Type] && (cs.Force == nil || !*cs.Force) {
// The condition is already set and this setter is not forceful.
log.Debug("skipping because condition is already set and setCondition is not forceful")
continue
}
log.Debug("setting condition")
c, err := transformCondition(cs, scGroups)
if err != nil {
log.Info("cannot set condition", "error", err)
response.ConditionFalse(rsp, typeFunctionSuccess, reasonSetConditionFailure).
WithMessage(errors.Wrapf(err, "cannot set condition, statusConditionHookIndex: %d, setConditionIndex: %d", shi, sci).Error())
errored = true
continue
}
rsp.Conditions = append(rsp.Conditions, c)
conditionsSet[cs.Condition.Type] = true
}
for cei, ce := range sh.CreateEvents {
log := log.WithValues("createEventIndex", cei)
r, err := transformEvent(ce, scGroups)
if err != nil {
log.Info("cannot create event")
response.ConditionFalse(rsp, typeFunctionSuccess, reasonSetConditionFailure).
WithMessage(errors.Wrapf(err, "cannot create event, statusConditionHookIndex: %d, createEventIndex: %d", shi, cei).Error())
errored = true
continue
}
rsp.Results = append(rsp.Results, r)
}
}
if !errored {
response.ConditionTrue(rsp, typeFunctionSuccess, reasonAvailable)
}
return rsp, nil
}
func matchResources(ctx context.Context, mc v1beta1.Matcher, observedMap map[string]*fnv1.Resource, xr *sdkresource.Composite) (bool, map[string]string, error) {
log := ctx.Value(logKey).(logging.Logger)
rs := map[string]conditionedObject{}
for i, r := range mc.Resources {
re, err := regexp.Compile(r.Name)
if err != nil {
log.Info("cannot compile resource key regex", "resourcesIndex", i, "error", err)
return false, nil, errors.Wrapf(err, "cannot compile resource key regex, resourcesIndex: %d", i)
}
for k, v := range observedMap {
if re.MatchString(k) {
u := &composed.Unstructured{}
if err := sdkresource.AsObject(v.GetResource(), u); err != nil {
log.Info("cannot convert resource to object", "resourcesIndex", i, "observedMapKey", k, "error", err)
return false, nil, errors.Wrapf(err, "cannot convert resource to object, resourcesIndex: %d, observedMapKey: %s", i, k)
}
rs[k] = u
}
}
}
if ptr.Deref(mc.IncludeCompositeAsResource, false) {
// The user wants to match against conditions of the composite resource.
rs[compositeResourceKey] = xr.Resource
}
if len(rs) == 0 {
// There are no resources to match against.
return false, nil, nil
}
if len(mc.Conditions) == 0 {
// There are no conditions to match against.
return false, nil, nil
}
switch ptr.Deref(mc.Type, v1beta1.AllResourcesMatchAllConditions) {
case v1beta1.AnyResourceMatchesAnyCondition:
return anyResourceMatchesAnyCondition(ctx, mc.Conditions, rs)
case v1beta1.AnyResourceMatchesAllConditions:
return anyResourceMatchesAllConditions(ctx, mc.Conditions, rs)
case v1beta1.AllResourcesMatchAnyCondition:
return allResourcesMatchAnyConditions(ctx, mc.Conditions, rs)
case v1beta1.AllResourcesMatchAllConditions:
fallthrough
default:
return allResourcesMatchAllConditions(ctx, mc.Conditions, rs)
}
}
func anyResourceMatchesAnyCondition(ctx context.Context, cms []v1beta1.ConditionMatcher, rm map[string]conditionedObject) (bool, map[string]string, error) {
log := ctx.Value(logKey).(logging.Logger)
for k, r := range rm {
for cmi, cm := range cms {
log := log.WithValues("resource", k, "conditionIndex", cmi)
ctx := context.WithValue(ctx, logKey, log)
m, cg, err := match(ctx, cm, r)
if err != nil {
log.Info("cannot match resource", "error", err)
return false, nil, err
}
if m {
return true, cg, nil
}
}
}
return false, nil, nil
}
func anyResourceMatchesAllConditions(ctx context.Context, cms []v1beta1.ConditionMatcher, rm map[string]conditionedObject) (bool, map[string]string, error) {
log := ctx.Value(logKey).(logging.Logger)
capturedGroups := map[string]string{}
for k, r := range rm {
matched := 0
for cmi, cm := range cms {
log := log.WithValues("resource", k, "conditionIndex", cmi)
ctx := context.WithValue(ctx, logKey, log)
m, cg, err := match(ctx, cm, r)
if err != nil {
log.Info("cannot match resource", "error", err)
return false, nil, err
}
if !m {
break
}
matched++
for k, v := range cg {
capturedGroups[k] = v
}
}
if matched == len(cms) {
return true, capturedGroups, nil
}
}
return false, nil, nil
}
func allResourcesMatchAnyConditions(ctx context.Context, cms []v1beta1.ConditionMatcher, rm map[string]conditionedObject) (bool, map[string]string, error) {
log := ctx.Value(logKey).(logging.Logger)
capturedGroups := map[string]string{}
for k, r := range rm {
matched := 0
for cmi, cm := range cms {
log := log.WithValues("resource", k, "conditionIndex", cmi)
ctx := context.WithValue(ctx, logKey, log)
m, cg, err := match(ctx, cm, r)
if err != nil {
log.Info("cannot match resource", "error", err)
return false, nil, err
}
if !m {
continue
}
matched++
for k, v := range cg {
capturedGroups[k] = v
}
}
if matched == 0 {
return false, nil, nil
}
}
return true, capturedGroups, nil
}
func allResourcesMatchAllConditions(ctx context.Context, cms []v1beta1.ConditionMatcher, rm map[string]conditionedObject) (bool, map[string]string, error) {
log := ctx.Value(logKey).(logging.Logger)
capturedGroups := map[string]string{}
for k, r := range rm {
for cmi, cm := range cms {
log := log.WithValues("resource", k, "conditionIndex", cmi)
ctx := context.WithValue(ctx, logKey, log)
m, cg, err := match(ctx, cm, r)
if err != nil {
log.Info("cannot match resource", "error", err)
return false, nil, err
}
if !m {
return false, nil, nil
}
for k, v := range cg {
capturedGroups[k] = v
}
}
}
return true, capturedGroups, nil
}
func match(ctx context.Context, cm v1beta1.ConditionMatcher, co conditionedObject) (bool, map[string]string, error) {
log := ctx.Value(logKey).(logging.Logger)
cmGroups := map[string]string{}
c := co.GetCondition(xpv1.ConditionType(cm.Type))
if cm.Reason != nil && *cm.Reason != string(c.Reason) {
log.Debug(fmt.Sprintf("condition reason \"%s\" did not match \"%s\"", c.Reason, *cm.Reason))
return false, nil, nil
}
if cm.Status != nil && *cm.Status != metav1.ConditionStatus(c.Status) {
log.Debug(fmt.Sprintf("condition status \"%s\" did not match \"%s\"", c.Status, *cm.Status))
return false, nil, nil
}
if cm.Message == nil {
log.Debug("condition matched")
return true, nil, nil
}
// Match the message and build up a map of template arguments.
re, err := regexp.Compile(*cm.Message)
if err != nil {
return false, nil, errors.Wrap(err, "cannot compile message regex")
}
matches := re.FindStringSubmatch(c.Message)
if len(matches) == 0 {
log.Debug(fmt.Sprintf("condition message \"%s\" did not match \"%s\"", c.Message, *cm.Message))
return false, nil, nil
}
for i := 1; i < len(matches); i++ {
cmGroups[re.SubexpNames()[i]] = matches[i]
}
log.Debug(fmt.Sprintf("condition matched - total captured groups: %v", cmGroups))
return true, cmGroups, nil
}
func transformCondition(cs v1beta1.SetCondition, templateValues map[string]string) (*fnv1.Condition, error) {
c := &fnv1.Condition{
Type: cs.Condition.Type,
Reason: cs.Condition.Reason,
Target: transformTarget(cs.Target),
}
switch cs.Condition.Status {
case metav1.ConditionTrue:
c.Status = fnv1.Status_STATUS_CONDITION_TRUE
case metav1.ConditionFalse:
c.Status = fnv1.Status_STATUS_CONDITION_FALSE
case metav1.ConditionUnknown:
fallthrough
default:
c.Status = fnv1.Status_STATUS_CONDITION_UNKNOWN
}
msg, err := templateMessage(cs.Condition.Message, templateValues)
if err != nil {
return &fnv1.Condition{}, err
}
c.Message = msg
return c, nil
}
func transformEvent(ec v1beta1.CreateEvent, templateValues map[string]string) (*fnv1.Result, error) {
e := &fnv1.Result{
Reason: ec.Event.Reason,
Target: transformTarget(ec.Target),
}
switch ptr.Deref(ec.Event.Type, v1beta1.EventTypeNormal) {
case v1beta1.EventTypeNormal:
e.Severity = fnv1.Severity_SEVERITY_NORMAL
case v1beta1.EventTypeWarning:
e.Severity = fnv1.Severity_SEVERITY_WARNING
default:
return &fnv1.Result{}, errors.Errorf("invalid type %s, must be one of [Normal, Warning]", *ec.Event.Type)
}
msg, err := templateMessage(&ec.Event.Message, templateValues)
if err != nil {
return &fnv1.Result{}, err
}
e.Message = ptr.Deref(msg, "")
return e, nil
}
func transformTarget(t *v1beta1.Target) *fnv1.Target {
target := ptr.Deref(t, v1beta1.TargetComposite)
if target == v1beta1.TargetCompositeAndClaim {
return fnv1.Target_TARGET_COMPOSITE_AND_CLAIM.Enum()
}
return fnv1.Target_TARGET_COMPOSITE.Enum()
}
func templateMessage(msg *string, values map[string]string) (*string, error) {
if msg == nil || len(values) == 0 {
return msg, nil
}
t, err := template.New("").Parse(*msg)
if err != nil {
return nil, errors.Wrap(err, "cannot parse template")
}
b := bytes.NewBuffer(nil)
if err := t.Execute(b, values); err != nil {
return nil, errors.Wrap(err, "cannot execute template")
}
return ptr.To(b.String()), nil
}
type conditionedObject interface {
resource.Object
resource.Conditioned
}