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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Conversation

kvaps
Copy link
Member

@kvaps kvaps commented Nov 23, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced OpenAPI schema handling for the Apps API server.
    • Introduced a method for deep copying schema structures to improve resource definition management.
  • Bug Fixes

    • Improved error handling during server configuration to ensure proper reporting of setup issues.
  • Refactor

    • Removed dynamic type registration for the v1alpha1 API version to simplify server initialization.
  • Documentation

    • Updated documentation to reflect changes in API server capabilities and configuration management.

@dosubot dosubot bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Nov 23, 2024
Copy link
Contributor

coderabbitai bot commented Nov 23, 2024

Walkthrough

The changes in this pull request involve updates to various files within the project. Notably, the values.yaml file has been modified to change the image tag for the cozystackAPI from a specific version to latest. Additionally, a new global variable RegisteredGVKs has been introduced in the register.go file to track dynamically registered types. The apiserver.go file has had the dynamic type registration for the v1alpha1 API version removed, simplifying the initialization process. Lastly, enhancements related to OpenAPI schema handling and configuration management have been made in the start.go file.

Changes

File Path Change Summary
packages/system/cozystack-api/values.yaml Updated image tag from v0.18.0 to latest, changing the associated SHA256 digest.
pkg/apis/apps/v1alpha1/register.go Added a new global variable RegisteredGVKs to store the GroupVersionKind of dynamically registered types.
pkg/apiserver/apiserver.go Removed dynamic type registration for v1alpha1, simplifying the initialization process of the AppsServer.
pkg/cmd/server/start.go Introduced DeepCopySchema function for OpenAPI schema handling, updated configuration management in AppsServer.

Possibly related PRs

  • Prepare release v0.16.1 #390: The image version for the cozystack application was updated from v0.16.0 to v0.16.1, which is related to the main PR's update of the image tag to latest.
  • Prepare release v0.17.0 #444: The image version for the cozystack application was updated from v0.16.5 to v0.17.0, which is relevant as it continues the trend of updating image versions.
  • Prepare release v0.17.1 #450: The image version for the nginx-cache component was updated, indicating ongoing changes to image tags within the project.
  • Update cozystack-installer.yaml #453: The image version for the cozystack application was updated from v0.17.0 to v0.17.1, which is a direct continuation of the image version updates seen in the main PR.
  • Prepare release v0.18.0 #462: The image version for the cozystack application was updated from v0.17.1 to v0.18.0, further extending the series of image version updates related to the main PR.

Suggested labels

bug, enhancement, documentation, size:M

Suggested reviewers

  • themoriarti

🐰 In the code where changes abound,
The latest image can now be found.
With GVKs tracked in a brand new way,
Our server's ready for a brighter day!
Deep copies made, schemas refined,
In the world of code, we're one of a kind! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (4)
pkg/apis/apps/v1alpha1/register.go (1)

77-77: Enhance GVK registration with validation and error handling

The current implementation could benefit from additional safeguards:

  1. Validate/deduplicate GVKs before appending
  2. Consider error handling for registration failures
  3. Implement bounds checking for the slice growth

Consider refactoring to include these improvements:

 func RegisterDynamicTypes(scheme *runtime.Scheme, cfg *config.ResourceConfig) error {
+    // Pre-allocate slice to avoid multiple growths
+    if len(RegisteredGVKs) == 0 {
+        RegisteredGVKs = make([]schema.GroupVersionKind, 0, len(cfg.Resources))
+    }
     for _, res := range cfg.Resources {
         kind := res.Application.Kind
         gvk := SchemeGroupVersion.WithKind(kind)
+        
+        // Check for duplicates
+        for _, existing := range RegisteredGVKs {
+            if existing == gvk {
+                log.Printf("Warning: Duplicate registration attempt for GVK: %v", gvk)
+                continue
+            }
+        }
         
         scheme.AddKnownTypeWithName(gvk, &Application{})
         scheme.AddKnownTypeWithName(gvk.GroupVersion().WithKind(kind+"List"), &ApplicationList{})
         
         log.Printf("Registered kind: %s\n", kind)
         RegisteredGVKs = append(RegisteredGVKs, gvk)
     }
     return nil
 }
pkg/cmd/server/start.go (3)

161-161: Use English for code comments to maintain consistency

The comment on line 161 is in Russian. For consistency and readability, please use English for all code comments.

Apply this diff to update the comment:

-// DeepCopySchema делает глубокую копию структуры spec.Schema
+// DeepCopySchema makes a deep copy of the spec.Schema structure

200-260: Use structured logging instead of fmt.Printf

Currently, fmt.Printf is used for logging messages in the PostProcessSpec function (lines 234 and 255). Consider using a standardized logging library like klog or the logger provided by genericapiserver to ensure consistent and configurable logging throughout the application.

Apply this diff to replace fmt.Printf with structured logging:

 import (
     "context"
+    "github.com/go-logr/logr"
     "encoding/json"
     // other imports...
 )

 func (o *AppsServerOptions) Config() (*apiserver.Config, error) {
     // existing code...
+    logger := o.GenericConfig.Logger.WithName("PostProcessSpec")

     serverConfig.OpenAPIConfig.PostProcessSpec = func(swagger *spec.Swagger) (*spec.Swagger, error) {
         // existing code...
-        fmt.Printf("PostProcessSpec: Added OpenAPI definition for %s\n", resourceName)
+        logger.Info("Added OpenAPI definition", "resource", resourceName)

         // existing code...
-        fmt.Printf("PostProcessSpec: Added OpenAPI definition for %s\n", listResourceName)
+        logger.Info("Added OpenAPI definition", "resource", listResourceName)
         return swagger, nil
     }
     // existing code...
 }

Ensure that you initialize the logger appropriately in your server configuration.


215-256: Refactor to eliminate code duplication in PostProcessSpec

The code blocks for processing resources and their list counterparts are very similar, leading to code duplication. Refactoring the repetitive code into helper functions can improve maintainability and readability.

For example, create a helper function to add definitions:

func addDefinition(defs map[string]spec.Schema, baseName string, gvk schema.GroupVersionKind, baseDef *spec.Schema, isList bool) error {
    newDef, err := DeepCopySchema(baseDef)
    if err != nil {
        kindType := ""
        if isList {
            kindType = "List"
        }
        return fmt.Errorf("failed to deepcopy schema for %s%s: %w", gvk.Kind, kindType, err)
    }

    if newDef.Extensions == nil {
        newDef.Extensions = map[string]interface{}{}
    }
    kindName := gvk.Kind
    if isList {
        kindName = fmt.Sprintf("%sList", gvk.Kind)
    }
    newDef.Extensions["x-kubernetes-group-version-kind"] = []map[string]interface{}{
        {
            "group":   gvk.Group,
            "version": gvk.Version,
            "kind":    kindName,
        },
    }
    defs[baseName] = *newDef
    fmt.Printf("PostProcessSpec: Added OpenAPI definition for %s\n", baseName)
    return nil
}

Then modify the loop to use this helper:

 for _, gvk := range v1alpha1.RegisteredGVKs {
     resourceName := fmt.Sprintf("com.github.aenix.io.cozystack.pkg.apis.apps.v1alpha1.%s", gvk.Kind)
-    // Existing code for resource...
-    // Existing code for list resource...
+    if err := addDefinition(defs, resourceName, gvk, &appDef, false); err != nil {
+        return nil, err
+    }
+
+    listResourceName := fmt.Sprintf("com.github.aenix.io.cozystack.pkg.apis.apps.v1alpha1.%sList", gvk.Kind)
+    if err := addDefinition(defs, listResourceName, gvk, &listDef, true); err != nil {
+        return nil, err
+    }
 }

This refactoring reduces duplication and makes the code easier to maintain.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b7375f7 and f7f5112.

📒 Files selected for processing (4)
  • packages/system/cozystack-api/values.yaml (1 hunks)
  • pkg/apis/apps/v1alpha1/register.go (2 hunks)
  • pkg/apiserver/apiserver.go (0 hunks)
  • pkg/cmd/server/start.go (5 hunks)
💤 Files with no reviewable changes (1)
  • pkg/apiserver/apiserver.go
✅ Files skipped from review due to trivial changes (1)
  • packages/system/cozystack-api/values.yaml
🔇 Additional comments (4)
pkg/apis/apps/v1alpha1/register.go (1)

Line range hint 31-77: Verify OpenAPI schema generation integration

Since this change is part of fixing OpenAPIv2 definitions for dynamic resources, we should verify how RegisteredGVKs is used in the OpenAPI schema generation process.

✅ Verification successful

OpenAPI schema generation integration is properly handled

The verification shows that RegisteredGVKs is correctly integrated with OpenAPI schema generation:

  • The RegisteredGVKs slice is used in start.go to dynamically add OpenAPI definitions for each registered GVK
  • The package has proper OpenAPI generation tags in doc.go (+k8s:openapi-gen=true)
  • The generated OpenAPI code in zz_generated.openapi.go includes the necessary schema definitions for the Application types
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for OpenAPI schema generation code that might use RegisteredGVKs
echo "Searching for OpenAPI schema generation code..."
rg -l "openapi|swagger" --type go

# Search for direct usage of RegisteredGVKs
echo -e "\nSearching for RegisteredGVKs usage..."
rg "RegisteredGVKs" --type go

# Search for dynamic type registration patterns
echo -e "\nSearching for dynamic type registration patterns..."
ast-grep --pattern 'func $_($_: *runtime.Scheme, $_) error {
  $$$
  AddToScheme($_)
  $$$
}'

Length of output: 807


Script:

#!/bin/bash
# Check how RegisteredGVKs is used in OpenAPI generation
echo "Checking OpenAPI usage in start.go..."
rg -A 10 "RegisteredGVKs" pkg/cmd/server/start.go

echo -e "\nChecking OpenAPI config in doc.go..."
cat pkg/apis/apps/v1alpha1/doc.go

echo -e "\nChecking generated OpenAPI code..."
head -n 50 pkg/generated/openapi/zz_generated.openapi.go

Length of output: 5720

pkg/cmd/server/start.go (3)

21-21: Import statement is appropriate

The addition of encoding/json is necessary for the DeepCopySchema function to perform JSON marshaling and unmarshaling.


41-41: Necessary import for OpenAPI schema manipulation

Importing k8s.io/kube-openapi/pkg/validation/spec is required for working with spec.Schema in OpenAPI definitions.


186-191: Dynamic type registration implemented correctly

The dynamic types are registered appropriately using v1alpha1.RegisterDynamicTypes. Error handling is correctly implemented.

Comment on lines +31 to +33
var (
RegisteredGVKs []schema.GroupVersionKind
)
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
)

Comment on lines +162 to +175
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
}
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size:L This PR changes 100-499 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant