-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathrender.go
More file actions
257 lines (231 loc) · 7.28 KB
/
Copy pathrender.go
File metadata and controls
257 lines (231 loc) · 7.28 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
package main
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"sort"
"strings"
"kcl-lang.io/cli/pkg/options"
"kcl-lang.io/kcl-go/pkg/kcl"
"kcl-lang.io/kpm/pkg/client"
"kcl-lang.io/krm-kcl/pkg/edit"
"kcl-lang.io/krm-kcl/pkg/source"
"sigs.k8s.io/kustomize/kyaml/kio"
fkcl "github.com/crossplane-contrib/function-kcl/input/v1alpha1"
)
// The default render path serializes the whole KCLInput to YAML, hands it to the
// krm-kcl byte-stream pipeline, which parses it back into kyaml RNodes, and then
// re-serializes those RNodes to JSON to build the KCL top-level arguments:
//
// JSON (RawExtension) -> YAML -> parse -> RNode -> JSON -> KCL
//
// We already hold JSON, and KCL wants JSON. Everything in between is conversion,
// and for a composition whose observed state is large (a Kubernetes resource with
// a fat status subresource) it dominates the cost of a RunFunction call, along
// with the GC pressure from the allocation churn it creates.
//
// renderInline skips it: it assembles the KCL arguments straight from the bytes
// we already have and invokes the KCL runtime directly. It handles the inline
// `source` case, which is the common one for Crossplane compositions; anything
// else (oci://, git, http, a local path) falls back to the krm-kcl pipeline.
// renderInline runs the KCL program without the YAML round trip. ok is false when
// the input is not something this path handles, in which case the caller must
// fall back to the krm-kcl pipeline.
func renderInline(in *fkcl.KCLInput) (out []byte, ok bool, err error) {
if !isInlineSource(in.Spec.Source) {
return nil, false, nil
}
// Resolve dependencies the same way krm-kcl's KCLRun.Transform does.
var dependencies []string
if in.Spec.Dependencies != "" {
cli, err := client.NewKpmClient()
if err != nil {
return nil, true, err
}
if dependencies, err = edit.LoadDepListFromConfig(cli, in.Spec.Dependencies); err != nil {
return nil, true, err
}
}
args, err := kclArguments(in)
if err != nil {
return nil, true, err
}
buf := bytes.NewBuffer(nil)
if !in.Spec.Config.Vendor {
opts := []kcl.Option{
kcl.WithCode(in.Spec.Source),
kcl.WithOptions(args...),
kcl.WithExternalPkgs(dependencies...),
// Surface KCL print() output to the function pod's stdout, as the
// krm-kcl CLI path does. Without a logger the gRPC LogMessage that
// carries print() output is discarded (see issue #453).
kcl.WithLogger(os.Stdout),
}
for _, setting := range in.Spec.Config.Settings {
opts = append(opts, kcl.WithSettings(setting))
}
exec := kcl.NewOption()
exec.Overrides = in.Spec.Config.Overrides
exec.PathSelector = in.Spec.Config.PathSelectors
exec.DisableNone = in.Spec.Config.DisableNone
exec.Debug = boolToInt32(in.Spec.Config.Debug)
exec.SortKeys = in.Spec.Config.SortKeys
exec.ShowHidden = in.Spec.Config.ShowHidden
exec.StrictRangeCheck = in.Spec.Config.StrictRangeCheck
opts = append(opts, *exec)
result, err := kcl.Run("prog.k", opts...)
if err != nil {
return nil, true, err
}
buf.WriteString(result.GetRawYamlResult())
} else {
if err := renderInlineVendor(in, dependencies, args, buf); err != nil {
return nil, true, err
}
}
// KCL emits every top-level variable; krm-kcl's contract is that the resources
// live under `items`. Unwrap exactly as SimpleTransformer.Transform does. This
// operates on the output, which is small — the saving is all on the input side.
nodes, err := (&kio.ByteReader{Reader: buf, OmitReaderAnnotations: true}).Read()
if err != nil {
return nil, true, err
}
items, _, err := edit.UnwrapResources(nodes)
if err != nil {
return nil, true, err
}
res := bytes.NewBuffer(nil)
if err := (&kio.ByteWriter{Writer: res}).Write(items); err != nil {
return nil, true, err
}
return res.Bytes(), true, nil
}
func renderInlineVendor(in *fkcl.KCLInput, dependencies, args []string, buf *bytes.Buffer) error {
dir, err := os.MkdirTemp("", "kcl-sandbox")
if err != nil {
return err
}
defer os.RemoveAll(dir)
prog := filepath.Join(dir, "prog.k")
if err := os.WriteFile(prog, []byte(in.Spec.Source), 0o600); err != nil {
return err
}
opts := options.NewRunOptions()
opts.NoStyle = true
opts.Entries = []string{prog}
opts.Arguments = args
opts.Writer = buf
if len(dependencies) > 0 {
opts.ExternalPackages = dependencies
}
if c := &in.Spec.Config; c != nil {
opts.Debug = c.Debug
opts.DisableNone = c.DisableNone
opts.Overrides = c.Overrides
opts.PathSelectors = c.PathSelectors
opts.Settings = c.Settings
opts.ShowHidden = c.ShowHidden
opts.SortKeys = c.SortKeys
opts.StrictRangeCheck = c.StrictRangeCheck
opts.Vendor = c.Vendor
opts.Arguments = append(opts.Arguments, c.Arguments...)
}
if err := opts.Complete([]string{}); err != nil {
return err
}
if err := opts.Validate(); err != nil {
return err
}
if err := opts.Run(); err != nil {
return err
}
return nil
}
func boolToInt32(v bool) int32 {
if v {
return 1
}
return 0
}
// renderKey returns bytes that uniquely identify a render: source, dependencies,
// params, config and target all live in the input. It is JSON rather than YAML
// because the params are already JSON, so this is a single cheap pass.
func renderKey(in *fkcl.KCLInput) ([]byte, error) { return json.Marshal(in) }
// isInlineSource mirrors the fallthrough branch of krm-kcl's SourceToTempEntry:
// anything that is not a recognised remote or local location is inline KCL code.
func isInlineSource(src string) bool {
return !source.IsOCI(src) &&
!source.IsLocal(src) &&
!source.IsRemoteUrl(src) &&
!source.IsGit(src) &&
!source.IsVCSDomain(src)
}
// kclArguments builds the KCL top-level arguments directly from the input. The
// params are already JSON (runtime.RawExtension), so the payload is copied rather
// than re-encoded.
func kclArguments(in *fkcl.KCLInput) ([]string, error) {
// functionConfig is the KCLRun itself. RawExtension marshals as raw JSON, so
// this is a single pass over the payload.
fc, err := json.Marshal(in)
if err != nil {
return nil, err
}
params, err := paramsJSON(in)
if err != nil {
return nil, err
}
var rl bytes.Buffer
rl.WriteString(`{"apiVersion":"config.kubernetes.io/v1","kind":"ResourceList","items":[],"functionConfig":`)
rl.Write(fc)
rl.WriteByte('}')
env, err := envJSON()
if err != nil {
return nil, err
}
return []string{
"resource_list=" + rl.String(),
"items=[]",
"params=" + string(params),
"PATH=" + os.Getenv("PATH"),
"env=" + string(env),
}, nil
}
// paramsJSON assembles {"oxr":<raw>,"dxr":<raw>,...} from the raw JSON we hold.
// Keys are sorted so the result is deterministic.
func paramsJSON(in *fkcl.KCLInput) ([]byte, error) {
keys := make([]string, 0, len(in.Spec.Params))
for k := range in.Spec.Params {
keys = append(keys, k)
}
sort.Strings(keys)
var b bytes.Buffer
b.WriteByte('{')
for i, k := range keys {
if i > 0 {
b.WriteByte(',')
}
kb, err := json.Marshal(k)
if err != nil {
return nil, err
}
b.Write(kb)
b.WriteByte(':')
if raw := in.Spec.Params[k].Raw; len(raw) > 0 {
b.Write(raw)
} else {
b.WriteString("{}")
}
}
b.WriteByte('}')
return b.Bytes(), nil
}
func envJSON() ([]byte, error) {
m := make(map[string]string, len(os.Environ()))
for _, e := range os.Environ() {
if kv := strings.SplitN(e, "=", 2); len(kv) == 2 {
m[kv[0]] = kv[1]
}
}
return json.Marshal(m)
}