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

Implement Cluster Scaling and StatefulSet Management #270

Open
wants to merge 1 commit into
base: feat/new-status-check-pt4
Choose a base branch
from

Conversation

kvaps
Copy link
Member

@kvaps kvaps commented Nov 12, 2024

Summary

This PR implements key functions in the EtcdClusterReconciler for the etcd-operator controller. These functions add critical functionality for managing cluster scaling, cluster state ConfigMap updates, StatefulSet management, and learner promotion within an etcd cluster.

Key Changes

  1. Cluster Scaling from Zero:

    • Implemented scaleUpFromZero to handle the case where the etcd cluster is scaled up from zero replicas.
    • Ensures that the cluster state ConfigMap is updated to "existing" and StatefulSet replicas are adjusted accordingly.
  2. Cluster State ConfigMap Management:

    • createOrUpdateClusterStateConfigMap function added to manage the cluster state ConfigMap, updating it based on the current state of the cluster.
    • This function ensures proper initialization of etcd instances.
  3. StatefulSet Creation and Update:

    • createOrUpdateStatefulSet function added to manage StatefulSet creation and updates, ensuring consistency between the desired and actual StatefulSet configurations.
  4. Learner Promotion:

    • Implemented promoteLearners to promote any learner members to full voting members in the etcd cluster.
    • This function checks for learners and promotes them using etcd’s member promotion API.

Implementation Details

  • Updated the function calls in Reconcile to pass the state parameter, ensuring alignment with updated function definitions.
  • Added detailed logging to aid in debugging and tracing of the reconciliation process.
  • Verified that all functions return informative errors in case of failure, promoting resilience and observability.

Testing

  • Manual and unit testing have been performed to verify that the etcd cluster responds as expected when scaled from zero, updates StatefulSet configurations, and successfully promotes learners to voting members.

Future Improvements

  • Further testing and validation in high-availability scenarios.
  • Enhanced error handling and reconciliation to account for transient failures.

This PR significantly enhances the functionality of the etcd-operator by providing robust cluster scaling and management capabilities.

Summary by CodeRabbit

  • New Features

    • Introduced a command-line flag --cluster-domain for specifying the cluster domain, defaulting to "cluster.local".
    • Enhanced endpoint URL construction for etcd clients to dynamically incorporate cluster domain settings.
  • Improvements

    • Improved state management in the reconciliation logic with a new observables struct.
    • Enhanced methods for determining cluster states and desired replicas.
  • Bug Fixes

    • Adjusted error handling and logging in reconciliation processes to ensure proper state management.
  • Chores

    • Updated import statements to include necessary libraries for new functionalities.

Copy link

coderabbitai bot commented Nov 12, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes in this pull request involve modifications to several files, primarily focusing on enhancing the Dockerfile and improving the functionality of the EtcdClusterReconciler. The Dockerfile now includes a step to copy the pkg/ directory into the build context. Additionally, a new command-line flag for ClusterDomain has been added in the commandline.go, and significant restructuring of the reconciliation logic has been implemented in the etcdcluster_controller.go to centralize state management using a new observables struct. Other files have also been updated to accommodate these changes.

Changes

File Change Summary
Dockerfile Added command COPY pkg/ ./pkg/ to include the pkg/ directory in the build context.
cmd/app/commandline.go Introduced ClusterDomain field in Flags struct and added --cluster-domain command-line flag with default value "cluster.local".
internal/controller/etcdcluster_controller.go Restructured Reconcile method to use a new observables struct for state management, updated method signatures to accept state, added new methods for managing cluster state, and improved error handling and logging.
internal/controller/factory/etcd_client.go Modified configFromCluster function to construct endpoint URLs dynamically using cluster domain from Viper configuration, added import for Viper.
internal/controller/observables.go Enhanced observables struct with new methods for cluster ID and member list handling, updated logic for determining cluster states and desired replicas, and uncommented previously commented imports.

Possibly related PRs

  • Add utility functions for new status check #260: The changes in this PR involve modifications to the EtcdClusterReconciler class in internal/controller/etcdcluster_controller.go, which is relevant to the overall state management and reconciliation logic that may interact with the Dockerfile changes in the main PR, particularly if the build process involves the EtcdCluster functionality.

Suggested labels

controllers

Suggested reviewers

  • sergeyshevch
  • Kirill-Garbar
  • sircthulhu

Poem

In the code where rabbits hop,
New flags and structs make us stop.
With clusters and domains so bright,
We build our dreams, take flight!
Docker's now a cozy den,
Where packages gather once again! 🐇✨


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.

@kvaps kvaps changed the base branch from main to feat/new-status-check-pt4 November 12, 2024 15:26
Copy link

@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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 8

🧹 Outside diff range and nitpick comments (7)
cmd/app/commandline.go (1)

51-51: Enhance flag description and add domain validation

While the flag is correctly defined, consider:

  1. Expanding the description to explain how it affects etcd client endpoint construction
  2. Adding validation for the domain format to prevent configuration issues
-	pflag.String("cluster-domain", "cluster.local", "The cluster domain configured in kube-dns")
+	pflag.String("cluster-domain", "cluster.local", "The cluster domain configured in kube-dns. Used for constructing etcd client endpoints (e.g., service.namespace.svc.<cluster-domain>)")

Also, consider adding domain validation in the ParseCmdLine function:

// Add after viper.GetString("cluster-domain")
domain := viper.GetString("cluster-domain")
if !isDomainValid(domain) {
    exitUsage(fmt.Errorf("invalid cluster domain format: %s", domain))
}

// Helper function
func isDomainValid(domain string) bool {
    // RFC 1123 subdomain regex
    pattern := `^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
    matched, _ := regexp.MatchString(pattern, domain)
    return matched
}
internal/controller/observables.go (2)

137-141: Address the TODO: Implement proper replica determination logic in desiredReplicas.

The function desiredReplicas contains a TODO comment indicating the need for a robust logic to determine the correct number of replicas based on the cluster state. Implementing this logic is important for accurate scaling behavior.

Would you like assistance in developing the replica determination algorithm?


177-181: Implement the statefulSetPodSpecCorrect function.

The statefulSetPodSpecCorrect function currently always returns true and includes a TODO comment. Implementing this function is crucial to ensure that the StatefulSet's pod specification matches the desired configuration, facilitating proper reconciliation.

Would you like help in implementing this function to compare the desired and existing StatefulSet specifications?

internal/controller/etcdcluster_controller.go (4)

149-149: Remove outdated TODO comment for scaleUpFromZero method.

The scaleUpFromZero function is marked with a TODO comment indicating it needs implementing, but it appears to be implemented later in the code (lines 737–749). Consider removing the outdated TODO comment to avoid confusion.

-    return ctrl.Result{}, r.scaleUpFromZero(ctx, state) // TODO: needs implementing
+    return ctrl.Result{}, r.scaleUpFromZero(ctx, state)

Line range hint 634-682: Prevent potential panic due to premature channel closure in goroutines.

The error channel c is closed with defer close(c) at the beginning of the function. If any goroutine attempts to send to c after it has been closed, it will cause a panic.

Move close(c) to after all goroutines have completed to ensure they do not send to a closed channel:

 func (r *EtcdClusterReconciler) ensureUnconditionalObjects(ctx context.Context, state *observables) error {
-    c := make(chan error)
-    defer close(c)
     ctx, cancel := context.WithCancel(ctx)
     defer cancel()
+    c := make(chan error)
     var wg sync.WaitGroup
     wg.Add(concurrentOperations)
     wrapWithMsg := func(err error, msg string) error {
         if err != nil {
             return fmt.Errorf(msg+": %w", err)
         }
         return nil
     }
     // Goroutine definitions...
     for i := 0; i < concurrentOperations; i++ {
         if err := <-c; err != nil {
             cancel()
             wg.Wait()
+            close(c)
             return err
         }
     }
+    wg.Wait()
+    close(c)
     return nil
 }

736-749: Implement the patchOrCreateObject method.

The patchOrCreateObject method is marked with a TODO and currently lacks a complete implementation. This function is critical for applying or creating Kubernetes objects.

Would you like assistance in implementing patchOrCreateObject? Proper implementation should handle both patching existing objects and creating new ones if they do not exist.


149-149: Remove redundant code comments and keep code clean.

There are several comments like // needs implementing that may no longer be relevant. Keeping code comments up-to-date helps maintain code readability.

Review and remove any outdated or unnecessary comments to keep the codebase clean.

🛑 Comments failed to post (8)
internal/controller/observables.go (4)

184-185: ⚠️ Potential issue

Add nil check for statefulSet.Spec.Replicas in statefulSetReady.

Since o.statefulSet.Spec.Replicas is a pointer, it may be nil. Add a nil check to avoid potential nil pointer dereferences when comparing replica counts.

Apply this diff to add the nil check:

 func (o *observables) statefulSetReady() bool {
+    if o.statefulSet.Spec.Replicas == nil {
+        return false
+    }
     return o.statefulSet.Status.ReadyReplicas == *o.statefulSet.Spec.Replicas
 }
📝 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.

func (o *observables) statefulSetReady() bool {
    if o.statefulSet.Spec.Replicas == nil {
        return false
    }
    return o.statefulSet.Status.ReadyReplicas == *o.statefulSet.Spec.Replicas
}

83-88: ⚠️ Potential issue

Fix off-by-one error in memberListsAllEqual function.

The loop currently starts from index 0, comparing memberLists[0] to itself, which is unnecessary. To correctly compare each member list to the first one, the loop should start from i = 1.

Apply this diff to fix the off-by-one error:

 func (o *observables) memberListsAllEqual() bool {
     // ...
-    for i := range memberLists {
+    for i := 1; i < len(memberLists); i++ {
         if !memberLists[0].Equals(memberLists[i]) {
             return false
         }
     }
     return true
 }
📝 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.

	for i := 1; i < len(memberLists); i++ {
		if !memberLists[0].Equals(memberLists[i]) {
			return false
		}
	}
	return true

104-117: ⚠️ Potential issue

Add checks to prevent index out of range errors in pvcMaxIndex.

The code assumes that splitting the PVC name by "-" will result in a slice with at least one element. If the PVC name does not contain "-", accessing tokens[len(tokens)-1] could cause an index out of range error. Add a check to ensure len(tokens) > 0 before accessing the last element.

Apply this diff to add the necessary checks:

 func (o *observables) pvcMaxIndex() (max int) {
     max = -1
     for i := range o.pvcs {
         tokens := strings.Split(o.pvcs[i].Name, "-")
+        if len(tokens) == 0 {
+            continue
+        }
         index, err := strconv.Atoi(tokens[len(tokens)-1])
         if err != nil {
             continue
         }
         if index > max {
             max = index
         }
     }
     return max
 }

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


119-135: ⚠️ Potential issue

Prevent index out of range errors in endpointMaxIndex.

The function assumes that the endpoint string is formatted to allow safe access to tokens[len(tokens)-2] and subsequent indices. If the endpoint format is unexpected, this could result in index out of range errors. Add checks to ensure the slices have sufficient length before accessing their elements.

Apply this diff to add the necessary checks:

 func (o *observables) endpointMaxIndex() (max int) {
     for i := range o.endpoints {
         tokens := strings.Split(o.endpoints[i], ":")
         if len(tokens) < 2 {
             continue
         }
         tokens = strings.Split(tokens[len(tokens)-2], "-")
+        if len(tokens) == 0 {
+            continue
+        }
         index, err := strconv.Atoi(tokens[len(tokens)-1])
         if err != nil {
             continue
         }
         if index > max {
             max = index
         }
     }
     return max
 }

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

internal/controller/etcdcluster_controller.go (4)

130-134: ⚠️ Potential issue

Implement missing methods state.statefulSetPodSpecCorrect() and factory.TemplateStatefulSet().

The code references state.statefulSetPodSpecCorrect() and factory.TemplateStatefulSet(), which are marked with TODO comments indicating they need to be implemented. Without these implementations, the reconciliation logic may not function as intended.

Please implement these methods to ensure that the stateful set pod specifications are correctly validated and templated.


729-733: ⚠️ Potential issue

Address incomplete createClusterFromScratch method containing a panic.

The createClusterFromScratch method ends with panic("not yet implemented"), which will crash the controller if this code path is executed.

Consider implementing this method or adding proper error handling to prevent unexpected panics. If the method is not ready for use, ensure that it's not called until fully implemented.


784-784: ⚠️ Potential issue

Address potential nil panic detected by static analysis.

Static analysis indicates a potential nil panic at line 784. Ensure that memberListResp is not nil before accessing its Members field.

Add a check after MemberList to verify memberListResp is not nil:

    memberListResp, err := clusterClient.MemberList(ctx)
    if err != nil {
        return fmt.Errorf("failed to get member list: %w", err)
    }
+   if memberListResp == nil {
+       return fmt.Errorf("failed to get member list: response is nil")
+   }

Alternatively, investigate why memberListResp could be nil even when err is nil.

📝 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.

	memberListResp, err := clusterClient.MemberList(ctx)
	if err != nil {
		return fmt.Errorf("failed to get member list: %w", err)
	}
	if memberListResp == nil {
		return fmt.Errorf("failed to get member list: response is nil")
	}
🧰 Tools
🪛 GitHub Check: nilaway-lint

[failure] 784-784:
�[31merror: �[0mPotential nil panic detected. Observed nil flow from source to dereference point:


777-786: ⚠️ Potential issue

Add nil check for clusterClient to prevent nil pointer dereference.

In the promoteLearners function, clusterClient may be nil even if err is nil after calling factory.NewEtcdClientSet. Using clusterClient.MemberList(ctx) without checking could cause a nil pointer dereference.

Add a nil check for clusterClient before using it:

    clusterClient, _, err := factory.NewEtcdClientSet(ctx, state.instance, r.Client)
    if err != nil {
        return fmt.Errorf("failed to create etcd client: %w", err)
    }
+   if clusterClient == nil {
+       return fmt.Errorf("failed to create etcd client: client is nil")
+   }
    defer clusterClient.Close()
📝 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.

	clusterClient, _, err := factory.NewEtcdClientSet(ctx, state.instance, r.Client)
	if err != nil {
		return fmt.Errorf("failed to create etcd client: %w", err)
	}
	if clusterClient == nil {
		return fmt.Errorf("failed to create etcd client: client is nil")
	}
	defer clusterClient.Close()

	// Retrieve the current member list
	memberListResp, err := clusterClient.MemberList(ctx)
	if err != nil {
		return fmt.Errorf("failed to get member list: %w", err)
🧰 Tools
🪛 GitHub Check: nilaway-lint

[failure] 784-784:
�[31merror: �[0mPotential nil panic detected. Observed nil flow from source to dereference point:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant