-
Notifications
You must be signed in to change notification settings - Fork 0
/
xr.go
377 lines (323 loc) · 10.8 KB
/
xr.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
package resources
import (
"context"
"encoding/json"
"errors"
"regexp"
"strings"
"time"
"github.com/charmbracelet/log"
"github.com/kndpio/kndp/internal/engine"
"github.com/kndpio/kndp/internal/kube"
"github.com/charmbracelet/huh"
crossv1 "github.com/crossplane/crossplane/apis/apiextensions/v1"
v1 "github.com/crossplane/crossplane/apis/apiextensions/v1"
extv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
)
type XResource struct {
Resource string
unstructured.Unstructured
}
var apiFields = []string{"apiVersion", "kind"}
var metadataFields = []string{"metadata"}
func (xr *XResource) GetSchemaFormFromXRDefinition(ctx context.Context, xrd crossv1.CompositeResourceDefinition, client *dynamic.DynamicClient, logger *log.Logger) *huh.Form {
xrdInstance, err := client.Resource(schema.GroupVersionResource{
Group: xrd.GroupVersionKind().Group,
Version: xrd.GroupVersionKind().Version,
Resource: xrd.GroupVersionKind().Kind,
}).Get(ctx, xrd.Name, metav1.GetOptions{})
if err != nil {
logger.Error(err)
return nil
}
runtime.DefaultUnstructuredConverter.FromUnstructured(xrdInstance.UnstructuredContent(), &xrd)
formGroups := []*huh.Group{}
selectedVersion := v1.CompositeResourceDefinitionVersion{}
if len(xrd.Spec.Versions) == 1 {
selectedVersion = xrd.Spec.Versions[0]
} else {
selectedVersionIndex := 0
versionOptions := []huh.Option[int]{}
for index, version := range xrd.Spec.Versions {
versionOptions = append(versionOptions, huh.NewOption(version.Name, index))
}
vesionSelectForm := huh.NewForm(
huh.NewGroup(
huh.NewSelect[int]().
Title("Version").
Options(versionOptions...).
Value(&selectedVersionIndex),
),
)
vesionSelectForm.Run()
selectedVersion = xrd.Spec.Versions[selectedVersionIndex]
}
versionSchema, _ := parseSchema(selectedVersion.Schema, logger)
logger.Info("Type: \t\t" + xrd.Name)
logger.Info("Description: \t" + versionSchema.Description)
versionGroups := xr.getFormGroupsByProps(versionSchema, "")
formGroups = append(formGroups, versionGroups...)
xr.SetGroupVersionKind(schema.GroupVersionKind{
Group: xrd.Spec.Group,
Version: selectedVersion.Name,
})
xr.SetKind(xrd.Spec.Names.Kind)
xr.Resource = xrd.Spec.Names.Plural
formGroups = append(formGroups,
huh.NewGroup(
huh.NewConfirm().
Key("confirm").
Title("Would you like to create resource?"),
),
)
schemaForm := huh.NewForm(formGroups...)
return schemaForm
}
func (xr *XResource) getFormGroupsByProps(schema *extv1.JSONSchemaProps, parent string) []*huh.Group {
formGroups := []*huh.Group{}
formFields := []huh.Field{}
if xr.Object == nil {
xr.Object = make(map[string]interface{})
}
for propertyName, property := range schema.Properties {
breadCrumbs := parent + "[" + propertyName + "]"
shortDescription := strings.SplitN(property.Description, ".", 2)[0]
description := shortDescription + breadCrumbs
isRequired := isStringInArray(schema.Required, propertyName)
if (property.Type == "object" || property.Type == "array") && (!isStringInArray(metadataFields, propertyName) || len(property.Properties) > 0) {
schemaXr := XResource{}
(xr.Object)[propertyName] = &schemaXr.Object
if property.Type == "array" {
if property.Items.Schema.Type == "string" {
propertyValue := []string{}
if property.Items.Schema.Description != "" {
description = strings.SplitN(property.Items.Schema.Description, ".", 2)[0]
}
enums := []string{}
for _, optionValue := range property.Items.Schema.Enum {
timmedValue := strings.Trim(string(optionValue.Raw), "\"")
enums = append(enums, timmedValue)
}
formFields = append(formFields,
huh.NewText().
Title(description).
Lines(3).
Validate(func(s string) error {
if s != "" {
if len(enums) > 0 {
propertyValues := strings.Split(s, "\n")
for _, optionValue := range propertyValues {
if !isStringInArray(enums, optionValue) {
return errors.New("supported values: " + strings.Join(enums, ", "))
}
}
}
propertyValue = strings.Split(s, "\n")
}
return nil
}),
)
(xr.Object)[propertyName] = &propertyValue
} else if property.Items.Schema.Type == "object" {
propertyGroups := schemaXr.getFormGroupsByProps(property.Items.Schema, breadCrumbs)
formGroups = append(formGroups, propertyGroups...)
(xr.Object)[propertyName] = &[]map[string]interface{}{schemaXr.Object}
}
} else {
propertyGroups := schemaXr.getFormGroupsByProps(&property, breadCrumbs)
formGroups = append(formGroups, propertyGroups...)
(xr.Object)[propertyName] = &schemaXr.Object
}
} else if property.Type == "string" && !isStringInArray(apiFields, propertyName) {
propertyValue := ""
(xr.Object)[propertyName] = &propertyValue
if len(property.Enum) > 0 {
if property.Default != nil {
propertyValue = strings.Trim(string(property.Default.Raw), "\"")
}
options := []huh.Option[string]{}
for _, optionValue := range property.Enum {
timmedValue := strings.Trim(string(optionValue.Raw), "\"")
options = append(options, huh.NewOption(timmedValue, timmedValue))
}
formFields = append(formFields, huh.NewSelect[string]().
Options(options...).
Title(description).
Value(&propertyValue),
)
} else {
formFields = append(formFields, huh.NewInput().
Validate(func(s string) error {
if isRequired && s == "" {
return errors.New(propertyName + " is required")
} else {
return nil
}
}).
Title(description).
Value(&propertyValue),
)
}
} else if property.Type == "number" && !isStringInArray(apiFields, propertyName) {
propertyValue := json.Number("")
(xr.Object)[propertyName] = &propertyValue
formFields = append(formFields, huh.NewInput().
Validate(func(s string) error {
if s != "" && !regexp.MustCompile(`\d`).MatchString(s) {
return errors.New(propertyName + " shall be numeric")
}
if isRequired && s == "" {
return errors.New(propertyName + " is required")
}
propertyValue = json.Number(s)
return nil
}).
Title(description),
)
} else if property.Type == "boolean" && !isStringInArray(apiFields, propertyName) {
propertyValue := false
(xr.Object)[propertyName] = &propertyValue
formFields = append(formFields, huh.NewConfirm().
Title(description).
Value(&propertyValue),
)
} else if property.Type == "object" && isStringInArray(metadataFields, propertyName) {
propertyValue := metav1.ObjectMeta{
Name: "",
Labels: map[string]string{
"app.kubernetes.io/managed-by": "kndp",
"creation-date": time.Now().String(),
"update-date": time.Now().String(),
},
}
(xr.Object)[propertyName] = &propertyValue
formFields = append(formFields, huh.NewInput().
Validate(func(s string) error {
if s == "" {
return errors.New("name is required")
} else {
return nil
}
}).
Title("Name of resource").
Value(&propertyValue.Name),
)
}
}
if len(formFields) > 0 {
group := huh.NewGroup(formFields...).Description(schema.Description)
currentGroups := []*huh.Group{}
currentGroups = append(currentGroups, group)
formGroups = append(currentGroups, formGroups...)
}
return formGroups
}
func parseSchema(v *v1.CompositeResourceValidation, logger *log.Logger) (*extv1.JSONSchemaProps, error) {
if v == nil {
return nil, nil
}
s := &extv1.JSONSchemaProps{}
if err := json.Unmarshal(v.OpenAPIV3Schema.Raw, s); err != nil {
logger.Error(err)
}
return s, nil
}
func isStringInArray(a []string, s string) bool {
for _, e := range a {
if s == e {
return true
}
}
return false
}
func ApplyResources(ctx context.Context, client *dynamic.DynamicClient, logger *log.Logger, file string) error {
resources, err := transformToUnstructured(file, logger)
if err != nil {
return err
}
for _, resource := range resources {
apiAndVersion := strings.Split(resource.GetAPIVersion(), "/")
resourceId := schema.GroupVersionResource{
Group: apiAndVersion[0],
Version: apiAndVersion[1],
Resource: strings.ToLower(resource.GetKind()) + "s",
}
resource.SetLabels(engine.ManagedLabels(nil))
res, err := client.Resource(resourceId).Apply(ctx, resource.GetName(), &resource, metav1.ApplyOptions{FieldManager: "kndp"})
if err != nil {
return err
} else {
logger.Infof("Resource %s from %s successfully applied", res.GetName(), res.GetAPIVersion())
}
}
return nil
}
func CopyComposites(ctx context.Context, logger *log.Logger, sourceContext dynamic.Interface, destinationContext dynamic.Interface) error {
//Get composite resources from XRDs definition and apply them
XRDs, err := kube.GetKubeResources(kube.ResourceParams{
Dynamic: sourceContext,
Ctx: ctx,
Group: "apiextensions.crossplane.io",
Version: "v1",
Resource: "compositeresourcedefinitions",
Namespace: "",
ListOption: metav1.ListOptions{},
})
if err != nil {
return err
}
if len(XRDs) > 0 {
for _, xrd := range XRDs {
var paramsXRs v1.CompositeResourceDefinition
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(xrd.UnstructuredContent(), ¶msXRs); err != nil {
logger.Printf("Failed to convert item %s: %v\n", xrd.GetName(), err)
return nil
}
for _, version := range paramsXRs.Spec.Versions {
XRs, err := kube.GetKubeResources(kube.ResourceParams{
Dynamic: sourceContext,
Ctx: ctx,
Group: paramsXRs.Spec.Group,
Version: version.Name,
Resource: paramsXRs.Spec.Names.Plural,
Namespace: "",
ListOption: metav1.ListOptions{
LabelSelector: "app.kubernetes.io/managed-by=kndp",
},
})
if err != nil {
logger.Error(err)
return nil
}
for _, xr := range XRs {
xr.SetResourceVersion("")
xr.SetFinalizers(nil)
resourceId := schema.GroupVersionResource{
Group: paramsXRs.Spec.Group,
Version: version.Name,
Resource: paramsXRs.Spec.Names.Plural,
}
_, err = destinationContext.Resource(resourceId).Namespace("").Get(ctx, xr.GetName(), metav1.GetOptions{})
if err != nil {
_, err = destinationContext.Resource(resourceId).Namespace("").Create(ctx, &xr, metav1.CreateOptions{})
if err != nil {
logger.Warn(err)
} else {
logger.Infof("Resource created successfully %s", xr.GetName())
}
} else {
logger.Warnf("Resource %s with type %s already exists, skipping.", xr.GetName(), resourceId.GroupResource().String())
}
}
}
}
} else {
logger.Warn("Composite resources not found")
}
return nil
}