Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix OpenAPIv2 definitions for dynamic resources #484

Merged
merged 2 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/system/cozystack-api/values.yaml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
cozystackAPI:
image: ghcr.io/aenix-io/cozystack/cozystack-api:v0.18.0@sha256:d3f817ee20cc502b7c5deffa46a1ad94a6e1a74fa035dbeb65ef742e67fd1fe5
image: ghcr.io/aenix-io/cozystack/cozystack-api:latest@sha256:96d277a34aff6d9847251da521ca86615af2aae370ec095d046112bc4044ddea
11 changes: 7 additions & 4 deletions pkg/apis/apps/v1alpha1/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,20 @@ limitations under the License.
package v1alpha1

import (
"log"

"github.com/aenix.io/cozystack/pkg/config"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/klog/v2"
)

// GroupName holds the API group name.
const GroupName = "apps.cozystack.io"

var (
RegisteredGVKs []schema.GroupVersionKind
)
Comment on lines +30 to +32
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add documentation for the exported variable and consider thread-safety

The RegisteredGVKs variable is exported but lacks documentation. Since it's used to track dynamically registered types, it should be documented for API consumers. Additionally, as a global mutable slice, consider thread-safety implications if accessed concurrently.

Add documentation and consider making it thread-safe:

+// RegisteredGVKs contains the GroupVersionKinds of all dynamically registered types.
+// This slice is populated during dynamic type registration and is used for OpenAPI
+// schema generation. Note: This variable is not thread-safe.
 var (
     RegisteredGVKs []schema.GroupVersionKind
 )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var (
RegisteredGVKs []schema.GroupVersionKind
)
// RegisteredGVKs contains the GroupVersionKinds of all dynamically registered types.
// This slice is populated during dynamic type registration and is used for OpenAPI
// schema generation. Note: This variable is not thread-safe.
var (
RegisteredGVKs []schema.GroupVersionKind
)


// SchemeGroupVersion is group version used to register these objects
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"}

Expand Down Expand Up @@ -69,8 +72,8 @@ func RegisterDynamicTypes(scheme *runtime.Scheme, cfg *config.ResourceConfig) er
scheme.AddKnownTypeWithName(gvk, &Application{})
scheme.AddKnownTypeWithName(gvk.GroupVersion().WithKind(kind+"List"), &ApplicationList{})

log.Printf("Registered kind: %s\n", kind)

klog.V(1).Infof("Registered kind: %s\n", kind)
RegisteredGVKs = append(RegisteredGVKs, gvk)
}

return nil
Expand Down
7 changes: 0 additions & 7 deletions pkg/apiserver/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import (

"github.com/aenix.io/cozystack/pkg/apis/apps"
"github.com/aenix.io/cozystack/pkg/apis/apps/install"
appsv1alpha1 "github.com/aenix.io/cozystack/pkg/apis/apps/v1alpha1"
"github.com/aenix.io/cozystack/pkg/config"
appsregistry "github.com/aenix.io/cozystack/pkg/registry"
applicationstorage "github.com/aenix.io/cozystack/pkg/registry/apps/application"
Expand Down Expand Up @@ -112,12 +111,6 @@ func (c completedConfig) New() (*AppsServer, error) {

apiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(apps.GroupName, Scheme, metav1.ParameterCodec, Codecs)

// Dynamically register types based on the configuration.
err = appsv1alpha1.RegisterDynamicTypes(Scheme, c.ResourceConfig)
if err != nil {
return nil, fmt.Errorf("failed to register dynamic types: %v", err)
}

// Create a dynamic client for HelmRelease using InClusterConfig.
inClusterConfig, err := restclient.InClusterConfig()
if err != nil {
Expand Down
87 changes: 87 additions & 0 deletions pkg/cmd/server/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package server

import (
"context"
"encoding/json"
"fmt"
"io"
"net"
Expand All @@ -37,6 +38,8 @@ import (
utilversionpkg "k8s.io/apiserver/pkg/util/version"
"k8s.io/component-base/featuregate"
baseversion "k8s.io/component-base/version"
"k8s.io/klog/v2"
"k8s.io/kube-openapi/pkg/validation/spec"
netutils "k8s.io/utils/net"
)

Expand Down Expand Up @@ -156,6 +159,22 @@ func (o AppsServerOptions) Validate(args []string) error {
return utilerrors.NewAggregate(allErrors)
}

// DeepCopySchema делает глубокую копию структуры spec.Schema
func DeepCopySchema(schema *spec.Schema) (*spec.Schema, error) {
data, err := json.Marshal(schema)
if err != nil {
return nil, fmt.Errorf("failed to marshal schema: %w", err)
}

var newSchema spec.Schema
err = json.Unmarshal(data, &newSchema)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal schema: %w", err)
}

return &newSchema, nil
}
Comment on lines +163 to +176
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Avoid using json.Marshal and json.Unmarshal for deep copying

Using json.Marshal and json.Unmarshal to deep copy spec.Schema may lead to inefficient code and could potentially lose unexported fields or metadata. Consider implementing a deep copy function or using an existing library that properly handles deep copying of complex structures.

For example, if spec.Schema supports DeepCopy methods or if you can use runtime.DeepCopy, it would be more appropriate:

 func DeepCopySchema(schema *spec.Schema) (*spec.Schema, error) {
-	data, err := json.Marshal(schema)
-	if err != nil {
-		return nil, fmt.Errorf("failed to marshal schema: %w", err)
-	}
-
-	var newSchema spec.Schema
-	err = json.Unmarshal(data, &newSchema)
-	if err != nil {
-		return nil, fmt.Errorf("failed to unmarshal schema: %w", err)
-	}
-
-	return &newSchema, nil
+	// Assuming spec.Schema has a DeepCopy method
+	if schema == nil {
+		return nil, fmt.Errorf("input schema is nil")
+	}
+	newSchema := schema.DeepCopy()
+	return newSchema, nil
 }

If spec.Schema does not have a DeepCopy method, you might consider using a utility function or library that can perform a deep copy efficiently.

Committable suggestion skipped: line range outside the PR's diff.


// Config returns the configuration for the API server based on AppsServerOptions
func (o *AppsServerOptions) Config() (*apiserver.Config, error) {
// TODO: set the "real" external address
Expand All @@ -165,6 +184,12 @@ func (o *AppsServerOptions) Config() (*apiserver.Config, error) {
return nil, fmt.Errorf("error creating self-signed certificates: %v", err)
}

// First, register the dynamic types
err := v1alpha1.RegisterDynamicTypes(apiserver.Scheme, o.ResourceConfig)
if err != nil {
return nil, fmt.Errorf("failed to register dynamic types: %v", err)
}

serverConfig := genericapiserver.NewRecommendedConfig(apiserver.Codecs)

serverConfig.OpenAPIConfig = genericapiserver.DefaultOpenAPIConfig(
Expand All @@ -173,6 +198,68 @@ func (o *AppsServerOptions) Config() (*apiserver.Config, error) {
serverConfig.OpenAPIConfig.Info.Title = "Apps"
serverConfig.OpenAPIConfig.Info.Version = "0.1"

serverConfig.OpenAPIConfig.PostProcessSpec = func(swagger *spec.Swagger) (*spec.Swagger, error) {
defs := swagger.Definitions

// Check basic Application definition
appDef, exists := defs["com.github.aenix.io.cozystack.pkg.apis.apps.v1alpha1.Application"]
if !exists {
return swagger, fmt.Errorf("Application definition not found")
}

// Check basic ApplicationList definition
listDef, exists := defs["com.github.aenix.io.cozystack.pkg.apis.apps.v1alpha1.ApplicationList"]
if !exists {
return swagger, fmt.Errorf("ApplicationList definition not found")
}

for _, gvk := range v1alpha1.RegisteredGVKs {
resourceName := fmt.Sprintf("com.github.aenix.io.cozystack.pkg.apis.apps.v1alpha1.%s", gvk.Kind)
newDef, err := DeepCopySchema(&appDef)
if err != nil {
return nil, fmt.Errorf("failed to deepcopy schema for %s: %w", gvk.Kind, err)
}

// Fix Extensions for resource
if newDef.Extensions == nil {
newDef.Extensions = map[string]interface{}{}
}
newDef.Extensions["x-kubernetes-group-version-kind"] = []map[string]interface{}{
{
"group": gvk.Group,
"version": gvk.Version,
"kind": gvk.Kind,
},
}
defs[resourceName] = *newDef
klog.V(6).Infof("PostProcessSpec: Added OpenAPI definition for %s\n", resourceName)

// List resource
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unnecessary

listResourceName := fmt.Sprintf("com.github.aenix.io.cozystack.pkg.apis.apps.v1alpha1.%sList", gvk.Kind)
newListDef, err := DeepCopySchema(&listDef)
if err != nil {
return nil, fmt.Errorf("failed to deepcopy schema for %sList: %w", gvk.Kind, err)
}

// Fix Extensions for List resource
if newListDef.Extensions == nil {
newListDef.Extensions = map[string]interface{}{}
}
newListDef.Extensions["x-kubernetes-group-version-kind"] = []map[string]interface{}{
{
"group": gvk.Group,
"version": gvk.Version,
"kind": fmt.Sprintf("%sList", gvk.Kind),
},
}
defs[listResourceName] = *newListDef
klog.V(6).Infof("PostProcessSpec: Added OpenAPI definition for %s\n", listResourceName)
}

swagger.Definitions = defs
return swagger, nil
}

serverConfig.OpenAPIV3Config = genericapiserver.DefaultOpenAPIV3Config(
kvaps marked this conversation as resolved.
Show resolved Hide resolved
sampleopenapi.GetOpenAPIDefinitions, openapi.NewDefinitionNamer(apiserver.Scheme),
)
Expand Down
Loading