Skip to content

Conversation

klinch0
Copy link
Contributor

@klinch0 klinch0 commented Aug 6, 2025

What this PR does

Release note

- add cozystackresource reconciler

Summary by CodeRabbit

  • New Features
    • Introduced automated rolling restarts for the "cozystack-api" deployment in the "cozy-system" namespace when changes are detected in related custom resources. This ensures updates are applied smoothly without manual intervention.
    • Added debounce logic to optimize restart frequency, preventing multiple rapid restarts by consolidating events within a configurable time window.

@klinch0 klinch0 requested review from kvaps and lllamnyp as code owners August 6, 2025 06:47
Copy link
Contributor

coderabbitai bot commented Aug 6, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

A new Kubernetes controller, CozystackResourceDefinitionReconciler, is introduced to monitor CozystackResourceDefinition resources. The main application is updated to register and start this controller. The controller triggers a rolling restart of the cozystack-api deployment in the cozy-system namespace by updating a pod annotation when relevant resources change, using debouncing logic to avoid excessive restarts.

Changes

Cohort / File(s) Change Summary
Controller Integration in Main
cmd/cozystack-controller/main.go
Registers and initializes the new CozystackResourceDefinitionReconciler with the manager in the main application setup.
New Resource Controller
internal/controller/cozystackresource_controller.go
Implements CozystackResourceDefinitionReconciler with debouncing to watch CozystackResourceDefinition resources, triggering rolling restarts of the cozystack-api deployment by patching pod annotations.

Sequence Diagram(s)

sequenceDiagram
    participant K8sAPI as Kubernetes API Server
    participant Controller as CozystackResourceDefinitionReconciler
    participant Deployment as cozystack-api Deployment

    K8sAPI->>Controller: Event: CozystackResourceDefinition changed
    Controller->>Controller: Update lastEvent timestamp
    Controller->>Controller: Wait for debounce period
    Controller->>K8sAPI: Get cozystack-api Deployment (cozy-system)
    alt Deployment exists and event not handled
        Controller->>K8sAPI: Patch pod template annotations (restartedAt)
        K8sAPI->>Deployment: Trigger rolling restart
    else Deployment not found or event already handled
        Controller->>Controller: Log error or skip restart
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

A bunny hops through cozy code,
Adding a watcher on the road.
When changes come, it waits a beat,
Then restarts pods with nimble feet.
Debounced and swift, it keeps things bright,
Rolling updates through the night.
🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch controller-add-api-server-reloader

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @klinch0, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request adds a new Kubernetes controller to the cozystack-controller application. This controller is designed to watch for CozystackResourceDefinition custom resources and, upon detecting them, it will trigger a restart of the cozystack-api deployment. This mechanism likely ensures that any changes or configurations defined by CozystackResourceDefinition objects are applied by restarting the relevant API component.

Highlights

  • New Reconciler: Introduces a new CozystackResourceReconciler responsible for managing CozystackResourceDefinition custom resources.
  • Deployment Restart Logic: The Reconcile method of the new controller fetches the cozystack-api Deployment in the cozy-system namespace and updates its kubectl.kubernetes.io/restartedAt annotation. This action effectively triggers a rolling restart of the cozystack-api pods.
  • Controller Integration: The newly created CozystackResourceReconciler is registered and set up with the main controller manager in main.go, ensuring it starts and watches for CozystackResourceDefinition objects.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request introduces the CozystackResourceReconciler controller to restart the cozystack-api deployment upon changes to CozystackResourceDefinition resources. The review suggests making the target deployment configurable and using Patch to prevent race conditions.

Comment on lines 33 to 83
if deploy.Spec.Template.Annotations == nil {
deploy.Spec.Template.Annotations = map[string]string{}
}
deploy.Spec.Template.Annotations["kubectl.kubernetes.io/restartedAt"] = time.Now().Format(time.RFC3339)

if err := r.Update(ctx, deploy); err != nil {
log.Error(err, "cant update Deployment annotation")
return ctrl.Result{}, err
}

Choose a reason for hiding this comment

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

high

The current Get-then-Update pattern can lead to race conditions if multiple CozystackResourceDefinition resources are modified concurrently. Using Patch instead of Update is a more robust approach to avoid optimistic locking conflicts.

Suggested change
if deploy.Spec.Template.Annotations == nil {
deploy.Spec.Template.Annotations = map[string]string{}
}
deploy.Spec.Template.Annotations["kubectl.kubernetes.io/restartedAt"] = time.Now().Format(time.RFC3339)
if err := r.Update(ctx, deploy); err != nil {
log.Error(err, "cant update Deployment annotation")
return ctrl.Result{}, err
}
// Use a patch to avoid race conditions when multiple reconciles are triggered.
patch := client.MergeFrom(deploy.DeepCopy())
if deploy.Spec.Template.Annotations == nil {
deploy.Spec.Template.Annotations = make(map[string]string)
}
deploy.Spec.Template.Annotations["kubectl.kubernetes.io/restartedAt"] = time.Now().Format(time.RFC3339)
if err := r.Patch(ctx, deploy, patch); err != nil {
log.Error(err, "cannot patch Deployment annotation")
return ctrl.Result{}, err
}

Comment on lines 25 to 26
Namespace: "cozy-system",
Name: "cozystack-api",

Choose a reason for hiding this comment

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

medium

The namespace and name of the deployment to be restarted are hardcoded. Consider making these values configurable via command-line flags or environment variables to increase the controller's flexibility and reusability.

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: 0

🧹 Nitpick comments (1)
internal/controller/cozystackresource_controller.go (1)

20-31: Consider making namespace and deployment name configurable.

The hardcoded "cozy-system" namespace and "cozystack-api" deployment name reduce flexibility and make testing more difficult.

Consider adding these as configurable fields in the reconciler struct:

 type CozystackResourceReconciler struct {
 	client.Client
 	Scheme *runtime.Scheme
+	DeploymentNamespace string
+	DeploymentName      string
 }

Then use them in the reconcile method:

 	err := r.Get(ctx, client.ObjectKey{
-		Namespace: "cozy-system",
-		Name:      "cozystack-api",
+		Namespace: r.DeploymentNamespace,
+		Name:      r.DeploymentName,
 	}, deploy)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cd80a73 and 063622c.

📒 Files selected for processing (2)
  • cmd/cozystack-controller/main.go (1 hunks)
  • internal/controller/cozystackresource_controller.go (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: lllamnyp
PR: cozystack/cozystack#1130
File: hack/e2e-apps/kubernetes.bats:101-101
Timestamp: 2025-07-11T06:11:25.438Z
Learning: In cozystack, the plural form for the Kubernetes custom resource is `kuberneteses.apps.cozystack.io`, not `kubernetes.apps.cozystack.io`. This is defined in the API schema even though it's not grammatically perfect.
Learnt from: NickVolynkin
PR: cozystack/cozystack#1120
File: packages/apps/clickhouse/README.md:60-67
Timestamp: 2025-07-03T05:54:51.264Z
Learning: The `cozy-lib.resources.sanitize` function in packages/library/cozy-lib/templates/_resources.tpl supports both standard Kubernetes resource format (with limits:/requests: sections) and flat format (direct resource specifications). The flat format takes priority over nested values. CozyStack apps include cozy-lib as a chart dependency through symlinks in packages/apps/*/charts/cozy-lib directories.
🧬 Code Graph Analysis (1)
internal/controller/cozystackresource_controller.go (2)
internal/controller/system_helm_reconciler.go (1)
  • Reconcile (34-81)
internal/controller/tenant_helm_reconciler.go (1)
  • Reconcile (27-106)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Build
🔇 Additional comments (5)
internal/controller/cozystackresource_controller.go (4)

1-13: LGTM!

The package declaration and imports are appropriate for a Kubernetes controller that watches custom resources and manages deployments.


15-18: LGTM!

The struct definition follows the standard controller-runtime pattern with embedded client and scheme fields.


20-44: Verify if broad restart behavior is intentional.

The controller restarts the cozystack-api deployment for any CozystackResourceDefinition change, regardless of which specific resource triggered the reconciliation (the req parameter is unused).

Is this broad restart behavior intentional? If the API server needs to restart for any CRD change, this is correct. Otherwise, consider using the req parameter to be more selective about when restarts occur.


47-51: LGTM!

The SetupWithManager method follows the standard controller-runtime pattern for watching CozystackResourceDefinition resources.

cmd/cozystack-controller/main.go (1)

209-216: LGTM!

The controller registration follows the established pattern used by other controllers in the same file. The error handling and logging are consistent and appropriate.

@klinch0 klinch0 changed the title controller add cozystackresource reconciler controller add CozystackResourceDefinition reconciler Aug 6, 2025
@klinch0 klinch0 force-pushed the controller-add-api-server-reloader branch from 063622c to 6756d0e Compare August 6, 2025 06:55
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

♻️ Duplicate comments (1)
internal/controller/cozystackresource_controller.go (1)

25-26: Consider making deployment namespace and name configurable.

The namespace and name of the deployment are hardcoded, which reduces flexibility and reusability of this controller.

🧹 Nitpick comments (1)
internal/controller/cozystackresource_controller.go (1)

47-51: Consider adding predicates to filter unnecessary reconciliation events.

The controller will reconcile on every change to any CozystackResourceDefinition, including status updates. Consider adding predicates to filter events:

+import (
+	"sigs.k8s.io/controller-runtime/pkg/predicate"
+)
+
 func (r *CozystackResourceDefinitionReconciler) SetupWithManager(mgr ctrl.Manager) error {
 	return ctrl.NewControllerManagedBy(mgr).
 		For(&cozyv1alpha1.CozystackResourceDefinition{}).
+		WithEventFilter(predicate.GenerationChangedPredicate{}).
 		Complete(r)
 }

This will ensure the controller only reconciles when the spec changes, not on status updates.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 063622c and 6756d0e.

📒 Files selected for processing (2)
  • cmd/cozystack-controller/main.go (1 hunks)
  • internal/controller/cozystackresource_controller.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/cozystack-controller/main.go
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: lllamnyp
PR: cozystack/cozystack#1130
File: hack/e2e-apps/kubernetes.bats:101-101
Timestamp: 2025-07-11T06:11:25.438Z
Learning: In cozystack, the plural form for the Kubernetes custom resource is `kuberneteses.apps.cozystack.io`, not `kubernetes.apps.cozystack.io`. This is defined in the API schema even though it's not grammatically perfect.
Learnt from: NickVolynkin
PR: cozystack/cozystack#1120
File: packages/apps/clickhouse/README.md:60-67
Timestamp: 2025-07-03T05:54:51.264Z
Learning: The `cozy-lib.resources.sanitize` function in packages/library/cozy-lib/templates/_resources.tpl supports both standard Kubernetes resource format (with limits:/requests: sections) and flat format (direct resource specifications). The flat format takes priority over nested values. CozyStack apps include cozy-lib as a chart dependency through symlinks in packages/apps/*/charts/cozy-lib directories.
🧬 Code Graph Analysis (1)
internal/controller/cozystackresource_controller.go (2)
internal/controller/system_helm_reconciler.go (1)
  • Reconcile (34-81)
internal/controller/tenant_helm_reconciler.go (1)
  • Reconcile (27-106)

Comment on lines 20 to 72
func (r *CozystackResourceDefinitionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := log.FromContext(ctx)

deploy := &appsv1.Deployment{}
err := r.Get(ctx, client.ObjectKey{
Namespace: "cozy-system",
Name: "cozystack-api",
}, deploy)
if err != nil {
log.Error(err, "cant get Deployment cozy-system/cozystack-api")
return ctrl.Result{}, client.IgnoreNotFound(err)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Controller doesn't examine the CozystackResourceDefinition that triggered reconciliation.

The reconciler ignores the req parameter and doesn't fetch the actual CozystackResourceDefinition resource that triggered this reconciliation. This means:

  1. Every change to any CozystackResourceDefinition triggers the same action
  2. You cannot implement conditional logic based on the resource's spec or status
  3. Multiple rapid changes will cause multiple deployment restarts

Consider fetching and examining the CozystackResourceDefinition to implement more targeted restart logic.

 func (r *CozystackResourceDefinitionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
 	log := log.FromContext(ctx)
 
+	// Fetch the CozystackResourceDefinition that triggered this reconciliation
+	crd := &cozyv1alpha1.CozystackResourceDefinition{}
+	if err := r.Get(ctx, req.NamespacedName, crd); err != nil {
+		return ctrl.Result{}, client.IgnoreNotFound(err)
+	}
+
+	// Add logic here to determine if restart is needed based on crd.Spec
+	// For example, you might only restart for certain types of changes
+
 	deploy := &appsv1.Deployment{}
📝 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
func (r *CozystackResourceDefinitionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := log.FromContext(ctx)
deploy := &appsv1.Deployment{}
err := r.Get(ctx, client.ObjectKey{
Namespace: "cozy-system",
Name: "cozystack-api",
}, deploy)
if err != nil {
log.Error(err, "cant get Deployment cozy-system/cozystack-api")
return ctrl.Result{}, client.IgnoreNotFound(err)
}
func (r *CozystackResourceDefinitionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := log.FromContext(ctx)
// Fetch the CozystackResourceDefinition that triggered this reconciliation
crd := &cozyv1alpha1.CozystackResourceDefinition{}
if err := r.Get(ctx, req.NamespacedName, crd); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// Add logic here to determine if restart is needed based on crd.Spec
// For example, you might only restart for certain types of changes
deploy := &appsv1.Deployment{}
err := r.Get(ctx, client.ObjectKey{
Namespace: "cozy-system",
Name: "cozystack-api",
}, deploy)
if err != nil {
log.Error(err, "cant get Deployment cozy-system/cozystack-api")
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// … rest of reconcile logic …
}
🤖 Prompt for AI Agents
In internal/controller/cozystackresource_controller.go around lines 20 to 31,
the Reconcile function does not fetch or examine the CozystackResourceDefinition
resource that triggered the reconciliation, relying only on a fixed Deployment
fetch. Modify the code to first retrieve the CozystackResourceDefinition
instance using the req.NamespacedName, handle not-found errors appropriately,
and then use its spec or status to conditionally control the deployment restart
logic, enabling more precise and efficient reconciliations.

@klinch0 klinch0 force-pushed the controller-add-api-server-reloader branch from 6756d0e to f73aa39 Compare August 8, 2025 12:59
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

♻️ Duplicate comments (1)
internal/controller/cozystackresource_controller.go (1)

37-40: Hard-coded target Deployment & ignored CRD still unresolved

The reconciler still short-circuits on req.Namespace != "cozy-system" || req.Name != "cozystack-api", which means:

  1. The namespace / name are baked in, so the controller cannot be reused in other environments.
  2. The req representing the CozystackResourceDefinition that triggered the event is still ignored, so you cannot apply conditional logic based on the CRD content.

Both points were raised in previous reviews and remain unaddressed.

🧹 Nitpick comments (2)
internal/controller/cozystackresource_controller.go (2)

74-82: Add retry loop around the Patch to avoid transient conflicts

Even with MergeFrom, optimistic-locking conflicts can still occur if another controller mutates the Deployment simultaneously.
Wrap the patch call in retry.RetryOnConflict (from k8s.io/client-go/util/retry) to make the restart more reliable under load.


100-104: Watching every Deployment is noisy

For(&appsv1.Deployment{}) registers for all Deployment updates cluster-wide, yet the reconciler only cares about a single deployment.
Limit the watch with Owns or use a predicate so unrelated Deployment churn doesn’t enqueue superfluous reconciliations.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6756d0e and f73aa39.

📒 Files selected for processing (2)
  • cmd/cozystack-controller/main.go (1 hunks)
  • internal/controller/cozystackresource_controller.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/cozystack-controller/main.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Build

Comment on lines +42 to +47
r.mu.Lock()
le := r.lastEvent
lh := r.lastHandled
debounce := r.Debounce
r.mu.Unlock()

Copy link
Contributor

@coderabbitai coderabbitai bot Aug 8, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Possible missed restarts due to TOCTOU on lastEvent / lastHandled

lastEvent is read under the lock (Lines 42-45) but lastHandled is written later (Lines 86-88) based on the old le value.
If another CRD event lands after you release the lock but before the patch completes, lastEvent is newer than lastHandled yet no new reconcile is queued, so the fresh event may never trigger a restart.

Patch either:

-   r.lastHandled = le
+   r.lastHandled = time.Now()

or keep the mutex held until lastHandled is updated.

Also applies to: 86-88

🤖 Prompt for AI Agents
In internal/controller/cozystackresource_controller.go around lines 42 to 47 and
86 to 88, there is a TOCTOU issue where lastEvent is read under the lock but
lastHandled is updated later outside the lock, risking missed restarts if new
events arrive in between. To fix this, either hold the mutex lock continuously
from reading lastEvent until after lastHandled is updated, or restructure the
code to update lastHandled while still holding the lock to ensure consistency
and prevent missing new events.

Copy link
Member

Choose a reason for hiding this comment

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

Looks like valid behavior to me. r.lastHandled ends up being set to the time of the last event, so any subsequent CRD events have a later event time and are also handled, instead of being dropped for having an earlier time than r.lastHandled. This might cause more restarts, not less.

Copy link
Contributor

Choose a reason for hiding this comment

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

@lllamnyp You’re right that the current sequence won’t drop a restart; the risk is extra restarts: if a new CRD event lands during the patch, writing lastHandled = le ( Lines 86–88) can trigger a second, redundant restart.

A minimal fix that preserves debounce and closes the race without holding the lock across I/O:

// after a successful patch of the Deployment
r.mu.Lock()
if le.After(r.lastHandled) {
    r.lastHandled = time.Now() // cover all events up to completion time
}
r.mu.Unlock()

This way, any events that arrived while patching are considered handled by the just-completed restart, avoiding unnecessary follow-up restarts, while still ensuring newer events after this point will be restarted.

Signed-off-by: kklinch0 <kklinch0@gmail.com>
@klinch0 klinch0 force-pushed the controller-add-api-server-reloader branch from f73aa39 to 8b1e55d Compare August 8, 2025 13:59
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

♻️ Duplicate comments (3)
internal/controller/cozystackresource_controller.go (3)

37-41: Hard-coded target & CRD ignored

Reconciler filters on a single hard-coded Deployment and never fetches the CozystackResourceDefinition that triggered the event. This repeats the issue already raised in earlier reviews.


42-47: Race window between lastEvent and restart

Reading the timestamps under the mutex and releasing it before the restart opens a gap where new events can arrive; combined with setting lastHandled = le later, this can schedule redundant restarts immediately after one just finished.

Either keep the lock until lastHandled is updated, or set lastHandled = time.Now() after the patch, as suggested previously.


86-88: Update lastHandled to actual completion time

Setting lastHandled = le means events that occurred during the patch are considered “unhandled”, forcing an immediate second reconcile. Use the current time to cover everything up to the successful patch.

-    r.lastHandled = le
+    r.lastHandled = time.Now()
🧹 Nitpick comments (1)
internal/controller/cozystackresource_controller.go (1)

100-116: Make restart target configurable

Namespace and Deployment name are embedded in three different places (if filter, Get, and EnqueueRequestsFromMapFunc`). Exposing these via flags or environment variables will make the controller reusable across environments and unit-testable.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f73aa39 and 8b1e55d.

📒 Files selected for processing (2)
  • cmd/cozystack-controller/main.go (1 hunks)
  • internal/controller/cozystackresource_controller.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/cozystack-controller/main.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Build

Comment on lines +1 to +2
package controller

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

Missing kubebuilder:rbac markers

The controller lacks RBAC comments required by controller-runtime scaffolding for generating the ClusterRole. Without them, make deploy (or equivalent) will install an empty role and the reconciler will fail with “forbidden” errors at runtime.
Add explicit RBAC lines for the CRD and for deployments patch/update permissions.

🤖 Prompt for AI Agents
In internal/controller/cozystackresource_controller.go at the top of the file,
add kubebuilder:rbac markers as comments to specify the required RBAC
permissions. Include lines granting access to the custom resource defined by the
CRD and also permissions to patch and update deployments. This will ensure that
when running `make deploy`, the generated ClusterRole includes the necessary
permissions to avoid forbidden errors during reconciliation.

@klinch0 klinch0 merged commit 330103c into main Aug 8, 2025
18 checks passed
@klinch0 klinch0 deleted the controller-add-api-server-reloader branch August 8, 2025 14:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants