Skip to content

Commit 48bfdd1

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

3 files changed

Lines changed: 224 additions & 105 deletions

File tree

‎pkg/cmd/server/openapi.go‎

Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
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, err := json.Marshal(in)
26+
if err != nil {
27+
// Log error or panic since this is unexpected
28+
panic(fmt.Sprintf("failed to marshal schema: %v", err))
29+
}
30+
var out spec.Schema
31+
if err := json.Unmarshal(b, &out); err != nil {
32+
panic(fmt.Sprintf("failed to unmarshal schema: %v", err))
33+
}
34+
return &out
35+
}
36+
37+
// find the object that already owns ".spec"
38+
func findSpecContainer(s *spec.Schema) *spec.Schema {
39+
if s == nil {
40+
return nil
41+
}
42+
if len(s.Type) > 0 && s.Type.Contains("object") && s.Properties != nil {
43+
if _, ok := s.Properties["spec"]; ok {
44+
return s
45+
}
46+
}
47+
for _, branch := range [][]spec.Schema{s.AllOf, s.OneOf, s.AnyOf} {
48+
for i := range branch {
49+
if res := findSpecContainer(&branch[i]); res != nil {
50+
return res
51+
}
52+
}
53+
}
54+
return nil
55+
}
56+
57+
// apply user-supplied schema; when raw == "" turn the field into a schemaless object
58+
func patchSpec(target *spec.Schema, raw string) error {
59+
// ------------------------------------------------------------------
60+
// No schema in config → we want an “open” object that accepts
61+
// arbitrary keys (`kubectl explain …spec` will show <JSON> again).
62+
// ------------------------------------------------------------------
63+
if strings.TrimSpace(raw) == "" {
64+
if target.Properties == nil {
65+
target.Properties = map[string]spec.Schema{}
66+
}
67+
68+
prop, ok := target.Properties["spec"]
69+
if !ok { // create if it didn't exist (paranoia)
70+
prop = spec.Schema{}
71+
}
72+
prop.Type = []string{"object"}
73+
prop.AdditionalProperties = &spec.SchemaOrBool{
74+
Allows: true,
75+
Schema: &spec.Schema{},
76+
}
77+
target.Properties["spec"] = prop
78+
return nil
79+
}
80+
81+
// ------------------------------------------------------------------
82+
// Custom schema provided → parse and replace the property.
83+
// ------------------------------------------------------------------
84+
if target.Properties == nil {
85+
target.Properties = map[string]spec.Schema{}
86+
}
87+
var custom spec.Schema
88+
if err := json.Unmarshal([]byte(raw), &custom); err != nil {
89+
return err
90+
}
91+
target.Properties["spec"] = custom
92+
return nil
93+
}
94+
95+
// -----------------------------------------------------------------------------
96+
// OpenAPI **v3** post-processor
97+
// -----------------------------------------------------------------------------
98+
func buildPostProcessV3(kindSchemas map[string]string) func(*spec3.OpenAPI) (*spec3.OpenAPI, error) {
99+
100+
return func(doc *spec3.OpenAPI) (*spec3.OpenAPI, error) {
101+
if doc.Components == nil {
102+
doc.Components = &spec3.Components{}
103+
}
104+
if doc.Components.Schemas == nil {
105+
doc.Components.Schemas = map[string]*spec.Schema{}
106+
}
107+
108+
base, ok := doc.Components.Schemas[baseRef]
109+
if !ok {
110+
return doc, fmt.Errorf("base schema %q not found", baseRef)
111+
}
112+
113+
for kind, raw := range kindSchemas {
114+
ref := fmt.Sprintf("%s.%s", "com.github.cozystack.cozystack.pkg.apis.apps.v1alpha1", kind)
115+
116+
s := doc.Components.Schemas[ref]
117+
if s == nil { // first time – clone "Application"
118+
s = deepCopySchema(base)
119+
s.Extensions = map[string]interface{}{
120+
"x-kubernetes-group-version-kind": []interface{}{
121+
map[string]interface{}{
122+
"group": "apps.cozystack.io", "version": "v1alpha1", "kind": kind,
123+
},
124+
},
125+
}
126+
doc.Components.Schemas[ref] = s
127+
}
128+
129+
container := findSpecContainer(s)
130+
if container == nil { // fallback: use the root
131+
container = s
132+
}
133+
if err := patchSpec(container, raw); err != nil {
134+
return nil, fmt.Errorf("kind %s: %w", kind, err)
135+
}
136+
}
137+
138+
delete(doc.Components.Schemas, baseRef)
139+
delete(doc.Components.Schemas, baseListRef)
140+
return doc, nil
141+
}
142+
}
143+
144+
// -----------------------------------------------------------------------------
145+
// OpenAPI **v2** (swagger) post-processor
146+
// -----------------------------------------------------------------------------
147+
func buildPostProcessV2(kindSchemas map[string]string) func(*spec.Swagger) (*spec.Swagger, error) {
148+
149+
return func(sw *spec.Swagger) (*spec.Swagger, error) {
150+
defs := sw.Definitions
151+
base, ok := defs[baseRef]
152+
if !ok {
153+
return sw, fmt.Errorf("base schema %q not found", baseRef)
154+
}
155+
156+
for kind, raw := range kindSchemas {
157+
ref := fmt.Sprintf("%s.%s", "com.github.cozystack.cozystack.pkg.apis.apps.v1alpha1", kind)
158+
159+
s := deepCopySchema(&base)
160+
s.Extensions = map[string]interface{}{
161+
"x-kubernetes-group-version-kind": []interface{}{
162+
map[string]interface{}{
163+
"group": "apps.cozystack.io", "version": "v1alpha1", "kind": kind,
164+
},
165+
},
166+
}
167+
168+
if err := patchSpec(s, raw); err != nil {
169+
return nil, fmt.Errorf("kind %s: %w", kind, err)
170+
}
171+
172+
defs[ref] = *s
173+
174+
// clone the List variant
175+
listName := ref + "List"
176+
listSrc := defs[baseListRef]
177+
listCopy := deepCopySchema(&listSrc)
178+
listCopy.Extensions = map[string]interface{}{
179+
"x-kubernetes-group-version-kind": []interface{}{
180+
map[string]interface{}{
181+
"group": "apps.cozystack.io",
182+
"version": "v1alpha1",
183+
"kind": kind + "List",
184+
},
185+
},
186+
}
187+
if items := listCopy.Properties["items"]; items.Items != nil && items.Items.Schema != nil {
188+
items.Items.Schema.Ref = spec.MustCreateRef("#/definitions/" + ref)
189+
listCopy.Properties["items"] = items
190+
}
191+
defs[listName] = *listCopy
192+
}
193+
194+
delete(defs, baseRef)
195+
delete(defs, baseListRef)
196+
return sw, nil
197+
}
198+
}

‎pkg/cmd/server/start.go‎

Lines changed: 21 additions & 101 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,34 @@ 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"
200182

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")
183+
version := "0.1"
184+
if o.ResourceConfig != nil {
185+
raw, err := json.Marshal(o.ResourceConfig)
186+
if err != nil {
187+
return nil, fmt.Errorf("failed to marshal resource config: %v", err)
213188
}
189+
sum := sha256.Sum256(raw)
190+
version = "0.1-" + hex.EncodeToString(sum[:8])
191+
}
214192

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-
}
238-
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")
280-
281-
swagger.Definitions = defs
282-
return swagger, nil
193+
// capture schemas from config once for fast lookup inside the closure
194+
kindSchemas := map[string]string{}
195+
for _, r := range o.ResourceConfig.Resources {
196+
kindSchemas[r.Application.Kind] = r.Application.OpenAPISchema
283197
}
284198

199+
serverConfig.OpenAPIConfig.Info.Title = "Apps"
200+
serverConfig.OpenAPIConfig.Info.Version = version
201+
serverConfig.OpenAPIConfig.PostProcessSpec = buildPostProcessV2(kindSchemas)
202+
285203
serverConfig.OpenAPIV3Config = genericapiserver.DefaultOpenAPIV3Config(
286204
sampleopenapi.GetOpenAPIDefinitions, openapi.NewDefinitionNamer(apiserver.Scheme),
287205
)
288206
serverConfig.OpenAPIV3Config.Info.Title = "Apps"
289-
serverConfig.OpenAPIV3Config.Info.Version = "0.1"
207+
serverConfig.OpenAPIV3Config.Info.Version = version
208+
209+
serverConfig.OpenAPIV3Config.PostProcessSpec = buildPostProcessV3(kindSchemas)
290210

291211
serverConfig.FeatureGate = utilversionpkg.DefaultComponentGlobalsRegistry.FeatureGateFor(
292212
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)