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: update configmap if exists #566

Merged
merged 4 commits into from
Sep 25, 2024

Conversation

mojtaba-esk
Copy link
Contributor

@mojtaba-esk mojtaba-esk commented Sep 25, 2024

While attempting to upgrade app e2e tests to knuu 0.16.0-rc.0, found out that some of the upgrade tests fail due to existing configmap and the main reason is because we use static names and it is expected to update a resource if it already exists. This PR proposes a change to the configmaps if they already exist which helps the tests pass when an upgrade is happening.

Summary by CodeRabbit

  • New Features
    • Enhanced functionality for managing Kubernetes ConfigMaps with methods to create or update them seamlessly.
    • Introduced validation for ConfigMap parameters to ensure data integrity.
  • Bug Fixes
    • Improved error handling for ConfigMap updates, providing clearer error messages for failures.

@mojtaba-esk mojtaba-esk added bug Something isn't working knuu labels Sep 25, 2024
@mojtaba-esk mojtaba-esk requested a review from a team September 25, 2024 07:27
@mojtaba-esk mojtaba-esk self-assigned this Sep 25, 2024
Copy link
Contributor

coderabbitai bot commented Sep 25, 2024

Warning

Rate limit exceeded

@mojtaba-esk has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 3 minutes and 19 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between 9012c69 and 7ac94a8.

Walkthrough

The changes involve enhancements to ConfigMap management within Kubernetes. The deployFiles function in pkg/instance/storage.go has been updated to utilize CreateOrUpdateConfigMap, allowing for the creation or updating of ConfigMaps as needed. New methods for updating and creating ConfigMaps have been added to the Client struct in pkg/k8s/configmap.go, along with corresponding updates to the KubeManager interface. Additionally, an error variable for handling ConfigMap update failures has been introduced.

Changes

File Change Summary
pkg/instance/storage.go Modified deployFiles function to use CreateOrUpdateConfigMap for handling ConfigMaps, ensuring they can be created or updated as necessary.
pkg/k8s/configmap.go Introduced UpdateConfigMap and CreateOrUpdateConfigMap methods to the Client struct for managing ConfigMaps.
pkg/k8s/errors.go Added ErrUpdatingConfigmap error variable for handling ConfigMap update failures.
pkg/k8s/types.go Updated KubeManager interface to include CreateOrUpdateConfigMap and UpdateConfigMap methods for enhanced ConfigMap management.
pkg/k8s/validate.go Added validateConfigMap function for streamlined validation of ConfigMap parameters.

Poem

🐇 In the garden where ConfigMaps grow,
A rabbit hops, with a code flow.
If one exists, we’ll clear the way,
To plant anew, come what may!
With each deploy, our dreams take flight,
Hopping high, in the coding light! 🌼


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.

@celestia-bot celestia-bot requested review from smuu and sysrex September 25, 2024 07:27
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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6623172 and 4b4ed04.

📒 Files selected for processing (1)
  • pkg/instance/storage.go (2 hunks)

pkg/instance/storage.go Outdated Show resolved Hide resolved
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: 3

🧹 Outside diff range and nitpick comments (1)
pkg/k8s/types.go (1)

78-78: LGTM: New method enhances ConfigMap management

The addition of the UpdateConfigMap method is appropriate and aligns with the PR objectives. It provides a way to explicitly update an existing ConfigMap, which complements the CreateOrUpdateConfigMap method.

Consider adding a comment to clarify the behavior if the ConfigMap doesn't exist. For example:

// UpdateConfigMap updates an existing ConfigMap. If the ConfigMap doesn't exist, it returns an error.
UpdateConfigMap(ctx context.Context, name string, labels, data map[string]string) (*corev1.ConfigMap, error)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4b4ed04 and 6572017.

📒 Files selected for processing (4)
  • pkg/instance/storage.go (1 hunks)
  • pkg/k8s/configmap.go (1 hunks)
  • pkg/k8s/errors.go (1 hunks)
  • pkg/k8s/types.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/instance/storage.go
🔇 Additional comments not posted (4)
pkg/k8s/types.go (2)

23-23: LGTM: New method aligns with PR objectives

The addition of CreateOrUpdateConfigMap method is appropriate and aligns well with the PR objectives. It provides a flexible way to manage ConfigMaps, allowing for creation or update as needed. This should help resolve the issues with upgrade tests failing due to existing configmaps.


23-23: Verify interface implementations

The additions to the KubeManager interface enhance ConfigMap management capabilities and align well with the PR objectives. These changes provide the necessary flexibility to handle existing ConfigMaps during upgrades.

To ensure consistency across the codebase, please verify that all implementations of the KubeManager interface are updated to include these new methods. Run the following script to identify potential places that need updates:

This script will help identify areas of the codebase that may need to be updated to implement the new methods.

Also applies to: 78-78

✅ Verification successful

All KubeManager implementations are up-to-date

The KubeManager interface only has implementations in pkg/k8s/configmap.go, and both CreateOrUpdateConfigMap and UpdateConfigMap methods are properly implemented there. No additional implementations require updates.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find potential implementations of KubeManager interface

# Search for struct types that might implement KubeManager
echo "Potential KubeManager implementations:"
rg --type go "type \w+ struct" -A 10 | rg "KubeManager"

# Search for KubeManager method implementations
echo "\nPotential KubeManager method implementations:"
rg --type go "func \(\w+ \*\w+\) (CreateOrUpdateConfigMap|UpdateConfigMap)"

Length of output: 856


Script:

#!/bin/bash
# Description: Verify all KubeManager implementations have the required methods

# Find all structs that implement KubeManager
IMPLEMENTATIONS=$(rg --type go "type\s+\w+\s+struct" -g '*.go' | rg "KubeManager" | awk -F':' '{print $1}')

echo "Checking implementations in the following files:"
echo "$IMPLEMENTATIONS"

for file in $IMPLEMENTATIONS; do
    echo "\n$file:"
    # Check for CreateOrUpdateConfigMap method
    rg -q "func\s+\(\w+\s+\*\w+\)\s+CreateOrUpdateConfigMap" "$file" && echo "  - CreateOrUpdateConfigMap: ✅" || echo "  - CreateOrUpdateConfigMap: ❌ Missing"

    # Check for UpdateConfigMap method
    rg -q "func\s+\(\w+\s+\*\w+\)\s+UpdateConfigMap" "$file" && echo "  - UpdateConfigMap: ✅" || echo "  - UpdateConfigMap: ❌ Missing"
done

Length of output: 226


Script:

#!/bin/bash
# Description: Comprehensive search for all implementations and usages of KubeManager interface

echo "Searching for all usages of KubeManager interface:"

# Search for struct embeddings of KubeManager
echo "\nStructs embedding KubeManager:"
rg --type go "type\s+\w+\s+struct" -A 10 | rg "KubeManager"

# Search for interface implementations using ast-grep
echo "\nSearching for implementations using ast-grep:"
ast-grep --lang go --pattern '
    type $_Interface interface {
        CreateOrUpdateConfigMap($_, $_)
        UpdateConfigMap($_)
    }
' 

# Search for variable declarations of type KubeManager
echo "\nVariable declarations of type KubeManager:"
rg --type go "\bKubeManager\b.*="

Length of output: 1616

pkg/k8s/errors.go (1)

139-139: LGTM: New error variable added for configmap update failures.

The addition of ErrUpdatingConfigmap is appropriate and aligns with the PR objective to address issues with updating existing configmaps. The error message is clear and consistent with the formatting of other errors in this file.

To ensure this new error is being used correctly, let's check for its usage in the codebase:

✅ Verification successful

Verified: New error variable is correctly used in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of the new error variable
rg --type go "ErrUpdatingConfigmap"

Length of output: 239

pkg/k8s/configmap.go (1)

67-92: Ensure termination check is consistent across methods

In UpdateConfigMap, the termination check is performed after entering the function, which is consistent with other methods. However, in the refactored CreateOrUpdateConfigMap, the termination check was added as part of the refactoring.

[consistency]

Verify that all methods in the Client struct perform the termination check, and ensure they are placed consistently at the beginning of each method for clarity.

pkg/k8s/configmap.go Outdated Show resolved Hide resolved
pkg/k8s/configmap.go Outdated Show resolved Hide resolved
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: 3

🧹 Outside diff range and nitpick comments (1)
pkg/k8s/validate.go (1)

280-288: LGTM! Consider enhancing error messages.

The validateConfigMap function is well-structured and correctly utilizes existing validation functions. It aligns with the PR objective of updating ConfigMaps if they exist by providing a comprehensive validation method.

Consider enhancing the error messages to provide more context about which part of the ConfigMap validation failed. This can be achieved by wrapping the returned errors. For example:

func validateConfigMap(name string, labels, data map[string]string) error {
	if err := validateConfigMapName(name); err != nil {
		return fmt.Errorf("invalid ConfigMap name: %w", err)
	}
	if err := validateLabels(labels); err != nil {
		return fmt.Errorf("invalid ConfigMap labels: %w", err)
	}
	if err := validateConfigMapKeys(data); err != nil {
		return fmt.Errorf("invalid ConfigMap data keys: %w", err)
	}
	return nil
}

This change would require adding "fmt" to the import list if it's not already present.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6572017 and 9012c69.

📒 Files selected for processing (2)
  • pkg/k8s/configmap.go (2 hunks)
  • pkg/k8s/validate.go (1 hunks)
🔇 Additional comments not posted (4)
pkg/k8s/configmap.go (4)

5-5: LGTM: Import of "errors" package

The addition of the "errors" package import is appropriate. It's likely used for improved error handling in the new CreateOrUpdateConfigMap method.


Line range hint 95-110: LGTM: Improved code organization

Moving the prepareConfigMap helper function to the end of the file is a good practice in Go. It improves readability by keeping the main methods at the top of the file and grouping helper functions together at the bottom.


Line range hint 1-110: Overall assessment: Good changes with minor improvements needed

The changes in this file successfully address the PR objectives by introducing methods to update ConfigMaps if they exist. The new UpdateConfigMap and CreateOrUpdateConfigMap methods, along with the modifications to CreateConfigMap, provide a more comprehensive approach to ConfigMap management.

Key points:

  1. The addition of the "errors" import supports improved error handling.
  2. Centralized validation with validateConfigMap improves code maintainability.
  3. The new methods align well with the PR objectives and add valuable functionality.

Areas for improvement:

  1. Minor issues in error handling logic in both CreateConfigMap and UpdateConfigMap need to be addressed.
  2. The CreateOrUpdateConfigMap method could benefit from more robust error handling and consideration of potential race conditions.

Once these minor issues are addressed, the changes will significantly enhance the package's functionality and reliability in managing ConfigMaps.


81-94: 🛠️ Refactor suggestion

New CreateOrUpdateConfigMap method: Good addition with room for improvement

The CreateOrUpdateConfigMap method is a valuable addition that aligns well with the PR objectives. It provides a convenient way to ensure a ConfigMap exists with the desired content, handling both update and create scenarios.

However, there are a couple of areas where it could be improved:

  1. Error handling:

The current implementation only checks for ErrConfigmapDoesNotExist. It would be more robust to handle other potential errors explicitly. Consider updating the error handling as follows:

updated, err := c.UpdateConfigMap(ctx, name, labels, data)
if err == nil {
    return updated, nil
}

if errors.Is(err, ErrConfigmapDoesNotExist) {
    return c.CreateConfigMap(ctx, name, labels, data)
}

// Handle other specific errors if needed

return nil, fmt.Errorf("failed to create or update ConfigMap: %w", err)
  1. Potential race condition:

There's a potential race condition where the ConfigMap could be created by another process between the update attempt and the create attempt. While this is a rare scenario, it might be worth considering. You could handle this by catching and handling the "already exists" error from CreateConfigMap:

if errors.Is(err, ErrConfigmapDoesNotExist) {
    created, createErr := c.CreateConfigMap(ctx, name, labels, data)
    if createErr == nil {
        return created, nil
    }
    if errors.Is(createErr, ErrConfigmapAlreadyExists) {
        // If creation failed because it now exists, try updating one more time
        return c.UpdateConfigMap(ctx, name, labels, data)
    }
    return nil, fmt.Errorf("failed to create ConfigMap: %w", createErr)
}

These changes would make the method more robust and less prone to edge-case errors.

pkg/k8s/configmap.go Outdated Show resolved Hide resolved
pkg/k8s/configmap.go Outdated Show resolved Hide resolved
pkg/k8s/validate.go Outdated Show resolved Hide resolved
Copy link
Contributor

@tty47 tty47 left a comment

Choose a reason for hiding this comment

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

nice! 💪

Copy link
Member

@smuu smuu left a comment

Choose a reason for hiding this comment

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

Please remember that when changing a ConfigMap, the Pod the ConfigMap is mounted to, is not restarted automatically.
So we should consider to restart the Pod(Instance) when the dev only changes a ConfigMap.

@mojtaba-esk
Copy link
Contributor Author

Please remember that when changing a ConfigMap, the Pod the ConfigMap is mounted to, is not restarted automatically. So we should consider to restart the Pod(Instance) when the dev only changes a ConfigMap.

Great point. Thanks for raising it.
I double checked it and it is called only when the instance is in the committed state, so even if user wants to change it somehow, they need to stop the instance do changes then commit it and then start so it will be called.
We have to bare that in mind for future development.

@mojtaba-esk mojtaba-esk merged commit bd3b94d into main Sep 25, 2024
11 of 12 checks passed
@mojtaba-esk mojtaba-esk deleted the mojtaba/fix-update-configmap-if-exist branch September 25, 2024 14:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working knuu
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

4 participants