← Back to Pull requests

[CONTP-2030] Operator monitors DCA and CLC health #3487

Merged
adel121 merged 10 files (1194 lines) on Sep 30, 2026 10:25 UTC
View on GitHub
adel121 adel121 commented on Sep 18, 2026 13:52 UTC
Author

What does this PR do?

Implements first version of component health, monitoring common issues for DCA and CLC on the cluster level:

  • component_oomkilled

  • component_crash_looping

  • component_unschedulable

  • image_pull_failure
  • 2 things should change in a follow-up PR:

  • The Emit/Resolve actions should be asynchronous to avoid blocking the main flow.

  • Currently we emit and resolve by logging and prometheus metrics, we should submit payloads to the backend instead (or as well).
  • The health component is disabled by default.

    Describe your test plan

  • Unit tests

  • Manual testing: Deploy the operator with the component health enabled, and try forcing one of the 4 issues above (use a bad image tag, set very small memory limits/requests, etc.). Validate the logs are emitted properly on declaration and resolution (same for the metrics).
  • No need to QA this PR alone because it is a partial implementation, feature is new and disabled by default.
    Full QA or E2E tests shall apply on the follow-up PR.

    Checklist

  • PR has at least one valid label: bug, enhancement, refactoring, documentation, tooling, and/or dependencies

  • PR has a milestone or the qa/skip-qa label

  • All commits are signed (see: [signing commits][1])
  • [1]: https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits

    Diff: 1194 lines (+1187 / -7) across 10 files Reviewer: levan-m Review duration: 17072m
    All Vouch review confidence checks passed
    Residual risk 0.09 = Change Risk (0.56) × (1 − Review Confidence (0.84)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.56 · 1194 lines diff across 10 files
    0.56
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.76 · 5 substantive comment(s)
    0.76
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    83%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    10 items
    datadog-prod-us1-6[bot] datadog-prod-us1-6[bot] commented on Sep 18, 2026 14:03 UTC
    Bot

    <a target='_blank' href='https://app.datadoghq.com/ci/code-coverage/github.com%2Fdatadog%2Fdatadog-operator/pull-requests/3487'><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/code-coverage-error.svg"/><img src="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/code-coverage-error-light.svg" alt="Code Coverage" align="center" /></picture></a>

    🛑 Gate Violations

    ### 🎯 1 Code Coverage issue detected

    A _Patch coverage percentage_ gate may be blocking this PR.

    > • <b>Patch coverage</b>: 67.30% (threshold: 80.00%)

    ℹ️ Info

    🎯 Code Coverage (<a target='_blank' href='https://app.datadoghq.com/ci/code-coverage/github.com%2Fdatadog%2Fdatadog-operator/pull-requests/3487'>details</a>)<br>• <strong><span title="Percentage of modified executable lines covered by tests in this PR">Patch Coverage</span></strong>: 67.30%<br>• <strong><span title="Percentage of all executable lines covered by tests in the entire codebase">Overall Coverage</span></strong>: 52.08% <span title="Change in overall coverage compared to the base branch">(+0.41%)</span><br>

    Useful? React with 👍 / 👎

    <sub>
    This comment will be updated automatically if new data arrives. <br />
    🔗 Commit SHA: b54da13 | <a href="https://docs.datadoghq.com/integrations/guide/source-code-integration/#pr-comments">Docs</a> | Give us <a href="https://dd.enterprise.slack.com/archives/C07E3U2QRMM">feedback</a>!
    </sub>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Sep 21, 2026 13:34 UTC
    Code Review
    internal/controller/componenthealth_controller.go:1
    @@ -0,0 +1,292 @@
    +// Unless explicitly stated otherwise all files in this repository are licensed
    +// under the Apache License Version 2.0.
    +// This product includes software developed at Datadog (https://www.datadoghq.com/).
    +// Copyright 2016-present Datadog, Inc.
    +
    +package controller
    +
    +import (
    +	"context"
    +	"sort"
    +	"sync"
    +
    +	"github.com/go-logr/logr"
    +	corev1 "k8s.io/api/core/v1"
    +	apierrors "k8s.io/apimachinery/pkg/api/errors"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/apimachinery/pkg/types"
    +	ctrl "sigs.k8s.io/controller-runtime"
    +	"sigs.k8s.io/controller-runtime/pkg/builder"
    +	"sigs.k8s.io/controller-runtime/pkg/client"
    +	"sigs.k8s.io/controller-runtime/pkg/predicate"
    +
    +	"github.com/DataDog/datadog-operator/api/datadoghq/common"
    +	"github.com/DataDog/datadog-operator/internal/controller/metrics"
    +	"github.com/DataDog/datadog-operator/pkg/componenthealth"
    +	"github.com/DataDog/datadog-operator/pkg/constants"
    +)
    +
    +const (
    +	componentHealthControllerName = "ComponentHealth"
    +
    +	// defaultRestartThreshold is the cumulative container restart count at or
    +	// above which a component container is flagged as crash-looping even when it
    +	// is not currently backing off.
    +	defaultRestartThreshold = 5
    +)
    +
    +// +kubebuilder:rbac:groups="",resources=pods,verbs=get;list;watch
    +
    +// componentHealthEmitter reports state transitions of component-level issues:
    +// Emit when an issue type first appears on a component (its first affected pod),
    +// Resolve when the last affected pod recovers. The controller only calls these
    +// on transitions, so callers receive edges (appeared/cleared), not the full
    +// state on every reconcile.
    +//
    +// The default implementation logs and increments a Prometheus counter. A backend
    +// implementation that ships issues to the health-platform intake can be added
    +// behind this interface without changing the controller.
    +//
    +// TODO(componentHealth): Emit/Resolve are currently called synchronously while
    +// r.mu is held (see addPod/dropPod), and are transition-based only. That's fine
    +// for the in-process log/metric emitter, but the production backend emitter is
    +// expected to be snapshot-based (periodically walk the active-issue map and POST
    +// the full current state) rather than transition-based, and must not do network
    +// I/O while holding r.mu — that would serialize/block reconciliation of
    +// unrelated pods behind a slow or retrying intake call. Reshape this interface
    +// (e.g. a Snapshot(ctx, []ComponentIssue) called outside the lock on a ticker)
    +// before wiring in a backend emitter.
    +type componentHealthEmitter interface {
    +	Emit(ctx context.Context, issue componenthealth.ComponentIssue)
    +	Resolve(ctx context.Context, issue componenthealth.ComponentIssue)
    +}
    +
    +// componentIssueKey identifies a component-level issue instance.
    +// Detection happens per pod, but this is the granularity at which issues are reported.
    +type componentIssueKey struct {
    +	namespace string
    +	component string
    +	issueType string
    +}
    +
    +// componentIssueState is the live state of one component-level issue: the pods
    +// currently exhibiting it, keyed by pod name. The issue is active while pods
    +// is non-empty.
    +type componentIssueState struct {
    +	pods map[string]struct{}
    +}
    +
    +// ComponentHealthReconciler watches the managed cluster-level component pods
    +// (Datadog Cluster Agent and Cluster Check Runners) and reports Kubernetes
    +// health issues (OOMKills, crash loops, scheduling failures, image-pull
    +// failures) derived from their pod status.
    +//
    +// Detection is per pod, but issues are reported per component: the same issue
    +// type across several pods of a component is one issue instance, so a rolling
    +// restart where the problem hops between pods stays a single active issue rather
    +// than a churn of emit/resolve events.
    +//
    +// It is gated behind the ComponentHealth feature flag and depends on the pod
    +// status being retained in the cache (see pkg/config.CacheOptions).
    +type ComponentHealthReconciler struct {
    +	client           client.Client
    +	log              logr.Logger
    +	restartThreshold int32
    +	emitter          componentHealthEmitter
    +
    +	// mu guards reported. reported holds every currently-active component-level
    +	// issue and the set of pods exhibiting it, so the controller emits only on
    +	// presence transitions (first pod affected / last pod recovered) rather than
    +	// on every reconcile.
    +	mu       sync.Mutex
    +	reported map[componentIssueKey]*componentIssueState
    +}
    +
    +// NewComponentHealthReconciler builds a ComponentHealthReconciler with the
    +// default logging/metric emitter.
    +func NewComponentHealthReconciler(c client.Client, log logr.Logger) *ComponentHealthReconciler {
    +	return &ComponentHealthReconciler{
    +		client:           c,
    +		log:              log,
    +		restartThreshold: defaultRestartThreshold,
    +		emitter:          &logEmitter{log: log},
    +		reported:         map[componentIssueKey]*componentIssueState{},
    +	}
    +}
    +
    +// Reconcile evaluates a single managed component pod and folds its detected
    +// issues into the component-level state, emitting only the resulting transitions.
    +func (r *ComponentHealthReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    +	pod := &corev1.Pod{}
    +	if err := r.client.Get(ctx, req.NamespacedName, pod); err != nil {
    +		if apierrors.IsNotFound(err) {
    +			// Pod is gone: drop it from every component issue it contributed to.
    +			r.forgetPod(ctx, req.NamespacedName)
    +			return ctrl.Result{}, nil
    +		}
    +		return ctrl.Result{}, err
    +	}
    +
    +	// A pod being deleted is treated like a gone pod.
    +	if !pod.DeletionTimestamp.IsZero() {
    +		r.forgetPod(ctx, req.NamespacedName)
    +		return ctrl.Result{}, nil
    +	}
    +
    +	component := componenthealth.ManagedComponent(pod)
    +	issues := componenthealth.DetectPodIssues(pod, r.restartThreshold)
    +	r.reconcilePod(ctx, req.NamespacedName, component, issues)
    +	return ctrl.Result{}, nil
    +}
    +
    +// reconcilePod folds one pod's currently-detected issues into the component-level
    +// state: it registers the pod on the issues it now exhibits and removes it from
    +// the component issues it no longer does, emitting Emit/Resolve on the component's
    +// presence transitions.
    +func (r *ComponentHealthReconciler) reconcilePod(ctx context.Context, pod types.NamespacedName, component string, issues []componenthealth.DetectedIssue) {
    +	// A pod can carry the same issue type on more than one container (e.g. two
    +	// crash-looping containers)
    +	current := make(map[string]struct{}, len(issues))
    +	for _, issue := range issues {
    +		current[issue.IssueType] = struct{}{}
    +	}
    +
    +	r.mu.Lock()
    +	defer r.mu.Unlock()
    +
    +	// Remove the pod from any component issue of this component that it no longer
    +	// exhibits.
    +	for key, state := range r.reported {
    +		if key.namespace != pod.Namespace || key.component != component {
    +			continue
    +		}
    +		if _, still := current[key.issueType]; still {
    +			continue
    +		}
    +		r.dropPod(ctx, key, state, pod.Name)
    +	}
    +
    +	// Register the pod on every issue it currently exhibits.
    +	for issueType := range current {
    +		key := componentIssueKey{namespace: pod.Namespace, component: component, issueType: issueType}
    +		r.addPod(ctx, key, pod.Name)
    +	}
    +}
    +
    +// addPod records that a pod exhibits a component issue, emitting Emit if this is
    +// the first affected pod (the issue transitioning to active). Caller holds mu.
    +func (r *ComponentHealthReconciler) addPod(ctx context.Context, key componentIssueKey, pod string) {
    +	state := r.reported[key]
    +	if state == nil {
    +		state = &componentIssueState{pods: map[string]struct{}{}}
    +		r.reported[key] = state
    +	}
    +	firstPod := len(state.pods) == 0
    +	state.pods[pod] = struct{}{}
    +
    +	if firstPod {
    +		r.emitter.Emit(ctx, r.issueFor(key, state))
    +	}
    +	r.setActiveGauge(key, len(state.pods))
    +}
    +
    +// dropPod removes a pod from a component issue, emitting Resolve and clearing the
    +// state when the last affected pod is gone. Caller holds mu.
    +func (r *ComponentHealthReconciler) dropPod(ctx context.Context, key componentIssueKey, state *componentIssueState, pod string) {
    +	if _, ok := state.pods[pod]; !ok {
    +		return
    +	}
    +	delete(state.pods, pod)
    +	if len(state.pods) == 0 {
    +		r.emitter.Resolve(ctx, r.issueFor(key, state))
    +		r.setActiveGauge(key, 0)
    +		delete(r.reported, key)
    +		return
    +	}
    +	r.setActiveGauge(key, len(state.pods))
    +}
    +
    +// forgetPod removes a pod from every component issue it contributed to (used when
    +// the pod disappears), resolving any issue whose last pod it was.
    +func (r *ComponentHealthReconciler) forgetPod(ctx context.Context, pod types.NamespacedName) {
    +	r.mu.Lock()
    +	defer r.mu.Unlock()
    +
    +	for key, state := range r.reported {
    +		if key.namespace != pod.Namespace {
    +			continue
    +		}
    +		r.dropPod(ctx, key, state, pod.Name)
    +	}
    +}
    +
    +// issueFor builds the component-level issue payload from the current state.
    +func (r *ComponentHealthReconciler) issueFor(key componentIssueKey, state *componentIssueState) componenthealth.ComponentIssue {
    +	pods := make([]string, 0, len(state.pods))
    +	for pod := range state.pods {
    +		pods = append(pods, pod)
    +	}
    +	sort.Strings(pods)
    +	return componenthealth.ComponentIssue{
    +		Component:    key.component,
    +		IssueType:    key.issueType,
    +		Severity:     componenthealth.SeverityForIssueType(key.issueType),
    +		Namespace:    key.namespace,
    +		AffectedPods: pods,
    +	}
    +}
    +
    +func (r *ComponentHealthReconciler) setActiveGauge(key componentIssueKey, affectedPods int) {
    +	metrics.ComponentHealthIssuesActive.WithLabelValues(key.component, key.issueType).Set(float64(affectedPods))

    <sub><sub>!P2 Badge</sub></sub> Aggregate the active gauge across watched namespaces

    When DD_AGENT_WATCH_NAMESPACE contains multiple namespaces, reported tracks each namespace separately but this gauge omits the namespace label and overwrites the shared series with only the last namespace's pod count. For example, resolving the last affected pod in namespace B sets the gauge to zero even if namespace A still has affected pods, so the advertised > 0 active-issue query becomes false; either include the namespace in the labels or calculate the total across all matching namespace states before calling Set.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Sep 21, 2026 13:34 UTC
    Code Review
    pkg/config/config.go:1
    @@ -184,6 +217,21 @@ func CacheOptions(logger logr.Logger, opts WatchOptions) cache.Options {
     					newPod.Status.StartTime = pod.Status.StartTime
     				}
     
    +				// Component health monitoring derives issues from the managed components'
    +				// pod status: container statuses (restart counts, OOMKill/crash reasons,
    +				// waiting reasons like ImagePullBackOff), scheduling conditions, phase, and
    +				// termination context. Retaining these fields is what increases cache memory,
    +				// which is why this is gated behind ComponentHealthEnabled.
    +				if opts.ComponentHealthEnabled {

    <sub><sub>!P2 Badge</sub></sub> Retain full status only for managed component pods

    When component health is combined with UntaintControllerWaitForCSIDriver, the earlier branch deliberately removes the Pod label selector, so this unconditional feature check copies container and init-container statuses for every Pod in all merged Agent/CSI watch namespaces, not just DCA/CLC pods. In a broad or cluster-wide watch this defeats the cache's memory stripping and can substantially increase operator memory or cause OOMs; gate these extra fields on the managed component label while retaining only the readiness fields required by untaint for other Pods.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Sep 21, 2026 13:34 UTC
    Reviewer

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: 846d87b7d4

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

    </details>

    levan-m levan-m commented on code on Sep 28, 2026 15:50 UTC
    Code Review
    internal/controller/componenthealth_controller.go:1
    @@ -0,0 +1,301 @@
    +// Unless explicitly stated otherwise all files in this repository are licensed
    +// under the Apache License Version 2.0.
    +// This product includes software developed at Datadog (https://www.datadoghq.com/).
    +// Copyright 2016-present Datadog, Inc.
    +
    +package controller
    +
    +import (
    +	"context"
    +	"sort"
    +	"sync"
    +
    +	"github.com/go-logr/logr"
    +	corev1 "k8s.io/api/core/v1"
    +	apierrors "k8s.io/apimachinery/pkg/api/errors"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/apimachinery/pkg/types"
    +	ctrl "sigs.k8s.io/controller-runtime"
    +	"sigs.k8s.io/controller-runtime/pkg/builder"
    +	"sigs.k8s.io/controller-runtime/pkg/client"
    +	"sigs.k8s.io/controller-runtime/pkg/predicate"
    +
    +	"github.com/DataDog/datadog-operator/api/datadoghq/common"
    +	"github.com/DataDog/datadog-operator/internal/controller/metrics"
    +	"github.com/DataDog/datadog-operator/pkg/componenthealth"
    +	"github.com/DataDog/datadog-operator/pkg/constants"
    +)
    +
    +const (
    +	componentHealthControllerName = "ComponentHealth"
    +
    +	// defaultRestartThreshold is the cumulative container restart count at or
    +	// above which a component container is flagged as crash-looping even when it
    +	// is not currently backing off.
    +	defaultRestartThreshold = 5
    +)
    +
    +// +kubebuilder:rbac:groups="",resources=pods,verbs=get;list;watch
    +
    +// componentHealthEmitter reports state transitions of component-level issues:
    +// Emit when an issue type first appears on a component (its first affected pod),
    +// Resolve when the last affected pod recovers. The controller only calls these
    +// on transitions, so callers receive edges (appeared/cleared), not the full
    +// state on every reconcile.
    +//
    +// The default implementation logs and increments a Prometheus counter. A backend
    +// implementation that ships issues to the health-platform intake can be added
    +// behind this interface without changing the controller.
    +//
    +// TODO(componentHealth): Emit/Resolve are currently called synchronously while
    +// r.mu is held (see addPod/dropPod), and are transition-based only. That's fine
    +// for the in-process log/metric emitter, but the production backend emitter is
    +// expected to be snapshot-based (periodically walk the active-issue map and POST
    +// the full current state) rather than transition-based, and must not do network
    +// I/O while holding r.mu — that would serialize/block reconciliation of
    +// unrelated pods behind a slow or retrying intake call. Reshape this interface
    +// (e.g. a Snapshot(ctx, []ComponentIssue) called outside the lock on a ticker)
    +// before wiring in a backend emitter.
    +type componentHealthEmitter interface {
    +	Emit(ctx context.Context, issue componenthealth.ComponentIssue)
    +	Resolve(ctx context.Context, issue componenthealth.ComponentIssue)
    +}
    +
    +// componentIssueKey identifies a component-level issue instance.
    +// Detection happens per pod, but this is the granularity at which issues are reported.
    +type componentIssueKey struct {
    +	namespace string
    +	component string
    +	issueType string
    +}
    +
    +// componentIssueState is the live state of one component-level issue: the pods
    +// currently exhibiting it, keyed by pod name. The issue is active while pods
    +// is non-empty.
    +type componentIssueState struct {
    +	pods map[string]struct{}
    +}
    +
    +// ComponentHealthReconciler watches the managed cluster-level component pods
    +// (Datadog Cluster Agent and Cluster Check Runners) and reports Kubernetes
    +// health issues (OOMKills, crash loops, scheduling failures, image-pull
    +// failures) derived from their pod status.
    +//
    +// Detection is per pod, but issues are reported per component: the same issue
    +// type across several pods of a component is one issue instance, so a rolling
    +// restart where the problem hops between pods stays a single active issue rather
    +// than a churn of emit/resolve events.
    +//
    +// It is gated behind the ComponentHealth feature flag and depends on the pod
    +// status being retained in the cache (see pkg/config.CacheOptions).
    +type ComponentHealthReconciler struct {
    +	client           client.Client
    +	log              logr.Logger
    +	restartThreshold int32
    +	emitter          componentHealthEmitter
    +
    +	// mu guards reported. reported holds every currently-active component-level
    +	// issue and the set of pods exhibiting it, so the controller emits only on
    +	// presence transitions (first pod affected / last pod recovered) rather than
    +	// on every reconcile.
    +	mu       sync.Mutex
    +	reported map[componentIssueKey]*componentIssueState
    +}
    +
    +// NewComponentHealthReconciler builds a ComponentHealthReconciler with the
    +// default logging/metric emitter.
    +func NewComponentHealthReconciler(c client.Client, log logr.Logger) *ComponentHealthReconciler {
    +	return &ComponentHealthReconciler{
    +		client:           c,
    +		log:              log,
    +		restartThreshold: defaultRestartThreshold,
    +		emitter:          &logEmitter{log: log},
    +		reported:         map[componentIssueKey]*componentIssueState{},
    +	}
    +}
    +
    +// Reconcile evaluates a single managed component pod and folds its detected
    +// issues into the component-level state, emitting only the resulting transitions.
    +func (r *ComponentHealthReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    +	pod := &corev1.Pod{}
    +	if err := r.client.Get(ctx, req.NamespacedName, pod); err != nil {
    +		if apierrors.IsNotFound(err) {
    +			// Pod is gone: drop it from every component issue it contributed to.
    +			r.forgetPod(ctx, req.NamespacedName)
    +			return ctrl.Result{}, nil
    +		}
    +		return ctrl.Result{}, err
    +	}
    +
    +	// A pod being deleted is treated like a gone pod.
    +	if !pod.DeletionTimestamp.IsZero() {

    this needs to be cached too, PR only caches some of pod.Status fields only.

    levan-m levan-m commented on code on Sep 28, 2026 16:41 UTC
    Code Review
    internal/controller/metrics/componenthealth.go:1
    @@ -0,0 +1,49 @@
    +// Unless explicitly stated otherwise all files in this repository are licensed
    +// under the Apache License Version 2.0.
    +// This product includes software developed at Datadog (https://www.datadoghq.com/).
    +// Copyright 2016-present Datadog, Inc.
    +
    +package metrics
    +
    +import (
    +	"github.com/prometheus/client_golang/prometheus"
    +	"sigs.k8s.io/controller-runtime/pkg/metrics"
    +)
    +
    +var (
    +	// ComponentHealthIssuesDetected counts component-level health issues as they
    +	// first appear on the managed cluster-level components (cluster-agent,
    +	// cluster-checks-runner), labeled by component and issue type. It increments
    +	// once per component-level issue instance (an issue type going from absent to
    +	// present on a component) so it measures the rate
    +	// at which new problems surface.
    +	ComponentHealthIssuesDetected = prometheus.NewCounterVec(
    +		prometheus.CounterOpts{
    +			Subsystem: datadogAgentSubsystem,

    nit, should this use dedicated prefix?
    componenthealth_issues_detected_total or agenthealth_issues_detected_total instead of
    datadogagent_component_health_issues_detected_total.

    in the app it will get datadog.operator prefix right?

    levan-m levan-m approved these changes on Sep 28, 2026 16:41 UTC
    Approved Reviewer

    Approved these changes.

    adel121 adel121 commented on code on Sep 29, 2026 14:23 UTC
    Code Review
    internal/controller/componenthealth_controller.go:1
    @@ -0,0 +1,301 @@
    +// Unless explicitly stated otherwise all files in this repository are licensed
    +// under the Apache License Version 2.0.
    +// This product includes software developed at Datadog (https://www.datadoghq.com/).
    +// Copyright 2016-present Datadog, Inc.
    +
    +package controller
    +
    +import (
    +	"context"
    +	"sort"
    +	"sync"
    +
    +	"github.com/go-logr/logr"
    +	corev1 "k8s.io/api/core/v1"
    +	apierrors "k8s.io/apimachinery/pkg/api/errors"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/apimachinery/pkg/types"
    +	ctrl "sigs.k8s.io/controller-runtime"
    +	"sigs.k8s.io/controller-runtime/pkg/builder"
    +	"sigs.k8s.io/controller-runtime/pkg/client"
    +	"sigs.k8s.io/controller-runtime/pkg/predicate"
    +
    +	"github.com/DataDog/datadog-operator/api/datadoghq/common"
    +	"github.com/DataDog/datadog-operator/internal/controller/metrics"
    +	"github.com/DataDog/datadog-operator/pkg/componenthealth"
    +	"github.com/DataDog/datadog-operator/pkg/constants"
    +)
    +
    +const (
    +	componentHealthControllerName = "ComponentHealth"
    +
    +	// defaultRestartThreshold is the cumulative container restart count at or
    +	// above which a component container is flagged as crash-looping even when it
    +	// is not currently backing off.
    +	defaultRestartThreshold = 5
    +)
    +
    +// +kubebuilder:rbac:groups="",resources=pods,verbs=get;list;watch
    +
    +// componentHealthEmitter reports state transitions of component-level issues:
    +// Emit when an issue type first appears on a component (its first affected pod),
    +// Resolve when the last affected pod recovers. The controller only calls these
    +// on transitions, so callers receive edges (appeared/cleared), not the full
    +// state on every reconcile.
    +//
    +// The default implementation logs and increments a Prometheus counter. A backend
    +// implementation that ships issues to the health-platform intake can be added
    +// behind this interface without changing the controller.
    +//
    +// TODO(componentHealth): Emit/Resolve are currently called synchronously while
    +// r.mu is held (see addPod/dropPod), and are transition-based only. That's fine
    +// for the in-process log/metric emitter, but the production backend emitter is
    +// expected to be snapshot-based (periodically walk the active-issue map and POST
    +// the full current state) rather than transition-based, and must not do network
    +// I/O while holding r.mu — that would serialize/block reconciliation of
    +// unrelated pods behind a slow or retrying intake call. Reshape this interface
    +// (e.g. a Snapshot(ctx, []ComponentIssue) called outside the lock on a ticker)
    +// before wiring in a backend emitter.
    +type componentHealthEmitter interface {
    +	Emit(ctx context.Context, issue componenthealth.ComponentIssue)
    +	Resolve(ctx context.Context, issue componenthealth.ComponentIssue)
    +}
    +
    +// componentIssueKey identifies a component-level issue instance.
    +// Detection happens per pod, but this is the granularity at which issues are reported.
    +type componentIssueKey struct {
    +	namespace string
    +	component string
    +	issueType string
    +}
    +
    +// componentIssueState is the live state of one component-level issue: the pods
    +// currently exhibiting it, keyed by pod name. The issue is active while pods
    +// is non-empty.
    +type componentIssueState struct {
    +	pods map[string]struct{}
    +}
    +
    +// ComponentHealthReconciler watches the managed cluster-level component pods
    +// (Datadog Cluster Agent and Cluster Check Runners) and reports Kubernetes
    +// health issues (OOMKills, crash loops, scheduling failures, image-pull
    +// failures) derived from their pod status.
    +//
    +// Detection is per pod, but issues are reported per component: the same issue
    +// type across several pods of a component is one issue instance, so a rolling
    +// restart where the problem hops between pods stays a single active issue rather
    +// than a churn of emit/resolve events.
    +//
    +// It is gated behind the ComponentHealth feature flag and depends on the pod
    +// status being retained in the cache (see pkg/config.CacheOptions).
    +type ComponentHealthReconciler struct {
    +	client           client.Client
    +	log              logr.Logger
    +	restartThreshold int32
    +	emitter          componentHealthEmitter
    +
    +	// mu guards reported. reported holds every currently-active component-level
    +	// issue and the set of pods exhibiting it, so the controller emits only on
    +	// presence transitions (first pod affected / last pod recovered) rather than
    +	// on every reconcile.
    +	mu       sync.Mutex
    +	reported map[componentIssueKey]*componentIssueState
    +}
    +
    +// NewComponentHealthReconciler builds a ComponentHealthReconciler with the
    +// default logging/metric emitter.
    +func NewComponentHealthReconciler(c client.Client, log logr.Logger) *ComponentHealthReconciler {
    +	return &ComponentHealthReconciler{
    +		client:           c,
    +		log:              log,
    +		restartThreshold: defaultRestartThreshold,
    +		emitter:          &logEmitter{log: log},
    +		reported:         map[componentIssueKey]*componentIssueState{},
    +	}
    +}
    +
    +// Reconcile evaluates a single managed component pod and folds its detected
    +// issues into the component-level state, emitting only the resulting transitions.
    +func (r *ComponentHealthReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    +	pod := &corev1.Pod{}
    +	if err := r.client.Get(ctx, req.NamespacedName, pod); err != nil {
    +		if apierrors.IsNotFound(err) {
    +			// Pod is gone: drop it from every component issue it contributed to.
    +			r.forgetPod(ctx, req.NamespacedName)
    +			return ctrl.Result{}, nil
    +		}
    +		return ctrl.Result{}, err
    +	}
    +
    +	// A pod being deleted is treated like a gone pod.
    +	if !pod.DeletionTimestamp.IsZero() {

    Good catch. Updating the caching to include DeletionTimestamp

    levan-m levan-m approved these changes on Sep 29, 2026 16:40 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    adel121 adel121
    Labels
    risk: low confidence: 83.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 56.2% (MEDIUM) · Higher = larger blast radius
    56.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 83.9% · Lower = rushed or shallow review
    83.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 9.1% · Safe to merge
    9.1%