Skip to content

Commit 21fbcd0

Browse files
committed
[cozystack-api] Refactor OpenAPI Schema
Signed-off-by: Andrei Kvapil <[email protected]>
1 parent 699d38d commit 21fbcd0

3 files changed

Lines changed: 199 additions & 106 deletions

File tree

‎pkg/cmd/server/openapi.go‎

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
package server
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"strings"
7+
8+
"k8s.io/kube-openapi/pkg/spec3"
9+
"k8s.io/kube-openapi/pkg/validation/spec"
10+
)
11+
12+
// -----------------------------------------------------------------------------
13+
// shared helpers
14+
// -----------------------------------------------------------------------------
15+
16+
const (
17+
baseRef = "com.github.cozystack.cozystack.pkg.apis.apps.v1alpha1.Application"
18+
baseListRef = baseRef + "List"
19+
)
20+
21+
func deepCopySchema(in *spec.Schema) *spec.Schema {
22+
if in == nil {
23+
return nil
24+
}
25+
b, _ := json.Marshal(in)
26+
var out spec.Schema
27+
_ = json.Unmarshal(b, &out)
28+
return &out
29+
}
30+
31+
// find the object that already owns ".spec"
32+
func findSpecContainer(s *spec.Schema) *spec.Schema {
33+
if s == nil {
34+
return nil
35+
}
36+
if len(s.Type) > 0 && s.Type.Contains("object") && s.Properties != nil {
37+
if _, ok := s.Properties["spec"]; ok {
38+
return s
39+
}
40+
}
41+
for _, branch := range [][]spec.Schema{s.AllOf, s.OneOf, s.AnyOf} {
42+
for i := range branch {
43+
if res := findSpecContainer(&branch[i]); res != nil {
44+
return res
45+
}
46+
}
47+
}
48+
return nil
49+
}
50+
51+
// apply user-supplied schema; if raw == "", keep the original $ref to JSON
52+
func patchSpec(target *spec.Schema, raw string) error {
53+
// nothing provided → leave the original property untouched
54+
if strings.TrimSpace(raw) == "" {
55+
return nil
56+
}
57+
58+
if target.Properties == nil {
59+
target.Properties = map[string]spec.Schema{}
60+
}
61+
var custom spec.Schema
62+
if err := json.Unmarshal([]byte(raw), &custom); err != nil {
63+
return err
64+
}
65+
target.Properties["spec"] = custom
66+
return nil
67+
}
68+
69+
// -----------------------------------------------------------------------------
70+
// OpenAPI **v3** post-processor
71+
// -----------------------------------------------------------------------------
72+
func buildPostProcessV3(kindSchemas map[string]string) func(*spec3.OpenAPI) (*spec3.OpenAPI, error) {
73+
74+
return func(doc *spec3.OpenAPI) (*spec3.OpenAPI, error) {
75+
if doc.Components == nil {
76+
doc.Components = &spec3.Components{}
77+
}
78+
if doc.Components.Schemas == nil {
79+
doc.Components.Schemas = map[string]*spec.Schema{}
80+
}
81+
82+
base, ok := doc.Components.Schemas[baseRef]
83+
if !ok {
84+
return doc, fmt.Errorf("base schema %q not found", baseRef)
85+
}
86+
87+
for kind, raw := range kindSchemas {
88+
ref := fmt.Sprintf("%s.%s", "com.github.cozystack.cozystack.pkg.apis.apps.v1alpha1", kind)
89+
90+
s := doc.Components.Schemas[ref]
91+
if s == nil { // first time – clone "Application"
92+
s = deepCopySchema(base)
93+
s.Extensions = map[string]interface{}{
94+
"x-kubernetes-group-version-kind": []interface{}{
95+
map[string]interface{}{
96+
"group": "apps.cozystack.io", "version": "v1alpha1", "kind": kind,
97+
},
98+
},
99+
}
100+
doc.Components.Schemas[ref] = s
101+
}
102+
103+
container := findSpecContainer(s)
104+
if container == nil { // fallback: use the root
105+
container = s
106+
}
107+
if err := patchSpec(container, raw); err != nil {
108+
return nil, fmt.Errorf("kind %s: %w", kind, err)
109+
}
110+
}
111+
112+
delete(doc.Components.Schemas, baseRef)
113+
delete(doc.Components.Schemas, baseListRef)
114+
return doc, nil
115+
}
116+
}
117+
118+
// -----------------------------------------------------------------------------
119+
// OpenAPI **v2** (swagger) post-processor
120+
//
121+
// – only minimal changes; reuses the same helpers.
122+
//
123+
// -----------------------------------------------------------------------------
124+
func buildPostProcessV2(kindSchemas map[string]string) func(*spec.Swagger) (*spec.Swagger, error) {
125+
126+
return func(sw *spec.Swagger) (*spec.Swagger, error) {
127+
defs := sw.Definitions
128+
base, ok := defs[baseRef]
129+
if !ok {
130+
return sw, fmt.Errorf("base schema %q not found", baseRef)
131+
}
132+
133+
for kind, raw := range kindSchemas {
134+
ref := fmt.Sprintf("%s.%s", "com.github.cozystack.cozystack.pkg.apis.apps.v1alpha1", kind)
135+
136+
s := deepCopySchema(&base)
137+
s.Extensions = map[string]interface{}{
138+
"x-kubernetes-group-version-kind": []interface{}{
139+
map[string]interface{}{
140+
"group": "apps.cozystack.io", "version": "v1alpha1", "kind": kind,
141+
},
142+
},
143+
}
144+
145+
if err := patchSpec(s, raw); err != nil {
146+
return nil, fmt.Errorf("kind %s: %w", kind, err)
147+
}
148+
149+
defs[ref] = *s
150+
151+
// clone the List variant
152+
listName := ref + "List"
153+
listSrc := defs[baseListRef]
154+
listCopy := deepCopySchema(&listSrc)
155+
listCopy.Extensions = map[string]interface{}{
156+
"x-kubernetes-group-version-kind": []interface{}{
157+
map[string]interface{}{
158+
"group": "apps.cozystack.io",
159+
"version": "v1alpha1",
160+
"kind": kind + "List",
161+
},
162+
},
163+
}
164+
if items := listCopy.Properties["items"]; items.Items != nil && items.Items.Schema != nil {
165+
items.Items.Schema.Ref = spec.MustCreateRef("#/definitions/" + ref)
166+
listCopy.Properties["items"] = items
167+
}
168+
defs[listName] = *listCopy
169+
}
170+
171+
delete(defs, baseRef)
172+
delete(defs, baseListRef)
173+
return sw, nil
174+
}
175+
}

‎pkg/cmd/server/start.go‎

Lines changed: 19 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ package server
1818

1919
import (
2020
"context"
21+
"crypto/sha256"
22+
"encoding/hex"
2123
"encoding/json"
2224
"fmt"
2325
"io"
@@ -38,8 +40,6 @@ import (
3840
utilversionpkg "k8s.io/apiserver/pkg/util/version"
3941
"k8s.io/component-base/featuregate"
4042
baseversion "k8s.io/component-base/version"
41-
"k8s.io/klog/v2"
42-
"k8s.io/kube-openapi/pkg/validation/spec"
4343
netutils "k8s.io/utils/net"
4444
)
4545

@@ -159,22 +159,6 @@ func (o AppsServerOptions) Validate(args []string) error {
159159
return utilerrors.NewAggregate(allErrors)
160160
}
161161

162-
// DeepCopySchema делает глубокую копию структуры spec.Schema
163-
func DeepCopySchema(schema *spec.Schema) (*spec.Schema, error) {
164-
data, err := json.Marshal(schema)
165-
if err != nil {
166-
return nil, fmt.Errorf("failed to marshal schema: %w", err)
167-
}
168-
169-
var newSchema spec.Schema
170-
err = json.Unmarshal(data, &newSchema)
171-
if err != nil {
172-
return nil, fmt.Errorf("failed to unmarshal schema: %w", err)
173-
}
174-
175-
return &newSchema, nil
176-
}
177-
178162
// Config returns the configuration for the API server based on AppsServerOptions
179163
func (o *AppsServerOptions) Config() (*apiserver.Config, error) {
180164
// TODO: set the "real" external address
@@ -195,98 +179,31 @@ func (o *AppsServerOptions) Config() (*apiserver.Config, error) {
195179
serverConfig.OpenAPIConfig = genericapiserver.DefaultOpenAPIConfig(
196180
sampleopenapi.GetOpenAPIDefinitions, openapi.NewDefinitionNamer(apiserver.Scheme),
197181
)
198-
serverConfig.OpenAPIConfig.Info.Title = "Apps"
199-
serverConfig.OpenAPIConfig.Info.Version = "0.1"
200-
201-
serverConfig.OpenAPIConfig.PostProcessSpec = func(swagger *spec.Swagger) (*spec.Swagger, error) {
202-
defs := swagger.Definitions
203-
204-
// Verify the presence of the base Application/ApplicationList definitions
205-
appDef, exists := defs["com.github.cozystack.cozystack.pkg.apis.apps.v1alpha1.Application"]
206-
if !exists {
207-
return swagger, fmt.Errorf("Application definition not found")
208-
}
209-
210-
listDef, exists := defs["com.github.cozystack.cozystack.pkg.apis.apps.v1alpha1.ApplicationList"]
211-
if !exists {
212-
return swagger, fmt.Errorf("ApplicationList definition not found")
213-
}
214-
215-
// Iterate over all registered GVKs (e.g., Bucket, Database, etc.)
216-
for _, gvk := range v1alpha1.RegisteredGVKs {
217-
// This will be something like:
218-
// "com.github.cozystack.cozystack.pkg.apis.apps.v1alpha1.Bucket"
219-
resourceName := fmt.Sprintf("com.github.cozystack.cozystack.pkg.apis.apps.v1alpha1.%s", gvk.Kind)
220-
221-
// 1. Create a copy of the base Application definition for the new resource
222-
newDef, err := DeepCopySchema(&appDef)
223-
if err != nil {
224-
return nil, fmt.Errorf("failed to deepcopy schema for %s: %w", gvk.Kind, err)
225-
}
226-
227-
// 2. Update x-kubernetes-group-version-kind to match the new resource
228-
if newDef.Extensions == nil {
229-
newDef.Extensions = map[string]interface{}{}
230-
}
231-
newDef.Extensions["x-kubernetes-group-version-kind"] = []map[string]interface{}{
232-
{
233-
"group": gvk.Group,
234-
"version": gvk.Version,
235-
"kind": gvk.Kind,
236-
},
237-
}
238182

239-
// 3. Save the new resource definition under the correct name
240-
defs[resourceName] = *newDef
241-
klog.V(6).Infof("PostProcessSpec: Added OpenAPI definition for %s\n", resourceName)
242-
243-
// 4. Now handle the corresponding List type (e.g., BucketList).
244-
// We'll start by copying the ApplicationList definition.
245-
listResourceName := fmt.Sprintf("com.github.cozystack.cozystack.pkg.apis.apps.v1alpha1.%sList", gvk.Kind)
246-
newListDef, err := DeepCopySchema(&listDef)
247-
if err != nil {
248-
return nil, fmt.Errorf("failed to deepcopy schema for %sList: %w", gvk.Kind, err)
249-
}
250-
251-
// 5. Update x-kubernetes-group-version-kind for the List definition
252-
if newListDef.Extensions == nil {
253-
newListDef.Extensions = map[string]interface{}{}
254-
}
255-
newListDef.Extensions["x-kubernetes-group-version-kind"] = []map[string]interface{}{
256-
{
257-
"group": gvk.Group,
258-
"version": gvk.Version,
259-
"kind": fmt.Sprintf("%sList", gvk.Kind),
260-
},
261-
}
262-
263-
// 6. IMPORTANT: Fix the "items" reference so it points to the new resource
264-
// rather than to "Application".
265-
if itemsProp, found := newListDef.Properties["items"]; found {
266-
if itemsProp.Items != nil && itemsProp.Items.Schema != nil {
267-
itemsProp.Items.Schema.Ref = spec.MustCreateRef("#/definitions/" + resourceName)
268-
newListDef.Properties["items"] = itemsProp
269-
}
270-
}
271-
272-
// 7. Finally, save the new List definition
273-
defs[listResourceName] = *newListDef
274-
klog.V(6).Infof("PostProcessSpec: Added OpenAPI definition for %s\n", listResourceName)
275-
}
276-
277-
// Remove the original Application/ApplicationList from the definitions
278-
delete(defs, "com.github.cozystack.cozystack.pkg.apis.apps.v1alpha1.Application")
279-
delete(defs, "com.github.cozystack.cozystack.pkg.apis.apps.v1alpha1.ApplicationList")
183+
version := "0.1"
184+
if o.ResourceConfig != nil {
185+
raw, _ := json.Marshal(o.ResourceConfig)
186+
sum := sha256.Sum256(raw)
187+
version = "0.1-" + hex.EncodeToString(sum[:8])
188+
}
280189

281-
swagger.Definitions = defs
282-
return swagger, nil
190+
// capture schemas from config once for fast lookup inside the closure
191+
kindSchemas := map[string]string{}
192+
for _, r := range o.ResourceConfig.Resources {
193+
kindSchemas[r.Application.Kind] = r.Application.OpenAPISchema
283194
}
284195

196+
serverConfig.OpenAPIConfig.Info.Title = "Apps"
197+
serverConfig.OpenAPIConfig.Info.Version = version
198+
serverConfig.OpenAPIConfig.PostProcessSpec = buildPostProcessV2(kindSchemas)
199+
285200
serverConfig.OpenAPIV3Config = genericapiserver.DefaultOpenAPIV3Config(
286201
sampleopenapi.GetOpenAPIDefinitions, openapi.NewDefinitionNamer(apiserver.Scheme),
287202
)
288203
serverConfig.OpenAPIV3Config.Info.Title = "Apps"
289-
serverConfig.OpenAPIV3Config.Info.Version = "0.1"
204+
serverConfig.OpenAPIV3Config.Info.Version = version
205+
206+
serverConfig.OpenAPIV3Config.PostProcessSpec = buildPostProcessV3(kindSchemas)
290207

291208
serverConfig.FeatureGate = utilversionpkg.DefaultComponentGlobalsRegistry.FeatureGateFor(
292209
utilversionpkg.DefaultKubeComponent,

‎pkg/config/config.go‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,11 @@ type Resource struct {
3636

3737
// ApplicationConfig contains the application settings.
3838
type ApplicationConfig struct {
39-
Kind string `yaml:"kind"`
40-
Singular string `yaml:"singular"`
41-
Plural string `yaml:"plural"`
42-
ShortNames []string `yaml:"shortNames"`
39+
Kind string `yaml:"kind"`
40+
Singular string `yaml:"singular"`
41+
Plural string `yaml:"plural"`
42+
ShortNames []string `yaml:"shortNames"`
43+
OpenAPISchema string `yaml:"openAPISchema"`
4344
}
4445

4546
// ReleaseConfig contains the release settings.

0 commit comments

Comments
 (0)