This repository has been archived by the owner on Dec 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfn.go
91 lines (72 loc) · 2.46 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
package main
import (
"context"
"crypto/rand"
"fmt"
"github.com/crossplane/crossplane-runtime/pkg/errors"
"github.com/crossplane/crossplane-runtime/pkg/logging"
fnv1beta1 "github.com/crossplane/function-sdk-go/proto/v1beta1"
"github.com/crossplane/function-sdk-go/request"
"github.com/crossplane/function-sdk-go/resource"
"github.com/crossplane/function-sdk-go/response"
"github.com/crossplane/crossplane-runtime/pkg/fieldpath"
"github.com/23technologies/xp-fn-rndstr/input/v1beta1"
"k8s.io/apimachinery/pkg/runtime"
)
// Function returns whatever response you ask it to.
type Function struct {
fnv1beta1.UnimplementedFunctionRunnerServiceServer
log logging.Logger
}
// RunFunction runs the Function.
func (f *Function) RunFunction(_ context.Context, req *fnv1beta1.RunFunctionRequest) (*fnv1beta1.RunFunctionResponse, error) {
f.log.Info("Running Function", "tag", req.GetMeta().GetTag())
rsp := response.To(req, response.DefaultTTL)
in := &v1beta1.RandString{}
if err := request.GetInput(req, in); err != nil {
response.Fatal(rsp, errors.Wrapf(err, "cannot get Function input from %T", req))
return rsp, nil
}
desired, err := request.GetDesiredComposedResources(req)
if err != nil {
return nil, err
}
observed, err := request.GetObservedComposedResources(req)
if err != nil {
return nil, err
}
b := make([]byte, in.Cfg.RandStr.Length/2)
if _, err := rand.Read(b); err != nil {
panic(err)
}
randString := fmt.Sprintf("%x", b)
for _, obj := range in.Cfg.Objs {
if observed[resource.Name(obj.Name)].Resource != nil {
observedPaved, err := fieldpath.PaveObject(observed[resource.Name(obj.Name)].Resource)
if err != nil {
return nil, err
}
randString, err = observedPaved.GetString(obj.FieldPath)
if err != nil {
return nil, err
}
}
if observed[resource.Name(obj.Name)].Resource == nil && obj.Prefix != "" {
patchFieldValueToObject(obj.FieldPath, obj.Prefix+randString, desired[resource.Name(obj.Name)].Resource)
} else {
patchFieldValueToObject(obj.FieldPath, randString, desired[resource.Name(obj.Name)].Resource)
}
}
response.SetDesiredComposedResources(rsp, desired)
return rsp, nil
}
func patchFieldValueToObject(fieldPath string, value any, to runtime.Object) error {
paved, err := fieldpath.PaveObject(to)
if err != nil {
return err
}
if err := paved.SetValue(fieldPath, value); err != nil {
return err
}
return runtime.DefaultUnstructuredConverter.FromUnstructured(paved.UnstructuredContent(), to)
}