Skip to content

Commit edb3e92

Browse files
committed
[cozystack-api] Implement Kubernetes-like defaulting
Signed-off-by: Andrei Kvapil <[email protected]>
1 parent 7118232 commit edb3e92

3 files changed

Lines changed: 328 additions & 31 deletions

File tree

‎pkg/registry/apps/application/rest.go‎

Lines changed: 17 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@ import (
4545
internalapiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
4646
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
4747
structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
48-
schemadefault "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting"
4948

5049
// Importing API errors package to construct appropriate error responses
5150
apierrors "k8s.io/apimachinery/pkg/api/errors"
@@ -89,12 +88,24 @@ type REST struct {
8988
// NewREST creates a new REST storage for Application with specific configuration
9089
func NewREST(dynamicClient dynamic.Interface, config *config.Resource) *REST {
9190
var specSchema *structuralschema.Structural
91+
9292
if raw := strings.TrimSpace(config.Application.OpenAPISchema); raw != "" {
93-
var js internalapiext.JSONSchemaProps
94-
if err := json.Unmarshal([]byte(raw), &js); err != nil {
95-
klog.Errorf("Failed to unmarshal OpenAPI schema: %v", err)
96-
} else if specSchema, err = structuralschema.NewStructural(&js); err != nil {
97-
klog.Errorf("Failed to create structural schema: %v", err)
93+
var v1js apiextv1.JSONSchemaProps
94+
if err := json.Unmarshal([]byte(raw), &v1js); err != nil {
95+
klog.Errorf("Failed to unmarshal v1 OpenAPI schema: %v", err)
96+
} else {
97+
scheme := runtime.NewScheme()
98+
_ = internalapiext.AddToScheme(scheme)
99+
_ = apiextv1.AddToScheme(scheme)
100+
101+
var ijs internalapiext.JSONSchemaProps
102+
if err := scheme.Convert(&v1js, &ijs, nil); err != nil {
103+
klog.Errorf("Failed to convert v1->internal JSONSchemaProps: %v", err)
104+
} else if s, err := structuralschema.NewStructural(&ijs); err != nil {
105+
klog.Errorf("Failed to create structural schema: %v", err)
106+
} else {
107+
specSchema = s
108+
}
98109
}
99110
}
100111

@@ -1205,28 +1216,3 @@ func (e errNotAcceptable) Status() metav1.Status {
12051216
Message: e.Error(),
12061217
}
12071218
}
1208-
1209-
// applySpecDefaults applies default values to the Application spec based on the schema
1210-
func (r *REST) applySpecDefaults(app *appsv1alpha1.Application) error {
1211-
if r.specSchema == nil {
1212-
return nil
1213-
}
1214-
var m map[string]any
1215-
if app.Spec != nil && len(app.Spec.Raw) > 0 {
1216-
if err := json.Unmarshal(app.Spec.Raw, &m); err != nil {
1217-
return err
1218-
}
1219-
}
1220-
if m == nil {
1221-
m = map[string]any{}
1222-
}
1223-
1224-
schemadefault.Default(m, r.specSchema)
1225-
1226-
raw, err := json.Marshal(m)
1227-
if err != nil {
1228-
return err
1229-
}
1230-
app.Spec = &apiextv1.JSON{Raw: raw}
1231-
return nil
1232-
}
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
/*
2+
Copyright 2024 The Cozystack Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package application
18+
19+
import (
20+
"encoding/json"
21+
"fmt"
22+
23+
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
24+
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
25+
structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
26+
)
27+
28+
// applySpecDefaults applies default values to the Application spec based on the schema
29+
func (r *REST) applySpecDefaults(app *appsv1alpha1.Application) error {
30+
if r.specSchema == nil {
31+
return nil
32+
}
33+
var m map[string]any
34+
if app.Spec != nil && len(app.Spec.Raw) > 0 {
35+
if err := json.Unmarshal(app.Spec.Raw, &m); err != nil {
36+
return err
37+
}
38+
}
39+
if m == nil {
40+
m = map[string]any{}
41+
}
42+
if err := defaultLikeKubernetes(&m, r.specSchema); err != nil {
43+
return err
44+
}
45+
raw, err := json.Marshal(m)
46+
if err != nil {
47+
return err
48+
}
49+
app.Spec = &apiextv1.JSON{Raw: raw}
50+
return nil
51+
}
52+
53+
func defaultLikeKubernetes(root *map[string]any, s *structuralschema.Structural) error {
54+
v := any(*root)
55+
nv, err := applyDefaults(v, s, true)
56+
if err != nil {
57+
return err
58+
}
59+
obj, ok := nv.(map[string]any)
60+
if !ok && nv != nil {
61+
return fmt.Errorf("internal error: applyDefaults returned non-map type %T for object root", nv)
62+
}
63+
if obj == nil {
64+
obj = map[string]any{}
65+
}
66+
*root = obj
67+
return nil
68+
}
69+
70+
func applyDefaults(v any, s *structuralschema.Structural, top bool) (any, error) {
71+
if s == nil {
72+
return v, nil
73+
}
74+
75+
effType := s.Generic.Type
76+
if effType == "" {
77+
switch {
78+
case len(s.Properties) > 0 || (s.AdditionalProperties != nil && s.AdditionalProperties.Structural != nil):
79+
effType = "object"
80+
case s.Items != nil:
81+
effType = "array"
82+
default:
83+
// scalar
84+
}
85+
}
86+
87+
switch effType {
88+
case "object":
89+
mv, isMap := v.(map[string]any)
90+
if !isMap || v == nil {
91+
if s.Generic.Default.Object != nil && !top {
92+
if dm, ok := s.Generic.Default.Object.(map[string]any); ok {
93+
mv = cloneMap(dm)
94+
}
95+
}
96+
if mv == nil {
97+
mv = map[string]any{}
98+
}
99+
}
100+
101+
for name, ps := range s.Properties {
102+
if _, ok := mv[name]; !ok {
103+
if ps.Generic.Default.Object != nil {
104+
mv[name] = clone(ps.Generic.Default.Object)
105+
}
106+
}
107+
if cur, ok := mv[name]; ok {
108+
cv, err := applyDefaults(cur, &ps, false)
109+
if err != nil {
110+
return nil, err
111+
}
112+
mv[name] = cv
113+
}
114+
}
115+
116+
if s.AdditionalProperties != nil && s.AdditionalProperties.Structural != nil {
117+
ap := s.AdditionalProperties.Structural
118+
for k, cur := range mv {
119+
if _, isKnown := s.Properties[k]; isKnown {
120+
continue
121+
}
122+
cv, err := applyDefaults(cur, ap, false)
123+
if err != nil {
124+
return nil, err
125+
}
126+
mv[k] = cv
127+
}
128+
}
129+
return mv, nil
130+
131+
case "array":
132+
sl, isSlice := v.([]any)
133+
if !isSlice || v == nil {
134+
if s.Generic.Default.Object != nil {
135+
if ds, ok := s.Generic.Default.Object.([]any); ok {
136+
sl = cloneSlice(ds)
137+
}
138+
}
139+
if sl == nil {
140+
sl = []any{}
141+
}
142+
}
143+
if s.Items != nil {
144+
for i := range sl {
145+
cv, err := applyDefaults(sl[i], s.Items, false)
146+
if err != nil {
147+
return nil, err
148+
}
149+
sl[i] = cv
150+
}
151+
}
152+
return sl, nil
153+
154+
default:
155+
if v == nil && s.Generic.Default.Object != nil {
156+
return clone(s.Generic.Default.Object), nil
157+
}
158+
return v, nil
159+
}
160+
}
161+
162+
func clone(x any) any {
163+
switch t := x.(type) {
164+
case map[string]any:
165+
return cloneMap(t)
166+
case []any:
167+
return cloneSlice(t)
168+
default:
169+
return t
170+
}
171+
}
172+
173+
func cloneMap(m map[string]any) map[string]any {
174+
out := make(map[string]any, len(m))
175+
for k, v := range m {
176+
out[k] = clone(v)
177+
}
178+
return out
179+
}
180+
181+
func cloneSlice(s []any) []any {
182+
out := make([]any, len(s))
183+
for i := range s {
184+
out[i] = clone(s[i])
185+
}
186+
return out
187+
}
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
package application
2+
3+
import (
4+
"testing"
5+
6+
. "github.com/onsi/ginkgo/v2"
7+
. "github.com/onsi/gomega"
8+
apischema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
9+
)
10+
11+
func TestApplication(t *testing.T) {
12+
RegisterFailHandler(Fail)
13+
RunSpecs(t, "Application defaulting Suite")
14+
}
15+
16+
var _ = Describe("defaultLikeKubernetes", func() {
17+
var rootSchema *apischema.Structural
18+
19+
BeforeEach(func() {
20+
rootSchema = buildTestSchema()
21+
})
22+
23+
It("applies value-schema defaults to existing map key without merging parent object default", func() {
24+
spec := map[string]any{
25+
"nodeGroups": map[string]any{
26+
"md0": map[string]any{
27+
"minReplicas": 3,
28+
},
29+
},
30+
}
31+
32+
err := defaultLikeKubernetes(&spec, rootSchema)
33+
Expect(err).NotTo(HaveOccurred())
34+
35+
ng := spec["nodeGroups"].(map[string]any)["md0"].(map[string]any)
36+
37+
Expect(ng).To(HaveKeyWithValue("minReplicas", BeNumerically("==", 3)))
38+
Expect(ng).To(HaveKeyWithValue("instanceType", "u1.medium"))
39+
Expect(ng["roles"]).To(ConsistOf("ingress-nginx"))
40+
41+
Expect(ng).NotTo(HaveKey("ephemeralStorage"))
42+
Expect(ng).NotTo(HaveKey("maxReplicas"))
43+
Expect(ng).NotTo(HaveKey("resources"))
44+
})
45+
46+
It("does not create new map keys from parent object default", func() {
47+
spec := map[string]any{
48+
"nodeGroups": map[string]any{},
49+
}
50+
51+
err := defaultLikeKubernetes(&spec, rootSchema)
52+
Expect(err).NotTo(HaveOccurred())
53+
54+
ng := spec["nodeGroups"].(map[string]any)
55+
Expect(ng).NotTo(HaveKey("md0"))
56+
})
57+
})
58+
59+
func buildTestSchema() *apischema.Structural {
60+
instanceType := apischema.Structural{
61+
Generic: apischema.Generic{
62+
Type: "string",
63+
Default: apischema.JSON{Object: "u1.medium"},
64+
},
65+
}
66+
roles := apischema.Structural{
67+
Generic: apischema.Generic{
68+
Type: "array",
69+
Default: apischema.JSON{Object: []any{"ingress-nginx"}},
70+
},
71+
Items: &apischema.Structural{
72+
Generic: apischema.Generic{Type: "string"},
73+
},
74+
}
75+
minReplicas := apischema.Structural{
76+
Generic: apischema.Generic{Type: "integer"},
77+
}
78+
ephemeralStorage := apischema.Structural{
79+
Generic: apischema.Generic{Type: "string"},
80+
}
81+
maxReplicas := apischema.Structural{
82+
Generic: apischema.Generic{Type: "integer"},
83+
}
84+
resources := apischema.Structural{
85+
Generic: apischema.Generic{Type: "object"},
86+
Properties: map[string]apischema.Structural{},
87+
}
88+
89+
nodeGroupsValue := &apischema.Structural{
90+
Generic: apischema.Generic{Type: "object"},
91+
Properties: map[string]apischema.Structural{
92+
"instanceType": instanceType,
93+
"roles": roles,
94+
"minReplicas": minReplicas,
95+
"ephemeralStorage": ephemeralStorage,
96+
"maxReplicas": maxReplicas,
97+
"resources": resources,
98+
},
99+
}
100+
101+
nodeGroups := apischema.Structural{
102+
Generic: apischema.Generic{
103+
Type: "object",
104+
Default: apischema.JSON{Object: map[string]any{
105+
"md0": map[string]any{
106+
"ephemeralStorage": "20Gi",
107+
"maxReplicas": 10,
108+
"minReplicas": 0,
109+
"resources": map[string]any{},
110+
},
111+
}},
112+
},
113+
AdditionalProperties: &apischema.StructuralOrBool{
114+
Structural: nodeGroupsValue,
115+
},
116+
}
117+
118+
return &apischema.Structural{
119+
Generic: apischema.Generic{Type: "object"},
120+
Properties: map[string]apischema.Structural{
121+
"nodeGroups": nodeGroups,
122+
},
123+
}
124+
}

0 commit comments

Comments
 (0)