Skip to content

OCPBUGS-86229: apiserver: cache etcd storage monitors to avoid recreating clients on each metrics scrape#2674

Open
tchap wants to merge 1 commit into
openshift:masterfrom
tchap:grpc-logs-OCPBUGS-86229
Open

OCPBUGS-86229: apiserver: cache etcd storage monitors to avoid recreating clients on each metrics scrape#2674
tchap wants to merge 1 commit into
openshift:masterfrom
tchap:grpc-logs-OCPBUGS-86229

Conversation

@tchap
Copy link
Copy Markdown

@tchap tchap commented May 28, 2026

What type of PR is this?

/kind cleanup

What this PR does / why we need it:

The apiserver was creating new etcd storage monitor clients on every Prometheus metrics scrape cycle and immediately closing them afterward. This caused repeated gRPC connection churn against etcd, as each scrape round-tripped through client creation and teardown.

There are multiple client cases linked to this, either complaining about warnings or about memory consumption, so we decided on RIT to cherry-pick this and not wait for 1.37 to be incorporated.

Which issue(s) this PR is related to:

n/a

Special notes for your reviewer:

n/a

Does this PR introduce a user-facing change?

NONE

Additional documentation e.g., KEPs (Kubernetes Enhancement Proposals), usage docs, etc.:

n/a

Summary by CodeRabbit

  • Refactor

    • Enhanced etcd storage monitor management with thread-safe caching and improved lifecycle management to prevent resource leaks.
  • Tests

    • Added comprehensive tests for monitor caching, concurrent access, and proper resource cleanup.

…reating clients on each metrics scrape

Signed-off-by: xigang <wangxigang2014@gmail.com>
@openshift-ci openshift-ci Bot added the kind/cleanup Categorizes issue or PR as related to cleaning up code, process, or technical debt. label May 28, 2026
@openshift-ci-robot openshift-ci-robot added backports/validated-commits Indicates that all commits come to merged upstream PRs. jira/severity-moderate Referenced Jira bug's severity is moderate for the branch this PR is targeting. jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. jira/invalid-bug Indicates that a referenced Jira bug is invalid for the branch this PR is targeting. labels May 28, 2026
@openshift-ci-robot
Copy link
Copy Markdown

@tchap: This pull request references Jira Issue OCPBUGS-86229, which is invalid:

  • expected the bug to target the "5.0.0" version, but no target version was set

Comment /jira refresh to re-evaluate validity if changes to the Jira bug are made, or edit the title of this pull request to link to a different bug.

The bug has been updated to refer to the pull request using the external bug tracker.

Details

In response to this:

What type of PR is this?

/kind cleanup

What this PR does / why we need it:

The apiserver was creating new etcd storage monitor clients on every Prometheus metrics scrape cycle and immediately closing them afterward. This caused repeated gRPC connection churn against etcd, as each scrape round-tripped through client creation and teardown.

There are multiple client cases linked to this, either complaining about warnings or about memory consumption, so we decided on RIT to cherry-pick this and not wait for 1.37 to be incorporated.

Which issue(s) this PR is related to:

n/a

Special notes for your reviewer:

n/a

Does this PR introduce a user-facing change?

NONE

Additional documentation e.g., KEPs (Kubernetes Enhancement Proposals), usage docs, etc.:

n/a

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@openshift-ci-robot
Copy link
Copy Markdown

@tchap: the contents of this pull request could be automatically validated.

The following commits are valid:

Comment /validate-backports to re-evaluate validity of the upstream PRs, for example when they are merged upstream.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 28, 2026

Walkthrough

This PR refactors etcd storage monitor lifecycle from per-call creation to a cached, thread-safe initialization. A new monitorCache lazily creates monitors once, returns cached instances on subsequent calls, and manages cleanup via a background goroutine. Monitor closure is removed from metrics collection since the cache now owns the monitors' lifecycle.

Changes

Monitor cache implementation and lifecycle

Layer / File(s) Summary
Monitor cache implementation and server integration
staging/src/k8s.io/apiserver/pkg/server/options/etcd.go
Adds sync import. Replaces per-call monitor creation closure with monitorCache struct: mutex-protected cache field, fast-path read-lock retrieval, write-locked lazy initialization that creates monitors from storage factory and cleans up partial failures, plus async cleanup goroutine that closes monitors when stopCh closes. Integrates cache construction and getter registration into ApplyWithStorageFactoryTo.
Monitor cache test suite
staging/src/k8s.io/apiserver/pkg/server/options/etcd_test.go
Adds imports for context, sync/atomic, and etcd3 metrics. Implements fakeMonitor helper to count Close() calls and satisfy metrics.Monitor interface. Adds TestMonitorCache that validates monitor reuse across sequential get() calls, error handling and cleanup after cache closure, and concurrent get() call safety with single initialization.
Metrics collection cleanup
staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go
Removes explicit m.Close() call from monitorCollector.CollectWithStability monitor loop, relying on cache-owned lifecycle management.

Sequence Diagram

sequenceDiagram
    participant Server as Server Init
    participant Cache as monitorCache
    participant Factory as StorageFactory
    participant Caller as Metric Caller
    participant Cleanup as Cleanup Goroutine
    
    Server->>Cache: newMonitorCache()
    Server->>Cache: register get as StorageMonitorGetter
    Caller->>Cache: get() [first call]
    Cache->>Cache: acquire WLock
    Cache->>Factory: createMonitor loop
    Factory-->>Cache: [Monitor1, Monitor2, ...]
    Cache->>Cache: store in cache
    Cache-->>Caller: [Monitor1, Monitor2, ...]
    
    Caller->>Cache: get() [second call]
    Cache->>Cache: acquire RLock
    Cache-->>Caller: [Monitor1, Monitor2, ...] (cached)
    
    Server->>Cleanup: stopCh closed
    Cleanup->>Cache: close all monitors
    Cleanup->>Cache: clear cache
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 13 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Test Structure And Quality ❓ Inconclusive The custom check targets Ginkgo test code, but the PR uses Go's standard testing package (func TestMonitorCache(t *testing.T)) with t.Run subtests, not Ginkgo Describe/It blocks. Clarify if the check applies to standard Go tests or only Ginkgo BDD tests. If checking standard Go tests, the test quality is good with proper cleanup (t.Cleanup), helpers (t.Helper), meaningful assertions, and single-responsibility cases.
✅ Passed checks (13 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: caching etcd storage monitors to avoid client recreation on each metrics scrape, which directly addresses the core problem of unnecessary gRPC connection churn.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Stable And Deterministic Test Names ✅ Passed PR does not use Ginkgo testing framework; it uses standard Go testing with t.Run(). TestMonitorCache test names are stable, deterministic, and contain no dynamic information.
Microshift Test Compatibility ✅ Passed PR adds only standard Go unit tests (TestMonitorCache), not Ginkgo e2e tests. MicroShift compatibility check applies only to Ginkgo e2e tests, so it is not applicable here.
Single Node Openshift (Sno) Test Compatibility ✅ Passed No Ginkgo e2e tests added. The PR adds only standard Go unit tests (TestMonitorCache) in staging/src/k8s.io/apiserver, not Ginkgo e2e tests; check is not applicable.
Topology-Aware Scheduling Compatibility ✅ Passed PR modifies only internal apiserver Go library code (etcd monitor caching), not deployment manifests, operators, or controllers. Topology-aware check not applicable.
Ote Binary Stdout Contract ✅ Passed No process-level stdout writes detected. Code changes are in regular functions/methods/tests only, with no klog/fmt.Print calls to stdout in process-level code.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed No Ginkgo e2e tests added. TestMonitorCache is a standard Go unit test using the testing package, not Ginkgo, located in the apiserver package code directory.
No-Weak-Crypto ✅ Passed No weak crypto algorithms, custom crypto, or non-constant-time secret comparisons found. PR only modifies etcd monitor caching using standard sync primitives.
Container-Privileges ✅ Passed PR contains only Go source code files, no Kubernetes manifests or container configs with privilege settings. Check is not applicable.
No-Sensitive-Data-In-Logs ✅ Passed No logging statements expose sensitive data like passwords, tokens, API keys, or PII. Only generic operational messages and safe identifiers are logged.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@openshift-ci openshift-ci Bot requested review from jerpeter1 and p0lyn0mial May 28, 2026 14:03
@openshift-ci openshift-ci Bot added the vendor-update Touching vendor dir or related files label May 28, 2026
@openshift-ci
Copy link
Copy Markdown

openshift-ci Bot commented May 28, 2026

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: tchap
Once this PR has been reviewed and has the lgtm label, please assign jerpeter1 for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@openshift-ci-robot
Copy link
Copy Markdown

@tchap: This pull request references Jira Issue OCPBUGS-86229, which is invalid:

  • expected the bug to target the "5.0.0" version, but no target version was set

Comment /jira refresh to re-evaluate validity if changes to the Jira bug are made, or edit the title of this pull request to link to a different bug.

Details

In response to this:

What type of PR is this?

/kind cleanup

What this PR does / why we need it:

The apiserver was creating new etcd storage monitor clients on every Prometheus metrics scrape cycle and immediately closing them afterward. This caused repeated gRPC connection churn against etcd, as each scrape round-tripped through client creation and teardown.

There are multiple client cases linked to this, either complaining about warnings or about memory consumption, so we decided on RIT to cherry-pick this and not wait for 1.37 to be incorporated.

Which issue(s) this PR is related to:

n/a

Special notes for your reviewer:

n/a

Does this PR introduce a user-facing change?

NONE

Additional documentation e.g., KEPs (Kubernetes Enhancement Proposals), usage docs, etc.:

n/a

Summary by CodeRabbit

  • Refactor

  • Enhanced etcd storage monitor management with thread-safe caching and improved lifecycle management to prevent resource leaks.

  • Tests

  • Added comprehensive tests for monitor caching, concurrent access, and proper resource cleanup.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@tchap
Copy link
Copy Markdown
Author

tchap commented May 28, 2026

/jira refresh

@openshift-ci-robot openshift-ci-robot added jira/valid-bug Indicates that a referenced Jira bug is valid for the branch this PR is targeting. and removed jira/invalid-bug Indicates that a referenced Jira bug is invalid for the branch this PR is targeting. labels May 28, 2026
@openshift-ci-robot
Copy link
Copy Markdown

@tchap: This pull request references Jira Issue OCPBUGS-86229, which is valid. The bug has been moved to the POST state.

3 validation(s) were run on this bug
  • bug is open, matching expected state (open)
  • bug target version (5.0.0) matches configured target version for branch (5.0.0)
  • bug is in the state New, which is one of the valid states (NEW, ASSIGNED, POST)
Details

In response to this:

/jira refresh

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

Copy link
Copy Markdown

@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

🧹 Nitpick comments (1)
staging/src/k8s.io/apiserver/pkg/server/options/etcd_test.go (1)

500-645: ⚡ Quick win

Consider adding test coverage for empty configs and partial initialization failure.

The test suite covers the happy path well, but consider adding tests for:

  1. factory.Configs() returning an empty slice (this would catch the goroutine leak bug in initialize())
  2. createMonitor returning an error mid-iteration to verify partial initialization cleanup
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@staging/src/k8s.io/apiserver/pkg/server/options/etcd_test.go` around lines
500 - 645, Add two new subtests inside TestMonitorCache: one to exercise an
empty factory.Configs() by using a SimpleStorageFactory variant that returns an
empty slice and asserting cache.get() behaves/returns an empty monitor list (and
that no goroutines leak by still allowing stopCh cleanup via newTestCache), and
a second that simulates createMonitor failing mid-iteration by using
setCreateMonitor so the first call returns a valid fakeMonitor and the second
returns an error; assert that the error propagates from cache.get(), the first
monitor's closeCalls increased (cleanup happened), and cache.monitors does not
contain partially initialized entries. Use the existing helpers newTestCache,
setCreateMonitor, fakeMonitor, createMonitor, cache.get, cache.close, and
monitor.closeCalls to locate and implement these tests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@staging/src/k8s.io/apiserver/pkg/server/options/etcd.go`:
- Around line 304-316: The code can leave c.monitors nil when
c.factory.Configs() returns an empty slice, causing get() to repeatedly call
initialize() and leak goroutines; to fix it, ensure monitors is a non-nil empty
slice before assigning to c.monitors (e.g., initialize monitors :=
make([]metrics.Monitor, 0, len(c.factory.Configs())) or ensure c.monitors =
[]metrics.Monitor{} when no monitors were created), so checks like c.monitors !=
nil behave correctly; update the block using createMonitor, c.factory.Configs(),
and the assignment to c.monitors in initialize()/get() accordingly.

---

Nitpick comments:
In `@staging/src/k8s.io/apiserver/pkg/server/options/etcd_test.go`:
- Around line 500-645: Add two new subtests inside TestMonitorCache: one to
exercise an empty factory.Configs() by using a SimpleStorageFactory variant that
returns an empty slice and asserting cache.get() behaves/returns an empty
monitor list (and that no goroutines leak by still allowing stopCh cleanup via
newTestCache), and a second that simulates createMonitor failing mid-iteration
by using setCreateMonitor so the first call returns a valid fakeMonitor and the
second returns an error; assert that the error propagates from cache.get(), the
first monitor's closeCalls increased (cleanup happened), and cache.monitors does
not contain partially initialized entries. Use the existing helpers
newTestCache, setCreateMonitor, fakeMonitor, createMonitor, cache.get,
cache.close, and monitor.closeCalls to locate and implement these tests.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: openshift/coderabbit/.coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: f53702a7-374f-401a-ba1f-a090c1eb2529

📥 Commits

Reviewing files that changed from the base of the PR and between 99b75aa and 8eef07f.

📒 Files selected for processing (3)
  • staging/src/k8s.io/apiserver/pkg/server/options/etcd.go
  • staging/src/k8s.io/apiserver/pkg/server/options/etcd_test.go
  • staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go
💤 Files with no reviewable changes (1)
  • staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go

Comment thread staging/src/k8s.io/apiserver/pkg/server/options/etcd.go
@tchap
Copy link
Copy Markdown
Author

tchap commented May 28, 2026

I am actually going to fix the upstream issue found by CR and get back to this.

/hold

@openshift-ci openshift-ci Bot added the do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. label May 28, 2026
@tchap
Copy link
Copy Markdown
Author

tchap commented May 28, 2026

I created kubernetes#139358 . It's actually not critical as the issue is only theoretical right now since Configs() always return at least one item currently, so if this gets merged, it will be included in the next release no prob.

/unhold

@openshift-ci openshift-ci Bot removed the do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. label May 28, 2026
@tchap
Copy link
Copy Markdown
Author

tchap commented May 28, 2026

/retest

@openshift-ci
Copy link
Copy Markdown

openshift-ci Bot commented May 28, 2026

@tchap: The following test failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
ci/prow/e2e-aws-ovn-crun 8eef07f link true /test e2e-aws-ovn-crun

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

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

Labels

backports/validated-commits Indicates that all commits come to merged upstream PRs. jira/severity-moderate Referenced Jira bug's severity is moderate for the branch this PR is targeting. jira/valid-bug Indicates that a referenced Jira bug is valid for the branch this PR is targeting. jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. kind/cleanup Categorizes issue or PR as related to cleaning up code, process, or technical debt. vendor-update Touching vendor dir or related files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants