You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by ha...@apache.org on 2026/07/02 12:23:32 UTC
(skywalking-banyandb) branch main updated: Add FODC memory-pressure pprof capture (#1200)
This is an automated email from the ASF dual-hosted git repository.
hanahmily pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/skywalking-banyandb.git
The following commit(s) were added to refs/heads/main by this push:
new 38704419f Add FODC memory-pressure pprof capture (#1200)
38704419f is described below
commit 38704419f786f825cf7cfe8b12f306de1c71a906
Author: mrproliu <74...@qq.com>
AuthorDate: Thu Jul 2 20:23:27 2026 +0800
Add FODC memory-pressure pprof capture (#1200)
---
.github/workflows/test-fodc-e2e.yml | 49 ++-
CHANGES.md | 1 +
api/proto/banyandb/fodc/v1/rpc.proto | 75 ++++
banyand/protector/protector.go | 53 ++-
banyand/protector/protector_test.go | 107 ++++++
docs/api-reference.md | 155 ++++++++
fodc/agent/internal/cmd/root.go | 64 +++-
fodc/agent/internal/cmd/root_test.go | 39 ++
fodc/agent/internal/flightrecorder/datasource.go | 19 +
.../internal/flightrecorder/flightrecorder.go | 45 +++
.../internal/flightrecorder/flightrecorder_test.go | 52 +++
fodc/agent/internal/pressureprofiler/fetch.go | 59 +++
fodc/agent/internal/pressureprofiler/profiler.go | 239 ++++++++++++
.../internal/pressureprofiler/profiler_test.go | 206 +++++++++++
fodc/agent/internal/pressureprofiler/storage.go | 258 +++++++++++++
.../internal/pressureprofiler/storage_test.go | 128 +++++++
fodc/agent/internal/proxy/client.go | 263 +++++++++++++
.../internal/proxy/client_blocking_send_test.go | 4 +-
fodc/agent/internal/proxy/client_test.go | 99 ++---
fodc/agent/internal/watchdog/watchdog.go | 18 +
fodc/agent/testhelper/flightrecorder.go | 3 +
fodc/agent/testhelper/pressureprofiler.go | 110 ++++++
fodc/internal/pprofcapture/pprofcapture.go | 44 +++
fodc/proxy/cmd/proxy/main.go | 9 +-
fodc/proxy/internal/api/server.go | 136 +++++++
fodc/proxy/internal/api/server_test.go | 18 +-
fodc/proxy/internal/grpc/pressure_list_test.go | 130 +++++++
fodc/proxy/internal/grpc/server_test.go | 8 +-
fodc/proxy/internal/grpc/service.go | 406 ++++++++++++++++++++-
fodc/proxy/internal/grpc/service_test.go | 4 +-
.../integration/agent_reconnection_test.go | 4 +-
.../agent_registration_metrics_flow_test.go | 4 +-
.../cluster_topology_integration_test.go | 4 +-
fodc/proxy/internal/integration/diagnostic_test.go | 4 +-
.../internal/integration/failure_scenarios_test.go | 6 +-
.../integration/full_proxy_workflow_test.go | 4 +-
.../high_availability_scalability_test.go | 4 +-
.../integration/lifecycle_integration_test.go | 4 +-
.../integration/metrics_time_window_test.go | 4 +-
.../integration/multiple_agents_roles_test.go | 4 +-
.../internal/integration/pressure_profile_test.go | 246 +++++++++++++
.../integration/prometheus_integration_test.go | 4 +-
fodc/proxy/internal/pressure/aggregator.go | 269 ++++++++++++++
fodc/proxy/internal/pressure/aggregator_test.go | 99 +++++
.../cases/fodc-pressure/banyandb-cluster.yaml | 98 +++++
test/e2e-v2/cases/fodc-pressure/check-pressure.sh | 123 +++++++
test/e2e-v2/cases/fodc-pressure/e2e.yaml | 68 ++++
.../fodc-pressure/expected/pressure-status.yml | 16 +
48 files changed, 3658 insertions(+), 108 deletions(-)
diff --git a/.github/workflows/test-fodc-e2e.yml b/.github/workflows/test-fodc-e2e.yml
index d7b8d9325..8658c3c7d 100644
--- a/.github/workflows/test-fodc-e2e.yml
+++ b/.github/workflows/test-fodc-e2e.yml
@@ -142,5 +142,52 @@ jobs:
if [ -f /tmp/write-load.log ]; then
echo "::group::write-load output"
cat /tmp/write-load.log
- echo "::endgroup::"
+ echo "::endgroup::"
fi
+
+ # Second FODC e2e scenario: memory-pressure pprof capture against a real BanyanDB
+ # cluster + fodc-agent + fodc-proxy. Kept as a separate job (not a matrix leg with
+ # fodc-kind) because the two scenarios use different harnesses and, unlike the
+ # eBPF/KTM check above, this one is a hard gate (no continue-on-error). It runs via
+ # the skywalking-infra-e2e harness (test/e2e-v2/cases/fodc-pressure/e2e.yaml).
+ fodc-pressure-kind:
+ if: ${{ inputs.should_run }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 60
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+ with:
+ fetch-tags: true
+
+ - name: Load env
+ run: grep -v '^#' test/e2e-v2/script/env >> "$GITHUB_ENV"
+
+ - name: Setup build environment
+ uses: ./.github/actions/setup-build-env
+ with:
+ download-artifacts: 'true'
+ setup-docker: 'true'
+
+ - name: Build BanyanDB image
+ run: |
+ make -C banyand release
+ make -C banyand docker
+
+ - name: Build FODC agent image
+ run: |
+ make -C fodc/agent release
+ make -C fodc/agent docker
+
+ - name: Build FODC proxy image
+ run: |
+ make -C fodc/proxy release
+ make -C fodc/proxy docker
+
+ - name: List built images
+ run: docker image ls | grep -E 'skywalking-banyandb' || true
+
+ - name: Run FODC memory-pressure pprof e2e
+ uses: apache/skywalking-infra-e2e@ef073adb8b9e148e4eaf3f905fa4e238ee5cc7d6
+ with:
+ e2e-file: $GITHUB_WORKSPACE/test/e2e-v2/cases/fodc-pressure/e2e.yaml
diff --git a/CHANGES.md b/CHANGES.md
index fb123ea32..60bb76767 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -73,6 +73,7 @@ Release Notes.
- Cut the lifecycle external series-index deduplicator's memory from ~1.8 GB to near-zero per segment by bumping bluge to a memory-efficient implementation: duplicates are now resolved via `_id` term-dictionary point lookups (`Dictionary.Contains`) instead of decompressing and retaining every segment's stored fields, removing the dominant heap source during external-segment introduction. No public API change and identical dedup semantics (verified by a differential test); this is the roo [...]
- Add the storage-node in-merge trace retention filter (`PIPELINE_EVENT_MERGE`): a per-group sampler chain evaluates traces at merge time and drops non-retained traces from both the core part and the coupled sidx (`sidx.Merge` gains a keep predicate; a nil predicate restores the wholesale merge). Chain execution fails open on panic/error/length-mismatch/timeout, with a consecutive-timeout circuit breaker. Samplers are native Go plugins (`.so`) loaded at startup from `--trace-pipeline-con [...]
- Register/update/remove in-merge trace retention samplers at runtime without restarting the data node, replacing the static `--trace-pipeline-config` boot loader (now removed). The sampler pipeline config is carried on `common.v1.Group` (new optional `pipeline` field, with `TracePipelineConfig`/`SamplerPlugin` relocated from `pipeline/v1` into the leaf `common/v1` to avoid a `common`→`pipeline` import cycle) and delivered through the existing `KindGroup` schema watch; the data node rebu [...]
+- Add FODC memory-pressure pprof capture: agent grabs heap/goroutine profiles when RSS nears the cgroup limit, served via the proxy.
### Bug Fixes
diff --git a/api/proto/banyandb/fodc/v1/rpc.proto b/api/proto/banyandb/fodc/v1/rpc.proto
index 825f5fddc..a7a7af7ec 100644
--- a/api/proto/banyandb/fodc/v1/rpc.proto
+++ b/api/proto/banyandb/fodc/v1/rpc.proto
@@ -43,6 +43,12 @@ service FODCService {
// Bi-directional stream for crash diagnostics
// Agent sends StreamCrashDiagnosticsRequest (panic collections), Proxy sends StreamCrashDiagnosticsResponse (requests)
rpc StreamCrashDiagnostics(stream StreamCrashDiagnosticsRequest) returns (stream StreamCrashDiagnosticsResponse);
+
+ // Bi-directional stream for memory-pressure pprof profiles.
+ // Proxy drives via StreamPressureProfilesResponse (list metadata, or fetch one
+ // profile's bytes); agent replies with StreamPressureProfilesRequest (metadata
+ // records, or binary chunks).
+ rpc StreamPressureProfiles(stream StreamPressureProfilesRequest) returns (stream StreamPressureProfilesResponse);
}
message RegisterAgentRequest {
@@ -177,6 +183,75 @@ message StreamCrashDiagnosticsResponse {
bool request_diagnostics = 1;
}
+// One pprof profile inside a capture event (metadata only, no bytes).
+message PressureProfileInfo {
+ string type = 1; // "heap" | "goroutine"
+ string filename = 2; // base name, e.g. "heap.pprof"
+ string filepath = 3; // absolute path on the agent's disk, e.g. /tmp/pressure-profiles/20260627T101112.000000000Z/heap.pprof
+ string format = 4; // "pprof" (gzip-compressed protobuf)
+ int64 size_bytes = 5; // on-disk size
+}
+
+// Metadata for one capture event (no bytes). pod/role are NOT carried here:
+// the proxy enriches them from the registered AgentIdentity, same as crash.
+message PressureProfileRecord {
+ string profile_id = 1; // = event directory name (UTC ns timestamp)
+ google.protobuf.Timestamp captured_at = 2;
+ string source_endpoint = 3; // pprof endpoint pulled, e.g. http://localhost:6060
+ uint64 rss_bytes = 4; // RSS at trigger (process_resident_memory_bytes); top-N sort key
+ uint64 cgroup_limit_bytes = 5; // cgroup memory.max
+ uint32 trigger_percent = 6; // configured threshold percent (e.g. 75)
+ uint64 threshold_bytes = 7; // cgroup_limit_bytes * trigger_percent / 100
+ repeated PressureProfileInfo profiles = 8;
+}
+
+// One slice of a profile's bytes during download.
+message PressureProfileChunk {
+ string request_id = 1; // echoes FetchPressureProfile.request_id -- correlates this chunk stream to its fetch
+ string profile_id = 2;
+ string type = 3; // "heap" | "goroutine"
+ bytes data = 4; // a bounded slice (e.g. <= 1MB)
+ bool last = 5; // true on the final chunk
+ string error = 6; // non-empty if the file cannot be served (e.g. evicted / not found)
+}
+
+// Agent -> Proxy: either a metadata record (answer to list_profiles) or a byte
+// chunk (answer to fetch_profile).
+message StreamPressureProfilesRequest {
+ oneof payload {
+ PressureProfileRecord record = 1;
+ ListComplete list_complete = 2;
+ PressureProfileChunk chunk = 3;
+ }
+}
+
+// Agent -> Proxy: sent once after all records for a ListProfiles request have been
+// streamed (including the zero-record case), so the proxy knows the agent is done
+// without waiting out a fixed window.
+message ListComplete {
+ string request_id = 1; // echoes ListProfiles.request_id
+}
+
+message FetchPressureProfile {
+ string request_id = 1; // proxy-generated per fetch; echoed back in every PressureProfileChunk to correlate
+ string profile_id = 2;
+ string type = 3; // "heap" | "goroutine"
+ string filepath = 4; // the absolute path the agent reported in PressureProfileInfo.filepath; agent opens it AFTER validating it is within --pressure-profiler-dir
+}
+
+// Proxy -> Agent: either "stream all your metadata" or "stream one profile's bytes".
+message StreamPressureProfilesResponse {
+ oneof command {
+ ListProfiles list_profiles = 1;
+ FetchPressureProfile fetch_profile = 2;
+ }
+}
+
+// Proxy -> Agent: stream all capture-event metadata for this request id.
+message ListProfiles {
+ string request_id = 1; // proxy-generated per list; echoed back in ListComplete to correlate
+}
+
// GroupLifecycleService provides group lifecycle information from liaison nodes.
// Registered on the internal gRPC server so FODC agent can access it.
service GroupLifecycleService {
diff --git a/banyand/protector/protector.go b/banyand/protector/protector.go
index 6cf724680..6ad998406 100644
--- a/banyand/protector/protector.go
+++ b/banyand/protector/protector.go
@@ -79,30 +79,28 @@ var _ Memory = (*memory)(nil)
// Memory is a protector that stops the query services when the memory usage exceeds the limit.
type memory struct {
- omr observability.MetricsRegistry
- limitGauge meter.Gauge
- usageGauge meter.Gauge
- l *logger.Logger
- closed chan struct{}
- blockedChan chan struct{}
- allowedPercent int
- allowedBytes run.Bytes
- limit atomic.Uint64
- usage uint64
+ omr observability.MetricsRegistry
+ limitGauge meter.Gauge
+ usageGauge meter.Gauge
+ cgroupLimitGauge meter.Gauge
+ overLimitCounter meter.Counter
+ l *logger.Logger
+ closed chan struct{}
+ blockedChan chan struct{}
+ allowedPercent int
+ allowedBytes run.Bytes
+ limit atomic.Uint64
+ usage uint64
}
// NewMemory creates a new Memory protector.
func NewMemory(omr observability.MetricsRegistry) Memory {
queueSize := cgroups.CPUs()
- factory := omr.With(scope)
-
return &memory{
omr: omr,
blockedChan: make(chan struct{}, queueSize),
closed: make(chan struct{}),
l: logger.GetLogger("memory-protector"),
- limitGauge: factory.NewGauge("limit"),
- usageGauge: factory.NewGauge("usage"),
}
}
@@ -227,9 +225,31 @@ func (m *memory) Validate() error {
return nil
}
+// cgroupLimitGaugeValue maps a raw cgroup memory limit to the gauge value: an
+// unlimited ("max" => -1), unreadable, or implausibly large limit reports 0,
+// which downstream consumers treat as "no container memory limit".
+func cgroupLimitGaugeValue(limit int64, err error) float64 {
+ if err != nil || !cgroupLimitValid(limit) {
+ return 0
+ }
+ return float64(limit)
+}
+
+// cgroupLimitValid reports whether a raw cgroup memory limit is a real bound, i.e. not
+// unlimited ("max" => -1), zero, or implausibly large (the protector's own sanity ceiling).
+func cgroupLimitValid(limit int64) bool {
+ return limit > 0 && limit <= 1e18
+}
+
// PreRun initializes the protector.
func (m *memory) PreRun(context.Context) error {
m.l = logger.GetLogger(m.Name())
+ factory := m.omr.With(scope)
+ m.limitGauge = factory.NewGauge("limit")
+ m.usageGauge = factory.NewGauge("usage")
+ m.overLimitCounter = factory.NewCounter("over_limit_total")
+ m.cgroupLimitGauge = factory.NewGauge("cgroup_limit_bytes")
+
if m.allowedBytes > 0 {
m.limit.Store(uint64(m.allowedBytes))
m.l.Info().
@@ -237,11 +257,12 @@ func (m *memory) PreRun(context.Context) error {
Msg("memory protector enabled")
} else {
cgLimit, err := cgroups.MemoryLimit()
+ m.cgroupLimitGauge.Set(cgroupLimitGaugeValue(cgLimit, err))
if err != nil {
m.l.Warn().Err(err).Msg("failed to get memory limit from cgroups, disable memory protector")
return nil
}
- if cgLimit <= 0 || cgLimit > 1e18 {
+ if !cgroupLimitValid(cgLimit) {
m.l.Warn().Int64("cgroup_memory_limit", cgLimit).Msg("cgroup memory limit is invalid, disable memory protector")
return nil
}
@@ -291,8 +312,10 @@ func (m *memory) Serve() run.StopNotify {
}
atomic.StoreUint64(&m.usage, usedBytes)
+ m.usageGauge.Set(float64(usedBytes))
if usedBytes > m.limit.Load() {
+ m.overLimitCounter.Inc(1)
m.l.Warn().Str("used", humanize.Bytes(usedBytes)).Str("limit", humanize.Bytes(m.limit.Load())).Msg("memory usage exceeds limit")
}
}
diff --git a/banyand/protector/protector_test.go b/banyand/protector/protector_test.go
index e29d7e3d0..4736b77aa 100644
--- a/banyand/protector/protector_test.go
+++ b/banyand/protector/protector_test.go
@@ -18,10 +18,17 @@
package protector
import (
+ "context"
+ "errors"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
+
+ "github.com/apache/skywalking-banyandb/banyand/observability"
+ "github.com/apache/skywalking-banyandb/pkg/cgroups"
+ "github.com/apache/skywalking-banyandb/pkg/meter"
+ "github.com/apache/skywalking-banyandb/pkg/run"
)
// TestStateConstants verifies state constants are properly defined.
@@ -64,3 +71,103 @@ func TestMemoryStateNoLimit(t *testing.T) {
// No limit set (0)
assert.Equal(t, StateLow, m.State()) // Fail open
}
+
+// TestCgroupLimitGaugeValue verifies the raw cgroup limit is mapped to a gauge value,
+// reporting 0 for unlimited/unreadable/implausible inputs.
+func TestCgroupLimitGaugeValue(t *testing.T) {
+ assert.Equal(t, float64(4<<30), cgroupLimitGaugeValue(4<<30, nil)) // 4GiB limit
+ assert.Equal(t, float64(0), cgroupLimitGaugeValue(-1, nil)) // cgroup memory.max == "max"
+ assert.Equal(t, float64(0), cgroupLimitGaugeValue(0, nil))
+ assert.Equal(t, float64(0), cgroupLimitGaugeValue(int64(2e18), nil)) // implausibly large
+ assert.Equal(t, float64(0), cgroupLimitGaugeValue(4<<30, errors.New("x"))) // read error
+}
+
+// TestMetricsCreatedInPreRunNotConstructor pins the bug fix: NewMemory must NOT create
+// metrics (the prometheus provider is still nil during command assembly, so a gauge
+// created then is a silent no-op); PreRun creates all four against a ready provider.
+func TestMetricsCreatedInPreRunNotConstructor(t *testing.T) {
+ reg := newFakeRegistry()
+ m := NewMemory(reg).(*memory)
+
+ assert.Equal(t, 0, len(reg.created), "constructor must not create any metric")
+ assert.Nil(t, m.limitGauge)
+ assert.Nil(t, m.usageGauge)
+ assert.Nil(t, m.cgroupLimitGauge)
+ assert.Nil(t, m.overLimitCounter)
+
+ require := assert.New(t)
+ require.NoError(m.PreRun(context.Background()))
+
+ assert.NotNil(t, m.limitGauge)
+ assert.NotNil(t, m.usageGauge)
+ assert.NotNil(t, m.cgroupLimitGauge)
+ assert.NotNil(t, m.overLimitCounter)
+ assert.Contains(t, reg.created, "banyandb_memory_protector/limit")
+ assert.Contains(t, reg.created, "banyandb_memory_protector/usage")
+ assert.Contains(t, reg.created, "banyandb_memory_protector/over_limit_total")
+ assert.Contains(t, reg.created, "banyandb_memory_protector/cgroup_limit_bytes")
+
+ // The cgroup gauge is Set to the mapped raw cgroup limit (0 when unavailable/unlimited);
+ // comparing against the same mapping keeps the assertion environment-independent.
+ cgLimit, cgErr := cgroups.MemoryLimit()
+ assert.Equal(t, cgroupLimitGaugeValue(cgLimit, cgErr), m.cgroupLimitGauge.(*fakeGauge).value)
+}
+
+// fakeRegistry is a capturing observability.MetricsRegistry test double that records
+// the fully-qualified name of every metric created through it.
+type fakeRegistry struct {
+ created map[string]struct{}
+}
+
+func newFakeRegistry() *fakeRegistry {
+ return &fakeRegistry{created: make(map[string]struct{})}
+}
+
+func (r *fakeRegistry) With(scope meter.Scope) observability.Factory {
+ return &fakeFactory{reg: r, namespace: scope.GetNamespace()}
+}
+func (r *fakeRegistry) NativeEnabled() bool { return false }
+func (r *fakeRegistry) Name() string { return "fake-metrics-registry" }
+func (r *fakeRegistry) Serve() run.StopNotify { return nil }
+func (r *fakeRegistry) GracefulStop() {}
+
+type fakeFactory struct {
+ reg *fakeRegistry
+ namespace string
+}
+
+func (f *fakeFactory) record(name string) {
+ f.reg.created[f.namespace+"/"+name] = struct{}{}
+}
+
+func (f *fakeFactory) NewCounter(name string, _ ...string) meter.Counter {
+ f.record(name)
+ return &fakeCounter{}
+}
+
+func (f *fakeFactory) NewGauge(name string, _ ...string) meter.Gauge {
+ f.record(name)
+ return &fakeGauge{}
+}
+
+func (f *fakeFactory) NewHistogram(name string, _ meter.Buckets, _ ...string) meter.Histogram {
+ f.record(name)
+ return &fakeHistogram{}
+}
+func (f *fakeFactory) Close() {}
+
+type fakeGauge struct{ value float64 }
+
+func (g *fakeGauge) Set(v float64, _ ...string) { g.value = v }
+func (g *fakeGauge) Add(v float64, _ ...string) { g.value += v }
+func (g *fakeGauge) Delete(_ ...string) bool { return true }
+
+type fakeCounter struct{ value float64 }
+
+func (c *fakeCounter) Inc(v float64, _ ...string) { c.value += v }
+func (c *fakeCounter) Delete(_ ...string) bool { return true }
+
+type fakeHistogram struct{}
+
+func (h *fakeHistogram) Observe(_ float64, _ ...string) {}
+func (h *fakeHistogram) Delete(_ ...string) bool { return true }
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 7409ad42d..bc91b28c7 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -344,13 +344,19 @@
- [CrashBreadcrumb.FieldsEntry](#banyandb-fodc-v1-CrashBreadcrumb-FieldsEntry)
- [CrashPanicRecord](#banyandb-fodc-v1-CrashPanicRecord)
- [CrashPanicRecord.ProcessMetadataEntry](#banyandb-fodc-v1-CrashPanicRecord-ProcessMetadataEntry)
+ - [FetchPressureProfile](#banyandb-fodc-v1-FetchPressureProfile)
- [GroupLifecycleInfo](#banyandb-fodc-v1-GroupLifecycleInfo)
- [InspectAllRequest](#banyandb-fodc-v1-InspectAllRequest)
- [InspectAllResponse](#banyandb-fodc-v1-InspectAllResponse)
- [LifecycleData](#banyandb-fodc-v1-LifecycleData)
- [LifecycleReport](#banyandb-fodc-v1-LifecycleReport)
+ - [ListComplete](#banyandb-fodc-v1-ListComplete)
+ - [ListProfiles](#banyandb-fodc-v1-ListProfiles)
- [Metric](#banyandb-fodc-v1-Metric)
- [Metric.LabelsEntry](#banyandb-fodc-v1-Metric-LabelsEntry)
+ - [PressureProfileChunk](#banyandb-fodc-v1-PressureProfileChunk)
+ - [PressureProfileInfo](#banyandb-fodc-v1-PressureProfileInfo)
+ - [PressureProfileRecord](#banyandb-fodc-v1-PressureProfileRecord)
- [RegisterAgentRequest](#banyandb-fodc-v1-RegisterAgentRequest)
- [RegisterAgentRequest.LabelsEntry](#banyandb-fodc-v1-RegisterAgentRequest-LabelsEntry)
- [RegisterAgentResponse](#banyandb-fodc-v1-RegisterAgentResponse)
@@ -362,6 +368,8 @@
- [StreamLifecycleResponse](#banyandb-fodc-v1-StreamLifecycleResponse)
- [StreamMetricsRequest](#banyandb-fodc-v1-StreamMetricsRequest)
- [StreamMetricsResponse](#banyandb-fodc-v1-StreamMetricsResponse)
+ - [StreamPressureProfilesRequest](#banyandb-fodc-v1-StreamPressureProfilesRequest)
+ - [StreamPressureProfilesResponse](#banyandb-fodc-v1-StreamPressureProfilesResponse)
- [Topology](#banyandb-fodc-v1-Topology)
- [MetricType](#banyandb-fodc-v1-MetricType)
@@ -5472,6 +5480,24 @@ Phase represents the current phase of the deletion task.
+<a name="banyandb-fodc-v1-FetchPressureProfile"></a>
+
+### FetchPressureProfile
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| request_id | [string](#string) | | proxy-generated per fetch; echoed back in every PressureProfileChunk to correlate |
+| profile_id | [string](#string) | | |
+| type | [string](#string) | | "heap" | "goroutine" |
+| filepath | [string](#string) | | the absolute path the agent reported in PressureProfileInfo.filepath; agent opens it AFTER validating it is within --pressure-profiler-dir |
+
+
+
+
+
+
<a name="banyandb-fodc-v1-GroupLifecycleInfo"></a>
### GroupLifecycleInfo
@@ -5548,6 +5574,38 @@ Phase represents the current phase of the deletion task.
+<a name="banyandb-fodc-v1-ListComplete"></a>
+
+### ListComplete
+Agent -> Proxy: sent once after all records for a ListProfiles request have been
+streamed (including the zero-record case), so the proxy knows the agent is done
+without waiting out a fixed window.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| request_id | [string](#string) | | echoes ListProfiles.request_id |
+
+
+
+
+
+
+<a name="banyandb-fodc-v1-ListProfiles"></a>
+
+### ListProfiles
+Proxy -> Agent: stream all capture-event metadata for this request id.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| request_id | [string](#string) | | proxy-generated per list; echoed back in ListComplete to correlate |
+
+
+
+
+
+
<a name="banyandb-fodc-v1-Metric"></a>
### Metric
@@ -5584,6 +5642,68 @@ Phase represents the current phase of the deletion task.
+<a name="banyandb-fodc-v1-PressureProfileChunk"></a>
+
+### PressureProfileChunk
+One slice of a profile's bytes during download.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| request_id | [string](#string) | | echoes FetchPressureProfile.request_id -- correlates this chunk stream to its fetch |
+| profile_id | [string](#string) | | |
+| type | [string](#string) | | "heap" | "goroutine" |
+| data | [bytes](#bytes) | | a bounded slice (e.g. <= 1MB) |
+| last | [bool](#bool) | | true on the final chunk |
+| error | [string](#string) | | non-empty if the file cannot be served (e.g. evicted / not found) |
+
+
+
+
+
+
+<a name="banyandb-fodc-v1-PressureProfileInfo"></a>
+
+### PressureProfileInfo
+One pprof profile inside a capture event (metadata only, no bytes).
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| type | [string](#string) | | "heap" | "goroutine" |
+| filename | [string](#string) | | base name, e.g. "heap.pprof" |
+| filepath | [string](#string) | | absolute path on the agent's disk, e.g. /tmp/pressure-profiles/20260627T101112.000000000Z/heap.pprof |
+| format | [string](#string) | | "pprof" (gzip-compressed protobuf) |
+| size_bytes | [int64](#int64) | | on-disk size |
+
+
+
+
+
+
+<a name="banyandb-fodc-v1-PressureProfileRecord"></a>
+
+### PressureProfileRecord
+Metadata for one capture event (no bytes). pod/role are NOT carried here:
+the proxy enriches them from the registered AgentIdentity, same as crash.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| profile_id | [string](#string) | | = event directory name (UTC ns timestamp) |
+| captured_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | |
+| source_endpoint | [string](#string) | | pprof endpoint pulled, e.g. http://localhost:6060 |
+| rss_bytes | [uint64](#uint64) | | RSS at trigger (process_resident_memory_bytes); top-N sort key |
+| cgroup_limit_bytes | [uint64](#uint64) | | cgroup memory.max |
+| trigger_percent | [uint32](#uint32) | | configured threshold percent (e.g. 75) |
+| threshold_bytes | [uint64](#uint64) | | cgroup_limit_bytes * trigger_percent / 100 |
+| profiles | [PressureProfileInfo](#banyandb-fodc-v1-PressureProfileInfo) | repeated | |
+
+
+
+
+
+
<a name="banyandb-fodc-v1-RegisterAgentRequest"></a>
### RegisterAgentRequest
@@ -5765,6 +5885,40 @@ Phase represents the current phase of the deletion task.
+<a name="banyandb-fodc-v1-StreamPressureProfilesRequest"></a>
+
+### StreamPressureProfilesRequest
+Agent -> Proxy: either a metadata record (answer to list_profiles) or a byte
+chunk (answer to fetch_profile).
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| record | [PressureProfileRecord](#banyandb-fodc-v1-PressureProfileRecord) | | |
+| list_complete | [ListComplete](#banyandb-fodc-v1-ListComplete) | | |
+| chunk | [PressureProfileChunk](#banyandb-fodc-v1-PressureProfileChunk) | | |
+
+
+
+
+
+
+<a name="banyandb-fodc-v1-StreamPressureProfilesResponse"></a>
+
+### StreamPressureProfilesResponse
+Proxy -> Agent: either "stream all your metadata" or "stream one profile's bytes".
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| list_profiles | [ListProfiles](#banyandb-fodc-v1-ListProfiles) | | |
+| fetch_profile | [FetchPressureProfile](#banyandb-fodc-v1-FetchPressureProfile) | | |
+
+
+
+
+
+
<a name="banyandb-fodc-v1-Topology"></a>
### Topology
@@ -5815,6 +5969,7 @@ MetricType represents the Prometheus metric type.
| StreamClusterTopology | [StreamClusterTopologyRequest](#banyandb-fodc-v1-StreamClusterTopologyRequest) stream | [StreamClusterTopologyResponse](#banyandb-fodc-v1-StreamClusterTopologyResponse) stream | Bi-directional stream for cluster topology |
| StreamLifecycle | [StreamLifecycleRequest](#banyandb-fodc-v1-StreamLifecycleRequest) stream | [StreamLifecycleResponse](#banyandb-fodc-v1-StreamLifecycleResponse) stream | Bi-directional stream for lifecycle data |
| StreamCrashDiagnostics | [StreamCrashDiagnosticsRequest](#banyandb-fodc-v1-StreamCrashDiagnosticsRequest) stream | [StreamCrashDiagnosticsResponse](#banyandb-fodc-v1-StreamCrashDiagnosticsResponse) stream | Bi-directional stream for crash diagnostics Agent sends StreamCrashDiagnosticsRequest (panic collections), Proxy sends StreamCrashDiagnosticsResponse (requests) |
+| StreamPressureProfiles | [StreamPressureProfilesRequest](#banyandb-fodc-v1-StreamPressureProfilesRequest) stream | [StreamPressureProfilesResponse](#banyandb-fodc-v1-StreamPressureProfilesResponse) stream | Bi-directional stream for memory-pressure pprof profiles. Proxy drives via StreamPressureProfilesResponse (list metadata, or fetch one profile's bytes); agent replies with StreamPressureProfilesRequest (metadata records, or binary chunks). |
<a name="banyandb-fodc-v1-GroupLifecycleService"></a>
diff --git a/fodc/agent/internal/cmd/root.go b/fodc/agent/internal/cmd/root.go
index 73ede77ef..79a470f0b 100644
--- a/fodc/agent/internal/cmd/root.go
+++ b/fodc/agent/internal/cmd/root.go
@@ -39,6 +39,7 @@ import (
"github.com/apache/skywalking-banyandb/fodc/agent/internal/ktm"
"github.com/apache/skywalking-banyandb/fodc/agent/internal/lifecycle"
fodcmetrics "github.com/apache/skywalking-banyandb/fodc/agent/internal/metrics"
+ "github.com/apache/skywalking-banyandb/fodc/agent/internal/pressureprofiler"
"github.com/apache/skywalking-banyandb/fodc/agent/internal/proxy"
"github.com/apache/skywalking-banyandb/fodc/agent/internal/server"
"github.com/apache/skywalking-banyandb/fodc/agent/internal/watchdog"
@@ -61,6 +62,13 @@ const (
defaultReconnectInterval = 5 * time.Second
defaultClusterStatePollInterval = 30 * time.Second
defaultMaxDiagnosisMemoryUsagePercent = 5
+
+ defaultPressureTriggerPercent = 75
+ defaultPressurePprofPort = "6060"
+ defaultPressureCooldown = 5 * time.Minute
+ defaultPressureDir = "/tmp/pressure-profiles"
+ defaultPressureMaxArtifacts = 16
+ defaultPressureMaxDiskBytes = 512 * 1024 * 1024
)
var (
@@ -84,6 +92,13 @@ var (
lifecyclePort int
lifecycleReportDir string
lifecycleCacheTTL time.Duration
+ pressureProfilerEnabled bool
+ pressureTriggerPercent int
+ pressurePprofPort string
+ pressureCooldown time.Duration
+ pressureDir string
+ pressureMaxArtifacts int
+ pressureMaxDiskBytes int64
rootCmd = &cobra.Command{
Use: "fodc",
Short: "First Occurrence Data Collection (FODC) agent",
@@ -139,6 +154,20 @@ func init() {
"Directory where lifecycle sidecar writes report files")
rootCmd.Flags().DurationVar(&lifecycleCacheTTL, "lifecycle-cache-ttl", 10*time.Minute,
"TTL for cached lifecycle data. After expiry, the next collection call refreshes the cache")
+ rootCmd.Flags().BoolVar(&pressureProfilerEnabled, "pressure-profiler-enabled", true,
+ "Enable automatic heap+goroutine pprof capture when the monitored container's RSS approaches its cgroup memory limit")
+ rootCmd.Flags().IntVar(&pressureTriggerPercent, "pressure-profiler-trigger-percent", defaultPressureTriggerPercent,
+ "Capture when RSS / cgroup_max reaches this percentage (usage = process_resident_memory_bytes)")
+ rootCmd.Flags().StringVar(&pressurePprofPort, "pressure-profiler-pprof-port", defaultPressurePprofPort,
+ "Port of the monitored container's pprof endpoint to capture from")
+ rootCmd.Flags().DurationVar(&pressureCooldown, "pressure-profiler-cooldown", defaultPressureCooldown,
+ "Minimum interval between two pprof captures")
+ rootCmd.Flags().StringVar(&pressureDir, "pressure-profiler-dir", defaultPressureDir,
+ "Directory (absolute, on a writable volume) where captured profiles are stored")
+ rootCmd.Flags().IntVar(&pressureMaxArtifacts, "pressure-profiler-max-artifacts", defaultPressureMaxArtifacts,
+ "Maximum number of capture events to retain; the lowest-RSS events are evicted first")
+ rootCmd.Flags().Int64Var(&pressureMaxDiskBytes, "pressure-profiler-max-disk-bytes", defaultPressureMaxDiskBytes,
+ "Maximum total on-disk bytes for retained capture events (0 disables the disk bound)")
}
func calculateCapacity(log *logger.Logger) int64 {
@@ -284,6 +313,32 @@ func runFODC(_ *cobra.Command, _ []string) error {
wd.SetNodeInfoProvider(clusterCollector.GetNodeInfo)
}
+ var profileSource proxy.ProfileSource
+ if pressureProfilerEnabled {
+ roleProvider := func() string { return nodeRole }
+ if clusterCollector != nil {
+ roleProvider = func() string { role, _ := clusterCollector.GetNodeInfo(); return role }
+ }
+ pp, ppErr := pressureprofiler.New(pressureprofiler.Config{
+ Dir: pressureDir,
+ PprofPort: pressurePprofPort,
+ PodName: podName,
+ RoleProvider: roleProvider,
+ Cooldown: pressureCooldown,
+ MaxDiskBytes: pressureMaxDiskBytes,
+ TriggerPercent: pressureTriggerPercent,
+ MaxArtifacts: pressureMaxArtifacts,
+ }, fr, prom.NewProvider(panicScope, reg), log)
+ if ppErr != nil {
+ cluster.StopCollector(clusterCollector)
+ _ = metricsServer.Stop(ctx)
+ return fmt.Errorf("failed to start pressure profiler: %w", ppErr)
+ }
+ // Drive evaluation off the watchdog's poll completion (same cadence, freshest values).
+ wd.AddPostPollHook(pp.OnPollComplete)
+ profileSource = pp
+ }
+
stopKTM := initializeKTM(ctx, log, fr)
if preRunErr := wd.PreRun(ctx); preRunErr != nil {
@@ -315,7 +370,7 @@ func runFODC(_ *cobra.Command, _ []string) error {
}
return fmt.Errorf("failed to start metrics server: %w", startErr)
}
- proxyClient := startProxyClient(ctx, log, fr, nodeRole, nodeLabels, clusterCollector, crashCollectionLister)
+ proxyClient := startProxyClient(ctx, log, fr, nodeRole, nodeLabels, clusterCollector, crashCollectionLister, profileSource)
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
@@ -426,12 +481,15 @@ func validateFlags() error {
if maxFODCDiagnosisMemoryUsagePercent < 0 || maxFODCDiagnosisMemoryUsagePercent > 100 {
return fmt.Errorf("max-fodc-diagnosis-memory-usage-percentage must be between 0 and 100")
}
+ if pressureProfilerEnabled && (pressureTriggerPercent < 1 || pressureTriggerPercent > 100) {
+ return fmt.Errorf("pressure-profiler-trigger-percent must be between 1 and 100, got %d", pressureTriggerPercent)
+ }
return nil
}
func startProxyClient(ctx context.Context, log *logger.Logger, fr *flightrecorder.FlightRecorder,
nodeRole string, nodeLabels map[string]string, collector *cluster.Collector,
- collectionLister crashcollector.CollectionLister,
+ collectionLister crashcollector.CollectionLister, profileSource proxy.ProfileSource,
) *proxy.Client {
if proxyAddr == "" || podName == "" || nodeRole == "" {
log.Info().Msg("Proxy client not started (missing: --proxy-addr, --pod-name, and --node-role)")
@@ -447,7 +505,7 @@ func startProxyClient(ctx context.Context, log *logger.Logger, fr *flightrecorde
log.Info().Str("grpc_addr", grpcAddr).Msg("Lifecycle collector initialized")
}
client := proxy.NewClient(proxyAddr, nodeRole, podName, containerNames, nodeLabels,
- heartbeatInterval, reconnectInterval, fr, collector, lifecycleCollector, collectionLister, log)
+ heartbeatInterval, reconnectInterval, fr, collector, lifecycleCollector, collectionLister, profileSource, log)
panicdiag.GoWithRecovery(ctx, panicdiag.RecoveryOptions{
Component: "fodc-agent-proxy-client",
Logger: log,
diff --git a/fodc/agent/internal/cmd/root_test.go b/fodc/agent/internal/cmd/root_test.go
index 3dc117f9b..76f935e6f 100644
--- a/fodc/agent/internal/cmd/root_test.go
+++ b/fodc/agent/internal/cmd/root_test.go
@@ -67,6 +67,45 @@ func TestValidateFlags_Valid(t *testing.T) {
assert.NoError(t, err)
}
+func TestValidateFlags_PressureTriggerPercent(t *testing.T) {
+ origInterval := metricsPollInterval
+ origPorts := pollMetricsPorts
+ origContainers := containerNames
+ origMemPercent := maxMetricsMemoryUsagePercent
+ origEnabled := pressureProfilerEnabled
+ origTrigger := pressureTriggerPercent
+ defer func() {
+ metricsPollInterval = origInterval
+ pollMetricsPorts = origPorts
+ containerNames = origContainers
+ maxMetricsMemoryUsagePercent = origMemPercent
+ pressureProfilerEnabled = origEnabled
+ pressureTriggerPercent = origTrigger
+ }()
+
+ metricsPollInterval = defaultMetricsPollInterval
+ pollMetricsPorts = []string{"2121"}
+ containerNames = []string{"banyandb"}
+ maxMetricsMemoryUsagePercent = 10
+ pressureProfilerEnabled = true
+
+ for _, invalid := range []int{0, -1, 101} {
+ pressureTriggerPercent = invalid
+ err := validateFlags()
+ assert.Error(t, err, "trigger=%d", invalid)
+ assert.Contains(t, err.Error(), "pressure-profiler-trigger-percent must be between 1 and 100")
+ }
+
+ // A valid value passes.
+ pressureTriggerPercent = 75
+ assert.NoError(t, validateFlags())
+
+ // When the profiler is disabled, an out-of-range value is tolerated.
+ pressureProfilerEnabled = false
+ pressureTriggerPercent = 0
+ assert.NoError(t, validateFlags())
+}
+
func TestValidateFlags_ZeroInterval(t *testing.T) {
origInterval := metricsPollInterval
defer func() { metricsPollInterval = origInterval }()
diff --git a/fodc/agent/internal/flightrecorder/datasource.go b/fodc/agent/internal/flightrecorder/datasource.go
index b6ee00559..9aa2037e7 100644
--- a/fodc/agent/internal/flightrecorder/datasource.go
+++ b/fodc/agent/internal/flightrecorder/datasource.go
@@ -277,6 +277,25 @@ func (ds *Datasource) GetCurrentSnapshot() (map[string]float64, int64) {
return values, timestamp
}
+// latestValues fills out[name] with the current value of each metric whose key matches one
+// of names (with the optional label filter). It scans the metric keys directly under the read
+// lock and reads only the matched buffers, avoiding the full-map copy of GetCurrentSnapshot on
+// the watchdog poll path. Names already present in out are skipped.
+func (ds *Datasource) latestValues(out map[string]float64, names []string, labelFilter map[string]string) {
+ ds.mu.RLock()
+ defer ds.mu.RUnlock()
+ for key, buffer := range ds.metrics {
+ for _, name := range names {
+ if _, done := out[name]; done {
+ continue
+ }
+ if metricKeyMatches(key, name, labelFilter) {
+ out[name] = buffer.GetCurrentValue()
+ }
+ }
+ }
+}
+
// GetDescriptions returns a copy of the descriptions map.
func (ds *Datasource) GetDescriptions() map[string]string {
ds.mu.RLock()
diff --git a/fodc/agent/internal/flightrecorder/flightrecorder.go b/fodc/agent/internal/flightrecorder/flightrecorder.go
index 9709d0631..af5b6d464 100644
--- a/fodc/agent/internal/flightrecorder/flightrecorder.go
+++ b/fodc/agent/internal/flightrecorder/flightrecorder.go
@@ -20,6 +20,7 @@ package flightrecorder
import (
"fmt"
"runtime"
+ "strings"
"sync"
"time"
@@ -79,6 +80,50 @@ func (fr *FlightRecorder) GetDatasources() []*Datasource {
return result
}
+// LatestValues returns the latest scraped value for each requested metric name that has a
+// series matching labelFilter; names with no match are absent from the result. It snapshots
+// the datasources once and resolves all names in a single pass. When several series share a
+// name, an empty filter takes the first found.
+func (fr *FlightRecorder) LatestValues(names []string, labelFilter map[string]string) map[string]float64 {
+ out := make(map[string]float64, len(names))
+ if len(names) == 0 {
+ return out
+ }
+
+ fr.mu.RLock()
+ defer fr.mu.RUnlock()
+
+ for _, ds := range fr.datasources {
+ ds.latestValues(out, names, labelFilter)
+ if len(out) == len(names) {
+ break
+ }
+ }
+ return out
+}
+
+// metricKeyMatches reports whether a metric key produced by metrics.MetricKey.String()
+// (either "name" or `name{l1="v1",l2="v2"}`) has the given name and contains every
+// label in labelFilter.
+func metricKeyMatches(key, name string, labelFilter map[string]string) bool {
+ if !strings.HasPrefix(key, name) {
+ return false
+ }
+ rest := key[len(name):]
+ if rest != "" && !strings.HasPrefix(rest, "{") {
+ return false
+ }
+ for ln, lv := range labelFilter {
+ // Anchor the label name on a boundary ('{' for the first label, ',' otherwise) so a
+ // filter label `l` does not falsely match a longer label like `xl` in the key.
+ needle := ln + `="` + lv + `"`
+ if !strings.Contains(rest, "{"+needle) && !strings.Contains(rest, ","+needle) {
+ return false
+ }
+ }
+ return true
+}
+
// SetCapacitySize sets the memory limit for the flight recorder.
func (fr *FlightRecorder) SetCapacitySize(capacitySize int64) {
fr.mu.Lock()
diff --git a/fodc/agent/internal/flightrecorder/flightrecorder_test.go b/fodc/agent/internal/flightrecorder/flightrecorder_test.go
index f8e301d3c..8592a710a 100644
--- a/fodc/agent/internal/flightrecorder/flightrecorder_test.go
+++ b/fodc/agent/internal/flightrecorder/flightrecorder_test.go
@@ -627,3 +627,55 @@ func TestFlightRecorder_Update_ReusesFirstDatasource(t *testing.T) {
// Should reuse the same datasource
assert.Equal(t, firstDS, datasources2[0])
}
+
+// TestMetricKeyMatches pins the boundary-anchored key matching used by LatestValues.
+func TestMetricKeyMatches(t *testing.T) {
+ cases := []struct {
+ filter map[string]string
+ key string
+ name string
+ want bool
+ }{
+ {nil, "m", "m", true},
+ {nil, `m{a="1"}`, "m", true},
+ {nil, "m_total", "m", false}, // a longer metric name must not match
+ {map[string]string{"a": "1"}, `m{a="1"}`, "m", true},
+ {map[string]string{"a": "2"}, `m{a="1"}`, "m", false},
+ {map[string]string{"a": "1"}, `m{xa="1"}`, "m", false}, // boundary: xa is not a
+ {map[string]string{"b": "2"}, `m{a="1",b="2"}`, "m", true},
+ }
+ for _, c := range cases {
+ assert.Equal(t, c.want, metricKeyMatches(c.key, c.name, c.filter), "key=%s name=%s filter=%v", c.key, c.name, c.filter)
+ }
+}
+
+// TestLatestValues resolves multiple metrics by name and label filter in one pass.
+func TestLatestValues(t *testing.T) {
+ fr := NewFlightRecorder(0)
+ require.NoError(t, fr.Update([]metrics.RawMetric{
+ {Name: "process_resident_memory_bytes", Value: 1290, Labels: []metrics.Label{{Name: "container_name", Value: "data"}}},
+ {Name: "banyandb_memory_protector_cgroup_limit_bytes", Value: 4096},
+ {Name: "process_resident_memory_bytes_total", Value: 999},
+ }))
+
+ // Batch resolve both names in a single snapshot.
+ values := fr.LatestValues([]string{"process_resident_memory_bytes", "banyandb_memory_protector_cgroup_limit_bytes"}, nil)
+ assert.Equal(t, float64(1290), values["process_resident_memory_bytes"])
+ assert.Equal(t, float64(4096), values["banyandb_memory_protector_cgroup_limit_bytes"])
+
+ // Prefix must not match a longer metric name; missing names are absent from the result.
+ _, ok := fr.LatestValues([]string{"process_resident_memory"}, nil)["process_resident_memory"]
+ assert.False(t, ok)
+ _, ok = fr.LatestValues([]string{"does_not_exist"}, nil)["does_not_exist"]
+ assert.False(t, ok)
+
+ // Label filter selects the matching series.
+ match := fr.LatestValues([]string{"process_resident_memory_bytes"}, map[string]string{"container_name": "data"})
+ assert.Equal(t, float64(1290), match["process_resident_memory_bytes"])
+
+ _, ok = fr.LatestValues([]string{"process_resident_memory_bytes"}, map[string]string{"container_name": "liaison"})["process_resident_memory_bytes"]
+ assert.False(t, ok)
+
+ // An empty name list returns an empty map.
+ assert.Empty(t, fr.LatestValues(nil, nil))
+}
diff --git a/fodc/agent/internal/pressureprofiler/fetch.go b/fodc/agent/internal/pressureprofiler/fetch.go
new file mode 100644
index 000000000..7b41c5955
--- /dev/null
+++ b/fodc/agent/internal/pressureprofiler/fetch.go
@@ -0,0 +1,59 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package pressureprofiler
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+)
+
+// fetchProfile streams a pprof endpoint's body straight to dest, never buffering the
+// whole profile in memory. It returns the number of bytes written.
+func fetchProfile(ctx context.Context, client *http.Client, url, dest string) (int64, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return 0, fmt.Errorf("failed to build pprof request: %w", err)
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return 0, fmt.Errorf("failed to fetch pprof %q: %w", url, err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode != http.StatusOK {
+ return 0, fmt.Errorf("pprof %q returned status %d", url, resp.StatusCode)
+ }
+
+ f, err := os.Create(dest) //nolint:gosec // dest is built under the store's private directory
+ if err != nil {
+ return 0, fmt.Errorf("failed to create profile file %q: %w", dest, err)
+ }
+ n, copyErr := io.Copy(f, resp.Body)
+ closeErr := f.Close()
+ if copyErr != nil {
+ _ = os.Remove(dest)
+ return 0, fmt.Errorf("failed to write profile %q: %w", dest, copyErr)
+ }
+ if closeErr != nil {
+ _ = os.Remove(dest)
+ return 0, fmt.Errorf("failed to flush profile %q: %w", dest, closeErr)
+ }
+ return n, nil
+}
diff --git a/fodc/agent/internal/pressureprofiler/profiler.go b/fodc/agent/internal/pressureprofiler/profiler.go
new file mode 100644
index 000000000..dddda97e1
--- /dev/null
+++ b/fodc/agent/internal/pressureprofiler/profiler.go
@@ -0,0 +1,239 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Package pressureprofiler captures heap and goroutine pprof profiles from the
+// monitored BanyanDB container when its RSS approaches the cgroup memory limit,
+// stores them on a shared volume, and exposes them to the FODC proxy.
+package pressureprofiler
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "sync/atomic"
+ "time"
+
+ "github.com/apache/skywalking-banyandb/fodc/internal/pprofcapture"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+ "github.com/apache/skywalking-banyandb/pkg/meter"
+ "github.com/apache/skywalking-banyandb/pkg/run"
+)
+
+const (
+ // rssMetricName is the BanyanDB-exposed resident set size used as the usage signal.
+ rssMetricName = "process_resident_memory_bytes"
+ // limitMetricName is the BanyanDB-exposed raw cgroup memory.max gauge.
+ limitMetricName = "banyandb_memory_protector_cgroup_limit_bytes"
+ // captureHTTPTimeout bounds each pprof fetch.
+ captureHTTPTimeout = 30 * time.Second
+ // profileIDLayout names an event directory by its UTC nanosecond capture time.
+ profileIDLayout = "20060102T150405.000000000Z"
+)
+
+// Config holds the pressure profiler settings derived from the agent flags.
+type Config struct {
+ RoleProvider func() string
+ Dir string
+ PprofPort string
+ PodName string
+ Cooldown time.Duration
+ MaxDiskBytes int64
+ TriggerPercent int
+ MaxArtifacts int
+}
+
+// Profiler watches the flight recorder for memory pressure and captures pprof profiles.
+type Profiler struct {
+ fr metricSource
+ log *logger.Logger
+ store *store
+ httpClient *http.Client
+ captureTotal meter.Counter
+ skippedCooldownTotal meter.Counter
+ failuresTotal meter.Counter
+ cfg Config
+ lastCapture atomic.Int64
+ capturing atomic.Bool
+}
+
+// metricSource is the slice of the flight recorder the profiler depends on.
+type metricSource interface {
+ LatestValues(names []string, labelFilter map[string]string) map[string]float64
+}
+
+// New creates a Profiler and runs the storage self-check, returning an error if the storage
+// directory cannot be created or written so the caller can fail startup rather than discover
+// the misconfiguration at OOM time. Counters are created on the provider, whose scope prefixes
+// their exposed names with "fodc_agent_". Once created, the profiler is driven by OnPollComplete,
+// which the watchdog invokes after each metrics poll.
+func New(cfg Config, fr metricSource, provider meter.Provider, log *logger.Logger) (*Profiler, error) {
+ p := &Profiler{
+ cfg: cfg,
+ fr: fr,
+ log: log,
+ store: newStore(cfg.Dir, cfg.MaxArtifacts, cfg.MaxDiskBytes, log),
+ httpClient: &http.Client{Timeout: captureHTTPTimeout},
+ captureTotal: provider.Counter("pressure_capture_total"),
+ skippedCooldownTotal: provider.Counter("pressure_skipped_cooldown_total"),
+ failuresTotal: provider.Counter("pressure_failures_total", "reason"),
+ }
+ if err := p.store.selfCheck(); err != nil {
+ return nil, fmt.Errorf("pressure profiler self-check failed: %w", err)
+ }
+ log.Info().Str("dir", cfg.Dir).Int("trigger_percent", cfg.TriggerPercent).Msg("pressure profiler started")
+ return p, nil
+}
+
+// OnPollComplete evaluates memory pressure using the values the watchdog just scraped into
+// the flight recorder. The cheap trigger decision runs inline on the poll goroutine; an actual
+// capture (which fetches pprof over HTTP) is launched on its own goroutine so it never stalls
+// metrics polling, and the capturing guard prevents overlapping captures.
+func (p *Profiler) OnPollComplete(ctx context.Context) {
+ values := p.fr.LatestValues([]string{rssMetricName, limitMetricName}, nil)
+ rss, okRSS := values[rssMetricName]
+ limit, okLimit := values[limitMetricName]
+ if !okRSS || !okLimit || limit <= 0 {
+ return
+ }
+ threshold := limit * float64(p.cfg.TriggerPercent) / 100
+ if rss < threshold {
+ p.log.Debug().
+ Float64("rss_bytes", rss).
+ Float64("cgroup_limit_bytes", limit).
+ Float64("threshold_bytes", threshold).
+ Int("trigger_percent", p.cfg.TriggerPercent).
+ Msg("memory pressure below trigger threshold, skipping capture")
+ return
+ }
+
+ now := time.Now()
+ last := p.lastCapture.Load()
+ if last != 0 && now.Sub(time.Unix(0, last)) < p.cfg.Cooldown {
+ p.skippedCooldownTotal.Inc(1)
+ p.log.Info().
+ Float64("rss_bytes", rss).
+ Float64("cgroup_limit_bytes", limit).
+ Float64("threshold_bytes", threshold).
+ Dur("since_last_capture", now.Sub(time.Unix(0, last))).
+ Dur("cooldown", p.cfg.Cooldown).
+ Msg("memory pressure threshold reached but within cooldown, skipping capture")
+ return
+ }
+
+ if !p.capturing.CompareAndSwap(false, true) {
+ // A capture launched by an earlier poll is still running.
+ p.log.Info().
+ Float64("rss_bytes", rss).
+ Float64("cgroup_limit_bytes", limit).
+ Float64("threshold_bytes", threshold).
+ Msg("memory pressure threshold reached but a capture is already in progress, skipping")
+ return
+ }
+ p.log.Info().
+ Float64("rss_bytes", rss).
+ Float64("cgroup_limit_bytes", limit).
+ Float64("threshold_bytes", threshold).
+ Int("trigger_percent", p.cfg.TriggerPercent).
+ Msg("memory pressure threshold reached, launching pprof capture")
+ rssBytes, limitBytes, thresholdBytes := uint64(rss), uint64(limit), uint64(threshold)
+ run.Go(ctx, "fodc.agent.pressure-capture", p.log, func(ctx context.Context) {
+ defer p.capturing.Store(false)
+ p.capture(ctx, now, rssBytes, limitBytes, thresholdBytes)
+ })
+}
+
+// capture pulls every target profile into a unique event directory and finalizes the
+// event with a meta.json. A failed fetch is counted but never aborts the event: even
+// with no profiles the record preserves the "RSS X near limit Y" moment.
+func (p *Profiler) capture(ctx context.Context, at time.Time, rss, limit, threshold uint64) {
+ profileID := at.UTC().Format(profileIDLayout)
+ dir := p.store.eventDir(profileID)
+ if err := os.MkdirAll(dir, 0o750); err != nil {
+ p.failuresTotal.Inc(1, "mkdir")
+ p.log.Warn().Err(err).Str("dir", dir).Msg("failed to create pressure event directory")
+ return
+ }
+
+ base := fmt.Sprintf("http://localhost:%s", p.cfg.PprofPort)
+ infos := make([]ProfileInfo, 0, len(pprofcapture.Targets))
+ for _, target := range pprofcapture.Targets {
+ filename := target.Type + ".pprof"
+ dest := filepath.Join(dir, filename)
+ n, err := fetchProfile(ctx, p.httpClient, base+target.Path, dest)
+ if err != nil {
+ p.failuresTotal.Inc(1, "fetch")
+ p.log.Warn().Err(err).Str("type", target.Type).Msg("failed to fetch pprof profile")
+ continue
+ }
+ infos = append(infos, ProfileInfo{
+ Type: target.Type,
+ Filename: filename,
+ Filepath: dest,
+ Format: "pprof",
+ SizeBytes: n,
+ })
+ }
+
+ m := meta{
+ CapturedAt: at.UTC().Format(time.RFC3339Nano),
+ PodName: p.cfg.PodName,
+ Role: p.role(),
+ SourceEndpoint: base,
+ RSSBytes: rss,
+ CgroupLimitBytes: limit,
+ TriggerPercent: uint32(p.cfg.TriggerPercent),
+ ThresholdBytes: threshold,
+ Profiles: infos,
+ }
+ if err := p.store.finalize(profileID, m); err != nil {
+ p.failuresTotal.Inc(1, "finalize")
+ p.log.Error().Err(err).Str("profile_id", profileID).Msg("failed to finalize pressure event")
+ return
+ }
+ // Start the cooldown only from a successful capture; a failed one leaves lastCapture
+ // untouched so the next poll retries immediately. The capturing CAS already prevents
+ // overlapping captures, so nothing needs to reserve the window before this point.
+ p.lastCapture.Store(at.UnixNano())
+ p.captureTotal.Inc(1)
+ p.log.Info().
+ Str("profile_id", profileID).
+ Uint64("rss_bytes", rss).
+ Uint64("cgroup_limit_bytes", limit).
+ Int("profiles", len(infos)).
+ Msg("captured memory-pressure pprof profiles")
+}
+
+func (p *Profiler) role() string {
+ if p.cfg.RoleProvider == nil {
+ return ""
+ }
+ return p.cfg.RoleProvider()
+}
+
+// ListProfileRecords returns the metadata of every complete capture event on disk.
+func (p *Profiler) ListProfileRecords() []ProfileRecord {
+ return p.store.list()
+}
+
+// OpenProfile validates the path is within the storage directory and returns an open
+// handle for streaming; the caller closes it.
+func (p *Profiler) OpenProfile(path string) (io.ReadCloser, error) {
+ return p.store.open(path)
+}
diff --git a/fodc/agent/internal/pressureprofiler/profiler_test.go b/fodc/agent/internal/pressureprofiler/profiler_test.go
new file mode 100644
index 000000000..b2bcc9a15
--- /dev/null
+++ b/fodc/agent/internal/pressureprofiler/profiler_test.go
@@ -0,0 +1,206 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package pressureprofiler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+ "github.com/apache/skywalking-banyandb/pkg/meter"
+)
+
+type fakeSource struct {
+ rss float64
+ limit float64
+ okRSS bool
+}
+
+func (f *fakeSource) LatestValues(names []string, _ map[string]string) map[string]float64 {
+ out := make(map[string]float64, len(names))
+ for _, name := range names {
+ switch name {
+ case rssMetricName:
+ if f.okRSS {
+ out[name] = f.rss
+ }
+ case limitMetricName:
+ if f.limit > 0 {
+ out[name] = f.limit
+ }
+ }
+ }
+ return out
+}
+
+func newProfilerForTest(t *testing.T, dir, port string, src *fakeSource) (*Profiler, *fakeProvider) {
+ t.Helper()
+ require.NoError(t, logger.Init(logger.Logging{Env: "dev", Level: "error"}))
+ provider := newFakeProvider()
+ p, err := New(Config{
+ Dir: dir,
+ PprofPort: port,
+ PodName: "demo-pod",
+ RoleProvider: func() string { return "data" },
+ Cooldown: time.Minute,
+ TriggerPercent: 75,
+ MaxArtifacts: 16,
+ }, src, provider, logger.GetLogger("pressure-test"))
+ require.NoError(t, err)
+ return p, provider
+}
+
+func pprofTestServer(t *testing.T) (string, func()) {
+ t.Helper()
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte("PPROF-BYTES"))
+ }))
+ port := srv.URL[strings.LastIndex(srv.URL, ":")+1:]
+ return port, srv.Close
+}
+
+// TestOnPollCompleteCapturesOnPressure captures both profiles once RSS/limit crosses the threshold.
+func TestOnPollCompleteCapturesOnPressure(t *testing.T) {
+ port, stop := pprofTestServer(t)
+ defer stop()
+ p, provider := newProfilerForTest(t, t.TempDir(), port, &fakeSource{rss: 800, limit: 1000, okRSS: true})
+
+ p.OnPollComplete(context.Background())
+
+ require.Eventually(t, func() bool {
+ return provider.counter("pressure_capture_total").value() == 1
+ }, 3*time.Second, 20*time.Millisecond)
+
+ records := p.ListProfileRecords()
+ require.Len(t, records, 1)
+ assert.Equal(t, uint64(800), records[0].RSSBytes)
+ assert.Equal(t, uint64(750), records[0].ThresholdBytes)
+ assert.Len(t, records[0].Profiles, 2)
+}
+
+// TestOnPollCompleteBelowThreshold does nothing when RSS is under the threshold.
+func TestOnPollCompleteBelowThreshold(t *testing.T) {
+ port, stop := pprofTestServer(t)
+ defer stop()
+ p, provider := newProfilerForTest(t, t.TempDir(), port, &fakeSource{rss: 700, limit: 1000, okRSS: true})
+
+ p.OnPollComplete(context.Background())
+ time.Sleep(100 * time.Millisecond)
+
+ assert.Equal(t, int64(0), provider.counter("pressure_capture_total").value())
+ assert.Empty(t, p.ListProfileRecords())
+}
+
+// TestOnPollCompleteCooldown skips a second capture inside the cooldown window.
+func TestOnPollCompleteCooldown(t *testing.T) {
+ port, stop := pprofTestServer(t)
+ defer stop()
+ p, provider := newProfilerForTest(t, t.TempDir(), port, &fakeSource{rss: 900, limit: 1000, okRSS: true})
+
+ p.OnPollComplete(context.Background())
+ require.Eventually(t, func() bool {
+ return provider.counter("pressure_capture_total").value() == 1
+ }, 3*time.Second, 20*time.Millisecond)
+
+ // A second poll inside the cooldown window is skipped and counted.
+ p.OnPollComplete(context.Background())
+ assert.Equal(t, int64(1), provider.counter("pressure_skipped_cooldown_total").value())
+ assert.Equal(t, int64(1), provider.counter("pressure_capture_total").value())
+}
+
+// TestOnPollCompleteMissingMetrics does nothing when the metrics are unavailable.
+func TestOnPollCompleteMissingMetrics(t *testing.T) {
+ port, stop := pprofTestServer(t)
+ defer stop()
+ p, provider := newProfilerForTest(t, t.TempDir(), port, &fakeSource{rss: 900, limit: 0, okRSS: true})
+
+ p.OnPollComplete(context.Background())
+ time.Sleep(100 * time.Millisecond)
+ assert.Equal(t, int64(0), provider.counter("pressure_capture_total").value())
+}
+
+// TestOnPollCompleteFinalizesOnFetchFailure verifies that when the pprof endpoint is unreachable
+// the event is still finalized (with zero profiles) and the failures counter is incremented.
+func TestOnPollCompleteFinalizesOnFetchFailure(t *testing.T) {
+ // Port 1 has nothing listening, so every pprof fetch fails fast with connection refused.
+ p, provider := newProfilerForTest(t, t.TempDir(), "1", &fakeSource{rss: 800, limit: 1000, okRSS: true})
+
+ p.OnPollComplete(context.Background())
+
+ require.Eventually(t, func() bool {
+ return provider.counter("pressure_capture_total").value() == 1
+ }, 5*time.Second, 20*time.Millisecond)
+ assert.GreaterOrEqual(t, provider.counter("pressure_failures_total").value(), int64(1))
+
+ records := p.ListProfileRecords()
+ require.Len(t, records, 1)
+ assert.Empty(t, records[0].Profiles, "event is finalized even when no profile could be fetched")
+}
+
+// fakeProvider is a capturing meter.Provider test double.
+
+type fakeProvider struct {
+ counters map[string]*fakeCounter
+}
+
+func newFakeProvider() *fakeProvider {
+ return &fakeProvider{counters: make(map[string]*fakeCounter)}
+}
+
+func (p *fakeProvider) counter(name string) *fakeCounter {
+ if c, ok := p.counters[name]; ok {
+ return c
+ }
+ return &fakeCounter{}
+}
+
+func (p *fakeProvider) Counter(name string, _ ...string) meter.Counter {
+ c := &fakeCounter{}
+ p.counters[name] = c
+ return c
+}
+func (p *fakeProvider) Gauge(_ string, _ ...string) meter.Gauge { return &fakeGauge{} }
+func (p *fakeProvider) Histogram(_ string, _ meter.Buckets, _ ...string) meter.Histogram {
+ return &fakeHistogram{}
+}
+func (p *fakeProvider) Close() {}
+
+type fakeCounter struct{ n atomic.Int64 }
+
+func (c *fakeCounter) Inc(delta float64, _ ...string) { c.n.Add(int64(delta)) }
+func (c *fakeCounter) Delete(_ ...string) bool { return true }
+func (c *fakeCounter) value() int64 { return c.n.Load() }
+
+type fakeGauge struct{}
+
+func (g *fakeGauge) Set(_ float64, _ ...string) {}
+func (g *fakeGauge) Add(_ float64, _ ...string) {}
+func (g *fakeGauge) Delete(_ ...string) bool { return true }
+
+type fakeHistogram struct{}
+
+func (h *fakeHistogram) Observe(_ float64, _ ...string) {}
+func (h *fakeHistogram) Delete(_ ...string) bool { return true }
diff --git a/fodc/agent/internal/pressureprofiler/storage.go b/fodc/agent/internal/pressureprofiler/storage.go
new file mode 100644
index 000000000..0a464075e
--- /dev/null
+++ b/fodc/agent/internal/pressureprofiler/storage.go
@@ -0,0 +1,258 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package pressureprofiler
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+)
+
+// metaFilename marks a complete capture event; a directory is only listed and
+// counted once this file exists (written atomically last).
+const metaFilename = "meta.json"
+
+// ProfileInfo describes one pprof profile inside a capture event (metadata only).
+type ProfileInfo struct {
+ Type string `json:"type"`
+ Filename string `json:"filename"`
+ Filepath string `json:"filepath"`
+ Format string `json:"format"`
+ SizeBytes int64 `json:"size_bytes"`
+}
+
+// ProfileRecord is the metadata of one capture event, reconstructed from its meta.json. It
+// intentionally omits pod name and role: those are carried in meta.json for the file to be
+// self-describing, but over the wire the proxy enriches them from the registered AgentIdentity.
+type ProfileRecord struct {
+ CapturedAt time.Time
+ ProfileID string
+ SourceEndpoint string
+ Profiles []ProfileInfo
+ RSSBytes uint64
+ CgroupLimitBytes uint64
+ ThresholdBytes uint64
+ TriggerPercent uint32
+}
+
+// meta is the on-disk meta.json schema for one capture event.
+type meta struct {
+ CapturedAt string `json:"capturedAt"`
+ PodName string `json:"podName"`
+ Role string `json:"role"`
+ SourceEndpoint string `json:"sourceEndpoint"`
+ Profiles []ProfileInfo `json:"profiles"`
+ RSSBytes uint64 `json:"rssBytes"`
+ CgroupLimitBytes uint64 `json:"cgroupLimitBytes"`
+ ThresholdBytes uint64 `json:"thresholdBytes"`
+ TriggerPercent uint32 `json:"triggerPercent"`
+}
+
+// store owns the on-disk layout under a private directory: one sub-directory per
+// capture event (named by a UTC nanosecond timestamp), each holding the pprof
+// binaries plus a meta.json. A single mutex serializes the directory-entry
+// operations (finalize, evict, list, open); long file reads run lock-free because
+// an already-open fd survives a concurrent unlink.
+type store struct {
+ log *logger.Logger
+ dir string
+ maxArtifacts int
+ maxDiskBytes int64
+ mu sync.Mutex
+}
+
+func newStore(dir string, maxArtifacts int, maxDiskBytes int64, log *logger.Logger) *store {
+ return &store{dir: dir, maxArtifacts: maxArtifacts, maxDiskBytes: maxDiskBytes, log: log}
+}
+
+// selfCheck verifies the storage directory can be created and written, surfacing a
+// misconfigured/read-only volume at startup instead of at the moment of capture.
+func (s *store) selfCheck() error {
+ if err := os.MkdirAll(s.dir, 0o750); err != nil {
+ return fmt.Errorf("cannot create pressure-profiler dir %q: %w", s.dir, err)
+ }
+ probe := filepath.Join(s.dir, ".write-probe")
+ if err := os.WriteFile(probe, []byte("ok"), 0o600); err != nil {
+ return fmt.Errorf("pressure-profiler dir %q is not writable: %w", s.dir, err)
+ }
+ if err := os.Remove(probe); err != nil {
+ return fmt.Errorf("pressure-profiler dir %q probe cleanup failed: %w", s.dir, err)
+ }
+ return nil
+}
+
+// eventDir returns the directory path for a capture event without creating it.
+func (s *store) eventDir(profileID string) string {
+ return filepath.Join(s.dir, profileID)
+}
+
+// finalize atomically writes meta.json for an already-populated event directory and
+// then enforces the retention bounds. Profile binaries are streamed into the unique
+// event directory before this call without holding the lock; the directory only
+// becomes visible to list/evict once meta.json exists.
+func (s *store) finalize(profileID string, m meta) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ dir := s.eventDir(profileID)
+ data, err := json.MarshalIndent(m, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal meta.json: %w", err)
+ }
+ tmp := filepath.Join(dir, metaFilename+".tmp")
+ if err = os.WriteFile(tmp, data, 0o600); err != nil {
+ return fmt.Errorf("failed to write meta.json: %w", err)
+ }
+ if err = os.Rename(tmp, filepath.Join(dir, metaFilename)); err != nil {
+ return fmt.Errorf("failed to finalize meta.json: %w", err)
+ }
+ s.evictLocked()
+ return nil
+}
+
+// list returns the metadata of every complete capture event, newest sort handled by callers.
+func (s *store) list() []ProfileRecord {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.scanLocked()
+}
+
+// open validates that requestedPath resolves inside the storage directory (the path
+// is round-tripped through the proxy and therefore untrusted) and returns an open
+// file handle. The caller streams and closes it; a concurrent evict that unlinks the
+// directory entry does not disturb an already-open fd.
+func (s *store) open(requestedPath string) (*os.File, error) {
+ clean := filepath.Clean(requestedPath)
+ base := filepath.Clean(s.dir)
+ if clean != base && !strings.HasPrefix(clean, base+string(os.PathSeparator)) {
+ return nil, fmt.Errorf("path %q escapes pressure-profiler dir", requestedPath)
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ f, err := os.Open(clean) //nolint:gosec // path validated to be within s.dir above
+ if err != nil {
+ return nil, fmt.Errorf("failed to open profile %q: %w", requestedPath, err)
+ }
+ return f, nil
+}
+
+// diskSize is the on-disk size of an event: the sum of its profile file sizes.
+func (r ProfileRecord) diskSize() int64 {
+ var n int64
+ for _, p := range r.Profiles {
+ n += p.SizeBytes
+ }
+ return n
+}
+
+// scanLocked reads every complete event directory into a record. Callers must hold s.mu.
+func (s *store) scanLocked() []ProfileRecord {
+ entries, err := os.ReadDir(s.dir)
+ if err != nil {
+ return nil
+ }
+ var records []ProfileRecord
+ for _, entry := range entries {
+ if !entry.IsDir() {
+ continue
+ }
+ profileID := entry.Name()
+ m, readErr := readMeta(filepath.Join(s.dir, profileID, metaFilename))
+ if readErr != nil {
+ continue
+ }
+ capturedAt, _ := time.Parse(time.RFC3339Nano, m.CapturedAt)
+ records = append(records, ProfileRecord{
+ ProfileID: profileID,
+ CapturedAt: capturedAt,
+ SourceEndpoint: m.SourceEndpoint,
+ RSSBytes: m.RSSBytes,
+ CgroupLimitBytes: m.CgroupLimitBytes,
+ TriggerPercent: m.TriggerPercent,
+ ThresholdBytes: m.ThresholdBytes,
+ Profiles: m.Profiles,
+ })
+ }
+ return records
+}
+
+// evictLocked keeps the highest-RSS events within both the artifact-count and the
+// total-disk bounds, deleting the lowest-RSS events first; it always keeps at least
+// one event. Callers must hold s.mu.
+func (s *store) evictLocked() {
+ records := s.scanLocked()
+ if len(records) <= 1 {
+ return
+ }
+ sort.Slice(records, func(i, j int) bool {
+ if records[i].RSSBytes != records[j].RSSBytes {
+ return records[i].RSSBytes > records[j].RSSBytes
+ }
+ return records[i].CapturedAt.After(records[j].CapturedAt)
+ })
+
+ var kept int
+ var diskUsed int64
+ var evicted []string
+ for idx, rec := range records {
+ size := rec.diskSize()
+ overCount := s.maxArtifacts > 0 && kept >= s.maxArtifacts
+ overDisk := s.maxDiskBytes > 0 && diskUsed+size > s.maxDiskBytes
+ if idx > 0 && (overCount || overDisk) {
+ if err := os.RemoveAll(s.eventDir(rec.ProfileID)); err != nil {
+ if s.log != nil {
+ s.log.Warn().Err(err).Str("profile_id", rec.ProfileID).Msg("failed to evict pressure profile event")
+ }
+ continue
+ }
+ evicted = append(evicted, rec.ProfileID)
+ continue
+ }
+ kept++
+ diskUsed += size
+ }
+ if len(evicted) > 0 && s.log != nil {
+ s.log.Info().
+ Strs("evicted", evicted).
+ Int("evicted_count", len(evicted)).
+ Int("kept_count", kept).
+ Int64("disk_used_bytes", diskUsed).
+ Int("max_artifacts", s.maxArtifacts).
+ Int64("max_disk_bytes", s.maxDiskBytes).
+ Msg("enforced pressure profile retention")
+ }
+}
+
+func readMeta(path string) (meta, error) {
+ data, err := os.ReadFile(path) //nolint:gosec // path is built from the store's own directory listing
+ if err != nil {
+ return meta{}, err
+ }
+ var m meta
+ if err = json.Unmarshal(data, &m); err != nil {
+ return meta{}, err
+ }
+ return m, nil
+}
diff --git a/fodc/agent/internal/pressureprofiler/storage_test.go b/fodc/agent/internal/pressureprofiler/storage_test.go
new file mode 100644
index 000000000..9d329ef3c
--- /dev/null
+++ b/fodc/agent/internal/pressureprofiler/storage_test.go
@@ -0,0 +1,128 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package pressureprofiler
+
+import (
+ "io"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// writeEvent creates a complete capture event with one heap profile of the given size.
+func writeEvent(t *testing.T, s *store, profileID string, rss uint64, size int) {
+ t.Helper()
+ dir := s.eventDir(profileID)
+ require.NoError(t, os.MkdirAll(dir, 0o750))
+ dest := filepath.Join(dir, "heap.pprof")
+ require.NoError(t, os.WriteFile(dest, make([]byte, size), 0o600))
+ require.NoError(t, s.finalize(profileID, meta{
+ CapturedAt: "2026-06-27T10:11:12.000000000Z",
+ RSSBytes: rss,
+ Profiles: []ProfileInfo{
+ {Type: "heap", Filename: "heap.pprof", Filepath: dest, Format: "pprof", SizeBytes: int64(size)},
+ },
+ }))
+}
+
+func profileIDs(records []ProfileRecord) map[string]bool {
+ out := make(map[string]bool, len(records))
+ for _, r := range records {
+ out[r.ProfileID] = true
+ }
+ return out
+}
+
+// TestRetentionByArtifactCount keeps the highest-RSS events within the count bound.
+func TestRetentionByArtifactCount(t *testing.T) {
+ s := newStore(t.TempDir(), 2, 0, nil)
+ writeEvent(t, s, "evt-rss-100", 100, 10)
+ writeEvent(t, s, "evt-rss-300", 300, 10)
+ writeEvent(t, s, "evt-rss-200", 200, 10)
+
+ kept := profileIDs(s.list())
+ assert.Len(t, kept, 2)
+ assert.True(t, kept["evt-rss-300"])
+ assert.True(t, kept["evt-rss-200"])
+ assert.False(t, kept["evt-rss-100"], "lowest-RSS event must be evicted")
+}
+
+// TestRetentionByDiskBound evicts the lowest-RSS events until the disk bound holds.
+func TestRetentionByDiskBound(t *testing.T) {
+ // 1000-byte disk cap; each event's profile is 400 bytes, so only 2 fit.
+ s := newStore(t.TempDir(), 100, 1000, nil)
+ writeEvent(t, s, "evt-rss-100", 100, 400)
+ writeEvent(t, s, "evt-rss-300", 300, 400)
+ writeEvent(t, s, "evt-rss-200", 200, 400)
+
+ kept := profileIDs(s.list())
+ assert.Len(t, kept, 2)
+ assert.True(t, kept["evt-rss-300"])
+ assert.True(t, kept["evt-rss-200"])
+}
+
+// TestListIgnoresIncompleteEvents only counts directories that have a meta.json.
+func TestListIgnoresIncompleteEvents(t *testing.T) {
+ s := newStore(t.TempDir(), 16, 0, nil)
+ writeEvent(t, s, "complete", 100, 10)
+ // An in-progress directory without meta.json must not be listed.
+ require.NoError(t, os.MkdirAll(s.eventDir("incomplete"), 0o750))
+ require.NoError(t, os.WriteFile(filepath.Join(s.eventDir("incomplete"), "heap.pprof"), []byte("x"), 0o600))
+
+ kept := profileIDs(s.list())
+ assert.Len(t, kept, 1)
+ assert.True(t, kept["complete"])
+}
+
+// TestOpenRejectsPathTraversal refuses to open files outside the storage directory.
+func TestOpenRejectsPathTraversal(t *testing.T) {
+ dir := t.TempDir()
+ s := newStore(dir, 16, 0, nil)
+ writeEvent(t, s, "evt", 100, 8)
+
+ f, err := s.open(filepath.Join(dir, "evt", "heap.pprof"))
+ require.NoError(t, err)
+ data, _ := io.ReadAll(f)
+ require.NoError(t, f.Close())
+ assert.Len(t, data, 8)
+
+ _, err = s.open(filepath.Join(dir, "..", "escape.pprof"))
+ assert.Error(t, err)
+ _, err = s.open("/etc/passwd")
+ assert.Error(t, err)
+}
+
+// TestSelfCheckPasses succeeds for a writable directory.
+func TestSelfCheckPasses(t *testing.T) {
+ s := newStore(t.TempDir(), 16, 0, nil)
+ require.NoError(t, s.selfCheck())
+}
+
+// TestSelfCheckRejectsUncreatableDir surfaces a directory that cannot be created. A path under
+// a regular file fails with ENOTDIR regardless of uid, so this is robust even when tests run
+// as root (where a chmod-based read-only directory would be bypassed).
+func TestSelfCheckRejectsUncreatableDir(t *testing.T) {
+ parent := t.TempDir()
+ filePath := filepath.Join(parent, "not-a-dir")
+ require.NoError(t, os.WriteFile(filePath, []byte("x"), 0o600))
+ s := newStore(filepath.Join(filePath, "sub"), 16, 0, nil)
+ assert.Error(t, s.selfCheck())
+}
diff --git a/fodc/agent/internal/proxy/client.go b/fodc/agent/internal/proxy/client.go
index 855194aca..0328d2ca3 100644
--- a/fodc/agent/internal/proxy/client.go
+++ b/fodc/agent/internal/proxy/client.go
@@ -39,6 +39,7 @@ import (
"github.com/apache/skywalking-banyandb/fodc/agent/internal/flightrecorder"
"github.com/apache/skywalking-banyandb/fodc/agent/internal/lifecycle"
"github.com/apache/skywalking-banyandb/fodc/agent/internal/metrics"
+ "github.com/apache/skywalking-banyandb/fodc/agent/internal/pressureprofiler"
"github.com/apache/skywalking-banyandb/pkg/logger"
"github.com/apache/skywalking-banyandb/pkg/panicdiag"
"github.com/apache/skywalking-banyandb/pkg/run"
@@ -72,6 +73,8 @@ type Client struct {
clusterStateStream fodcv1.FODCService_StreamClusterTopologyClient
lifecycleStream fodcv1.FODCService_StreamLifecycleClient
crashStream fodcv1.FODCService_StreamCrashDiagnosticsClient
+ pressureStream fodcv1.FODCService_StreamPressureProfilesClient
+ profileSource ProfileSource
client fodcv1.FODCServiceClient
reconnectFn func(context.Context) // overridable in tests; nil means use reconnect
@@ -101,6 +104,7 @@ func NewClient(
clusterCollector *cluster.Collector,
lifecycleCollector *lifecycle.Collector,
collectionLister crashcollector.CollectionLister,
+ profileSource ProfileSource,
logger *logger.Logger,
) *Client {
connMgr := newConnManager(proxyAddr, reconnectInterval, logger)
@@ -117,6 +121,7 @@ func NewClient(
clusterCollector: clusterCollector,
lifecycleCollector: lifecycleCollector,
collectionLister: collectionLister,
+ profileSource: profileSource,
logger: logger,
stopCh: make(chan struct{}),
reconnectCh: make(chan struct{}, 1),
@@ -597,6 +602,231 @@ func (c *Client) handleCrashStream(ctx context.Context, stream fodcv1.FODCServic
}
}
+// pressureChunkSize bounds each pprof download chunk so a single gRPC message stays
+// far below the server's max-message-size regardless of profile size.
+const pressureChunkSize = 1 << 20 // 1MB
+
+// ProfileSource is the read side of the pressure profiler the proxy client serves:
+// it lists capture-event metadata and opens a profile file for chunked download.
+type ProfileSource interface {
+ ListProfileRecords() []pressureprofiler.ProfileRecord
+ OpenProfile(path string) (io.ReadCloser, error)
+}
+
+// StartPressureProfilesStream establishes the bi-directional pressure-profiles stream with Proxy.
+func (c *Client) StartPressureProfilesStream(ctx context.Context) error {
+ c.streamsMu.Lock()
+ if c.client == nil {
+ c.streamsMu.Unlock()
+ return fmt.Errorf("client not connected, call Connect() first")
+ }
+ client := c.client
+ agentID := c.agentID
+ c.streamsMu.Unlock()
+
+ if agentID == "" {
+ return fmt.Errorf("agent ID not available, register agent first")
+ }
+
+ md := metadata.New(map[string]string{"agent_id": agentID})
+ ctxWithMetadata := metadata.NewOutgoingContext(ctx, md)
+
+ stream, streamErr := client.StreamPressureProfiles(ctxWithMetadata)
+ if streamErr != nil {
+ return fmt.Errorf("failed to create pressure profiles stream: %w", streamErr)
+ }
+
+ c.streamsMu.Lock()
+ c.pressureStream = stream
+ c.streamsMu.Unlock()
+
+ run.Go(ctx, "fodc.agent.proxy.pressure-stream", c.logger, func(ctx context.Context) {
+ c.handlePressureProfilesStream(ctx, stream)
+ })
+
+ c.logger.Info().Str("agent_id", agentID).Msg("Pressure profiles stream established with Proxy")
+ return nil
+}
+
+// handlePressureProfilesStream serves proxy commands on the pressure-profiles stream:
+// list metadata, or stream one profile's bytes.
+func (c *Client) handlePressureProfilesStream(ctx context.Context, stream fodcv1.FODCService_StreamPressureProfilesClient) {
+ c.streamsMu.RLock()
+ stopCh := c.stopCh
+ c.streamsMu.RUnlock()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-stopCh:
+ return
+ default:
+ }
+ resp, recvErr := stream.Recv()
+ if errors.Is(recvErr, io.EOF) {
+ c.logger.Warn().Msg("Pressure profiles stream closed by Proxy, reconnecting...")
+ run.Go(ctx, "fodc.agent.proxy.reconnect", c.logger, func(ctx context.Context) {
+ c.reconnect(ctx)
+ })
+ return
+ }
+ if recvErr != nil {
+ c.streamsMu.RLock()
+ disconnected := c.disconnected
+ c.streamsMu.RUnlock()
+ if disconnected {
+ c.logger.Debug().Err(recvErr).Msg("Pressure profiles stream closed")
+ return
+ }
+ c.logger.Error().Err(recvErr).Msg("Error receiving from pressure profiles stream, reconnecting...")
+ run.Go(ctx, "fodc.agent.proxy.reconnect", c.logger, func(ctx context.Context) {
+ c.reconnect(ctx)
+ })
+ return
+ }
+ if resp == nil {
+ continue
+ }
+ switch cmd := resp.Command.(type) {
+ case *fodcv1.StreamPressureProfilesResponse_ListProfiles:
+ if sendErr := c.sendProfileRecords(stream, cmd.ListProfiles.GetRequestId()); sendErr != nil {
+ c.logger.Error().Err(sendErr).Msg("Failed to send pressure profile records to proxy")
+ }
+ case *fodcv1.StreamPressureProfilesResponse_FetchProfile:
+ if sendErr := c.sendProfileChunks(stream, cmd.FetchProfile); sendErr != nil {
+ c.logger.Error().Err(sendErr).Msg("Failed to send pressure profile chunks to proxy")
+ }
+ }
+ }
+}
+
+// sendProfileRecords answers a list_profiles command with one metadata record per complete event.
+func (c *Client) sendProfileRecords(stream fodcv1.FODCService_StreamPressureProfilesClient, requestID string) error {
+ c.streamsMu.RLock()
+ source := c.profileSource
+ disconnected := c.disconnected
+ current := c.pressureStream
+ c.streamsMu.RUnlock()
+ if disconnected || current != stream {
+ return fmt.Errorf("pressure profiles stream not established")
+ }
+
+ if source != nil {
+ for _, record := range source.ListProfileRecords() {
+ req := &fodcv1.StreamPressureProfilesRequest{
+ Payload: &fodcv1.StreamPressureProfilesRequest_Record{Record: toProtoRecord(record)},
+ }
+ if sendErr := c.sendPressureRequest(stream, req); sendErr != nil {
+ return sendErr
+ }
+ }
+ }
+
+ // Always signal completion (including the zero-record / nil-source case) so the proxy
+ // returns as soon as this agent is done instead of waiting out its timeout.
+ done := &fodcv1.StreamPressureProfilesRequest{
+ Payload: &fodcv1.StreamPressureProfilesRequest_ListComplete{
+ ListComplete: &fodcv1.ListComplete{RequestId: requestID},
+ },
+ }
+ return c.sendPressureRequest(stream, done)
+}
+
+// sendProfileChunks answers a fetch_profile command by streaming one profile's bytes
+// in bounded chunks; a non-empty chunk error reports a file that cannot be served.
+func (c *Client) sendProfileChunks(stream fodcv1.FODCService_StreamPressureProfilesClient, fetch *fodcv1.FetchPressureProfile) error {
+ c.streamsMu.RLock()
+ source := c.profileSource
+ c.streamsMu.RUnlock()
+ if source == nil {
+ return c.sendPressureRequest(stream, chunkError(fetch, "pressure profiler not available"))
+ }
+
+ file, openErr := source.OpenProfile(fetch.Filepath)
+ if openErr != nil {
+ return c.sendPressureRequest(stream, chunkError(fetch, openErr.Error()))
+ }
+ defer func() { _ = file.Close() }()
+
+ buf := make([]byte, pressureChunkSize)
+ for {
+ n, readErr := file.Read(buf)
+ isEOF := errors.Is(readErr, io.EOF)
+ if n > 0 || isEOF {
+ chunk := &fodcv1.PressureProfileChunk{
+ RequestId: fetch.RequestId,
+ ProfileId: fetch.ProfileId,
+ Type: fetch.Type,
+ Data: buf[:n],
+ Last: isEOF,
+ }
+ req := &fodcv1.StreamPressureProfilesRequest{
+ Payload: &fodcv1.StreamPressureProfilesRequest_Chunk{Chunk: chunk},
+ }
+ if sendErr := c.sendPressureRequest(stream, req); sendErr != nil {
+ return sendErr
+ }
+ }
+ if isEOF {
+ return nil
+ }
+ if readErr != nil {
+ return c.sendPressureRequest(stream, chunkError(fetch, readErr.Error()))
+ }
+ }
+}
+
+// sendPressureRequest sends one message on the pressure stream, guarding against a
+// stream that has been swapped out by a concurrent reconnect.
+func (c *Client) sendPressureRequest(stream fodcv1.FODCService_StreamPressureProfilesClient, req *fodcv1.StreamPressureProfilesRequest) error {
+ c.streamsMu.Lock()
+ defer c.streamsMu.Unlock()
+ if c.pressureStream != stream {
+ return fmt.Errorf("pressure profiles stream changed during send")
+ }
+ if sendErr := stream.Send(req); sendErr != nil {
+ return fmt.Errorf("failed to send pressure profiles message: %w", sendErr)
+ }
+ return nil
+}
+
+func chunkError(fetch *fodcv1.FetchPressureProfile, msg string) *fodcv1.StreamPressureProfilesRequest {
+ return &fodcv1.StreamPressureProfilesRequest{
+ Payload: &fodcv1.StreamPressureProfilesRequest_Chunk{
+ Chunk: &fodcv1.PressureProfileChunk{
+ RequestId: fetch.RequestId,
+ ProfileId: fetch.ProfileId,
+ Type: fetch.Type,
+ Error: msg,
+ Last: true,
+ },
+ },
+ }
+}
+
+func toProtoRecord(record pressureprofiler.ProfileRecord) *fodcv1.PressureProfileRecord {
+ profiles := make([]*fodcv1.PressureProfileInfo, 0, len(record.Profiles))
+ for _, p := range record.Profiles {
+ profiles = append(profiles, &fodcv1.PressureProfileInfo{
+ Type: p.Type,
+ Filename: p.Filename,
+ Filepath: p.Filepath,
+ Format: p.Format,
+ SizeBytes: p.SizeBytes,
+ })
+ }
+ return &fodcv1.PressureProfileRecord{
+ ProfileId: record.ProfileID,
+ CapturedAt: timestamppb.New(record.CapturedAt),
+ SourceEndpoint: record.SourceEndpoint,
+ RssBytes: record.RSSBytes,
+ CgroupLimitBytes: record.CgroupLimitBytes,
+ TriggerPercent: record.TriggerPercent,
+ ThresholdBytes: record.ThresholdBytes,
+ Profiles: profiles,
+ }
+}
+
// handleLifecycleStream handles the lifecycle stream.
func (c *Client) handleLifecycleStream(ctx context.Context, stream fodcv1.FODCService_StreamLifecycleClient) {
c.streamsMu.RLock()
@@ -1025,6 +1255,12 @@ func (c *Client) cleanupStreams() {
}
c.crashStream = nil
}
+ if c.pressureStream != nil {
+ if closeErr := c.pressureStream.CloseSend(); closeErr != nil {
+ c.logger.Warn().Err(closeErr).Msg("Error closing pressure profiles stream")
+ }
+ c.pressureStream = nil
+ }
c.client = nil
c.streamsMu.Unlock()
}
@@ -1088,6 +1324,12 @@ func (c *Client) Disconnect() error {
}
c.crashStream = nil
}
+ if c.pressureStream != nil {
+ if closeErr := c.pressureStream.CloseSend(); closeErr != nil {
+ c.logger.Warn().Err(closeErr).Msg("Error closing pressure profiles stream")
+ }
+ c.pressureStream = nil
+ }
c.streamsMu.Unlock()
c.connManager.stop()
@@ -1163,6 +1405,15 @@ func (c *Client) Start(ctx context.Context) error {
}
}
+ if c.profileSource != nil {
+ if pressureErr := c.StartPressureProfilesStream(ctx); pressureErr != nil {
+ c.logger.Error().Err(pressureErr).Msg("Failed to start pressure profiles stream, reconnecting...")
+ c.cleanupStreams()
+ time.Sleep(c.reconnectInterval)
+ continue
+ }
+ }
+
c.logger.Info().Msg("Proxy client started successfully")
return nil
}
@@ -1329,6 +1580,10 @@ func (c *Client) reconnect(ctx context.Context) {
_ = c.crashStream.CloseSend()
c.crashStream = nil
}
+ if c.pressureStream != nil {
+ _ = c.pressureStream.CloseSend()
+ c.pressureStream = nil
+ }
c.streamsMu.Unlock()
connResultCh := c.connManager.RequestConnect(ctx)
@@ -1394,6 +1649,14 @@ func (c *Client) reconnect(ctx context.Context) {
}
}
+ if c.profileSource != nil {
+ if pressureErr := c.StartPressureProfilesStream(ctx); pressureErr != nil {
+ c.logger.Error().Err(pressureErr).Msg("Failed to restart pressure profiles stream; will retry")
+ c.scheduleReconnect(ctx)
+ return
+ }
+ }
+
c.logger.Info().Msg("Successfully reconnected to Proxy")
}
diff --git a/fodc/agent/internal/proxy/client_blocking_send_test.go b/fodc/agent/internal/proxy/client_blocking_send_test.go
index 28b8adc67..49f44274a 100644
--- a/fodc/agent/internal/proxy/client_blocking_send_test.go
+++ b/fodc/agent/internal/proxy/client_blocking_send_test.go
@@ -55,7 +55,7 @@ func TestProxyClient_SendHeartbeat_RespectsCtxOnBlockingSend(t *testing.T) {
fr := flightrecorder.NewFlightRecorder(1000000)
pc := NewProxyClient(
"localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"},
- nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger,
+ nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger,
)
streamCtx, streamCancel := context.WithCancel(context.Background())
@@ -108,7 +108,7 @@ func TestProxyClient_reconnect_DeadlocksWhenHeartbeatBlockedOnSend(t *testing.T)
fr := flightrecorder.NewFlightRecorder(1000000)
pc := NewProxyClient(
"localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"},
- nil, 10*time.Millisecond, 100*time.Millisecond, fr, nil, nil, nil, testLogger,
+ nil, 10*time.Millisecond, 100*time.Millisecond, fr, nil, nil, nil, nil, testLogger,
)
bgCtx, bgCancel := context.WithCancel(context.Background())
diff --git a/fodc/agent/internal/proxy/client_test.go b/fodc/agent/internal/proxy/client_test.go
index b88e77726..afb08aeaa 100644
--- a/fodc/agent/internal/proxy/client_test.go
+++ b/fodc/agent/internal/proxy/client_test.go
@@ -88,6 +88,10 @@ func (m *mockFODCServiceClient) StreamCrashDiagnostics(_ context.Context, _ ...g
return nil, errors.New("not implemented")
}
+func (m *mockFODCServiceClient) StreamPressureProfiles(_ context.Context, _ ...grpc.CallOption) (fodcv1.FODCService_StreamPressureProfilesClient, error) {
+ return nil, nil
+}
+
// mockRegisterAgentClient implements fodcv1.FODCService_RegisterAgentClient for testing.
// When sendBlock is non-nil, Send blocks on it until the channel is closed (used by tests
// that reproduce the wedged-Send scenario). When sendEntered is non-nil, it is closed once
@@ -381,6 +385,7 @@ func TestNewProxyClient(t *testing.T) {
nil,
nil,
nil,
+ nil,
testLogger,
)
@@ -400,7 +405,7 @@ func TestNewProxyClient(t *testing.T) {
func TestProxyClient_Connect_Success(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -428,7 +433,7 @@ func TestProxyClient_Connect_Success(t *testing.T) {
func TestProxyClient_Connect_AlreadyConnected(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -449,7 +454,7 @@ func TestProxyClient_Connect_AlreadyConnected(t *testing.T) {
func TestProxyClient_Connect_Reconnection(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -485,7 +490,7 @@ func TestProxyClient_Connect_Reconnection(t *testing.T) {
func TestProxyClient_StartRegistrationStream_NotConnected(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
err := pc.StartRegistrationStream(ctx)
@@ -499,7 +504,7 @@ func TestProxyClient_StartRegistrationStream_Success(t *testing.T) {
fr := flightrecorder.NewFlightRecorder(1000000)
pc := NewProxyClient(
"localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, map[string]string{"env": "test"},
- 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
mockClient := &mockFODCServiceClient{}
@@ -533,7 +538,7 @@ func TestProxyClient_StartRegistrationStream_Success(t *testing.T) {
func TestProxyClient_StartRegistrationStream_StreamError(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
mockClient := &mockFODCServiceClient{}
@@ -554,7 +559,7 @@ func TestProxyClient_StartRegistrationStream_StreamError(t *testing.T) {
func TestProxyClient_StartRegistrationStream_SendError(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
mockClient := &mockFODCServiceClient{}
@@ -578,7 +583,7 @@ func TestProxyClient_StartRegistrationStream_SendError(t *testing.T) {
func TestProxyClient_StartRegistrationStream_RecvError(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
mockClient := &mockFODCServiceClient{}
@@ -602,7 +607,7 @@ func TestProxyClient_StartRegistrationStream_RecvError(t *testing.T) {
func TestProxyClient_StartRegistrationStream_RegistrationFailed(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
mockClient := &mockFODCServiceClient{}
@@ -631,7 +636,7 @@ func TestProxyClient_StartRegistrationStream_RegistrationFailed(t *testing.T) {
func TestProxyClient_StartRegistrationStream_MissingAgentID(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
mockClient := &mockFODCServiceClient{}
@@ -660,7 +665,7 @@ func TestProxyClient_StartRegistrationStream_MissingAgentID(t *testing.T) {
func TestProxyClient_StartMetricsStream_NotConnected(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
err := pc.StartMetricsStream(ctx)
@@ -672,7 +677,7 @@ func TestProxyClient_StartMetricsStream_NotConnected(t *testing.T) {
func TestProxyClient_StartMetricsStream_NoAgentID(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
mockClient := &mockFODCServiceClient{}
pc.streamsMu.Lock()
@@ -689,7 +694,7 @@ func TestProxyClient_StartMetricsStream_NoAgentID(t *testing.T) {
func TestProxyClient_StartMetricsStream_Success(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
mockClient := &mockFODCServiceClient{}
@@ -722,7 +727,7 @@ func TestProxyClient_StartMetricsStream_Success(t *testing.T) {
func TestProxyClient_StartMetricsStream_StreamError(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
mockClient := &mockFODCServiceClient{}
@@ -744,7 +749,7 @@ func TestProxyClient_StartMetricsStream_StreamError(t *testing.T) {
func TestProxyClient_StartClusterStateStream_NotConnected(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
err := pc.StartClusterStateStream(ctx)
@@ -756,7 +761,7 @@ func TestProxyClient_StartClusterStateStream_NotConnected(t *testing.T) {
func TestProxyClient_StartClusterStateStream_NoAgentID(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
mockClient := &mockFODCServiceClient{}
pc.streamsMu.Lock()
@@ -773,7 +778,7 @@ func TestProxyClient_StartClusterStateStream_NoAgentID(t *testing.T) {
func TestProxyClient_StartClusterStateStream_Success(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
mockClient := &mockFODCServiceClient{}
@@ -806,7 +811,7 @@ func TestProxyClient_StartClusterStateStream_Success(t *testing.T) {
func TestProxyClient_StartClusterStateStream_StreamError(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
mockClient := &mockFODCServiceClient{}
@@ -828,7 +833,7 @@ func TestProxyClient_StartClusterStateStream_StreamError(t *testing.T) {
func TestProxyClient_SendClusterTopology_NoStream(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
err := pc.sendClusterTopology()
@@ -859,7 +864,7 @@ func TestProxyClient_SendClusterTopology_Success(t *testing.T) {
}
collector.SetClusterTopology(testTopology)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, collector, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, collector, nil, nil, nil, testLogger)
ctx := context.Background()
mockStream := newMockStreamClusterStateClient(ctx)
@@ -883,7 +888,7 @@ func TestProxyClient_SendClusterTopology_Success(t *testing.T) {
func TestProxyClient_SendHeartbeat_NoStream(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
err := pc.SendHeartbeat(ctx)
@@ -898,7 +903,7 @@ func TestProxyClient_SendHeartbeat_Success(t *testing.T) {
pc := NewProxyClient(
"localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"},
map[string]string{"env": "test"},
- 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
mockStream := newMockRegisterAgentClient(ctx)
@@ -919,7 +924,7 @@ func TestProxyClient_SendHeartbeat_Success(t *testing.T) {
func TestProxyClient_SendHeartbeat_SendError(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
mockStream := newMockRegisterAgentClient(ctx)
@@ -938,7 +943,7 @@ func TestProxyClient_SendHeartbeat_SendError(t *testing.T) {
func TestProxyClient_RetrieveAndSendMetrics_NoStream(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
err := pc.RetrieveAndSendMetrics(ctx, nil)
@@ -950,7 +955,7 @@ func TestProxyClient_RetrieveAndSendMetrics_NoStream(t *testing.T) {
func TestProxyClient_RetrieveAndSendMetrics_NoDatasources(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
mockStream := newMockStreamMetricsClient(ctx)
@@ -972,7 +977,7 @@ func TestProxyClient_RetrieveAndSendMetrics_NoDatasources(t *testing.T) {
func TestProxyClient_RetrieveAndSendMetrics_LatestMetrics(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
// Add metrics to flight recorder
rawMetrics := []metrics.RawMetric{
@@ -1014,7 +1019,7 @@ func TestProxyClient_RetrieveAndSendMetrics_LatestMetrics(t *testing.T) {
func TestProxyClient_RetrieveAndSendMetrics_FilteredMetrics(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
// Add metrics with timestamps
rawMetrics := []metrics.RawMetric{
@@ -1062,7 +1067,7 @@ func TestProxyClient_RetrieveAndSendMetrics_FilteredMetrics(t *testing.T) {
func TestProxyClient_RetrieveAndSendMetrics_FilteredNoTimestamps(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
// Add metrics with timestamps far in the past
// Then filter for a future time window to ensure no matches
@@ -1106,7 +1111,7 @@ func TestProxyClient_RetrieveAndSendMetrics_FilteredNoTimestamps(t *testing.T) {
func TestProxyClient_Disconnect_Success(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -1155,7 +1160,7 @@ func TestProxyClient_Disconnect_Success(t *testing.T) {
func TestProxyClient_Disconnect_Idempotent(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
pc.streamsMu.Lock()
pc.disconnected = true
@@ -1172,7 +1177,7 @@ func TestProxyClient_Disconnect_Idempotent(t *testing.T) {
func TestProxyClient_handleRegistrationStream_EOF(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -1188,7 +1193,7 @@ func TestProxyClient_handleRegistrationStream_EOF(t *testing.T) {
func TestProxyClient_handleRegistrationStream_ContextCanceled(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx, cancel := context.WithCancel(context.Background())
cancel()
@@ -1204,7 +1209,7 @@ func TestProxyClient_handleRegistrationStream_ContextCanceled(t *testing.T) {
func TestProxyClient_handleMetricsStream_EOF(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -1220,7 +1225,7 @@ func TestProxyClient_handleMetricsStream_EOF(t *testing.T) {
func TestProxyClient_handleMetricsStream_RequestMetrics(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
// Add metrics
rawMetrics := []metrics.RawMetric{
@@ -1266,7 +1271,7 @@ func TestProxyClient_handleMetricsStream_RequestMetrics(t *testing.T) {
func TestProxyClient_parseMetricKey_Simple(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
key, err := pc.parseMetricKey("cpu_usage")
@@ -1278,7 +1283,7 @@ func TestProxyClient_parseMetricKey_Simple(t *testing.T) {
func TestProxyClient_parseMetricKey_WithLabels(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
key, err := pc.parseMetricKey(`http_requests_total{method="GET",status="200"}`)
@@ -1290,7 +1295,7 @@ func TestProxyClient_parseMetricKey_WithLabels(t *testing.T) {
func TestProxyClient_parseMetricKey_InvalidFormat(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
key, err := pc.parseMetricKey("invalid{format")
@@ -1302,7 +1307,7 @@ func TestProxyClient_parseMetricKey_InvalidFormat(t *testing.T) {
func TestProxyClient_parseMetricKey_MalformedLabels(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
// Test with malformed labels - should still parse what it can
key, err := pc.parseMetricKey(`metric{invalid,key="value"}`)
@@ -1316,7 +1321,7 @@ func TestProxyClient_parseMetricKey_MalformedLabels(t *testing.T) {
func TestProxyClient_sendLatestMetrics_WithUnfinalizedValue(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
// Create a datasource with metrics
ds := flightrecorder.NewDatasource()
@@ -1351,7 +1356,7 @@ func TestProxyClient_sendLatestMetrics_WithUnfinalizedValue(t *testing.T) {
func TestProxyClient_sendFilteredMetrics_TimeWindow(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
// Create a datasource with metrics and timestamps
ds := flightrecorder.NewDatasource()
@@ -1401,7 +1406,7 @@ func TestProxyClient_sendFilteredMetrics_TimeWindow(t *testing.T) {
func TestProxyClient_sendFilteredMetrics_NoMatchingTimeWindow(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
// Create a datasource with metrics and timestamps
ds := flightrecorder.NewDatasource()
@@ -1448,7 +1453,8 @@ func TestProxyClient_sendFilteredMetrics_NoMatchingTimeWindow(t *testing.T) {
func TestProxyClient_Start_ContextCancellation(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("invalid-address:99999", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 100*time.Millisecond, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("invalid-address:99999", "datanode-hot", "192.168.1.1", []string{"data"}, nil,
+ 5*time.Second, 100*time.Millisecond, fr, nil, nil, nil, nil, testLogger)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -1465,7 +1471,8 @@ func TestProxyClient_Start_ContextCancellation(t *testing.T) {
func TestProxyClient_Start_StopChannel(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("invalid-address:99999", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 5*time.Second, 100*time.Millisecond, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("invalid-address:99999", "datanode-hot", "192.168.1.1", []string{"data"}, nil,
+ 5*time.Second, 100*time.Millisecond, fr, nil, nil, nil, nil, testLogger)
ctx := context.Background()
@@ -1480,7 +1487,7 @@ func TestProxyClient_Start_StopChannel(t *testing.T) {
func TestProxyClient_startHeartbeat_Success(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 100*time.Millisecond, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 100*time.Millisecond, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -1513,7 +1520,7 @@ func TestProxyClient_startHeartbeat_Success(t *testing.T) {
func TestProxyClient_startHeartbeat_ReplacesExistingTicker(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
- pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 100*time.Millisecond, 10*time.Second, fr, nil, nil, nil, testLogger)
+ pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil, 100*time.Millisecond, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -1542,7 +1549,7 @@ func TestProxyClient_reconnect_NoDeadlockWithActiveHeartbeat(t *testing.T) {
testLogger := initTestLogger(t)
fr := flightrecorder.NewFlightRecorder(1000000)
pc := NewProxyClient("localhost:8080", "datanode-hot", "192.168.1.1", []string{"data"}, nil,
- 100*time.Millisecond, 10*time.Second, fr, nil, nil, nil, testLogger)
+ 100*time.Millisecond, 10*time.Second, fr, nil, nil, nil, nil, testLogger)
// Use a short-lived context: reconnect now retries with backoff, so we cancel
// the context after enough time for cleanupStreams() to prove no deadlock.
diff --git a/fodc/agent/internal/watchdog/watchdog.go b/fodc/agent/internal/watchdog/watchdog.go
index 346a3a95d..bbb0bdafc 100644
--- a/fodc/agent/internal/watchdog/watchdog.go
+++ b/fodc/agent/internal/watchdog/watchdog.go
@@ -59,6 +59,7 @@ type Watchdog struct {
ctx context.Context
recorder MetricsRecorder
nodeInfo func() (role string, labels map[string]string)
+ postPollHooks []func(ctx context.Context)
log *logger.Logger
cancel context.CancelFunc
client *http.Client
@@ -101,6 +102,15 @@ func (w *Watchdog) SetNodeInfoProvider(fn func() (role string, labels map[string
w.mu.Unlock()
}
+// AddPostPollHook registers a callback invoked after each successful metrics poll is forwarded
+// to the recorder. Multiple hooks may be registered; they run in registration order on the poll
+// goroutine, so each must return quickly and offload any slow work to its own goroutine.
+func (w *Watchdog) AddPostPollHook(fn func(ctx context.Context)) {
+ w.mu.Lock()
+ w.postPollHooks = append(w.postPollHooks, fn)
+ w.mu.Unlock()
+}
+
// resolveNodeInfo returns the current node role and labels from the live provider, falling back
// to the static role captured at construction when no provider is set. The first resolved
// identity is cached and "sticks": if the provider later regresses to an unresolved role
@@ -320,6 +330,14 @@ func (w *Watchdog) pollAndForward(ctx context.Context) (context.Context, error)
"metric_count": fmt.Sprintf("%d", len(rawMetrics)),
})
+ w.mu.RLock()
+ hooks := make([]func(context.Context), len(w.postPollHooks))
+ copy(hooks, w.postPollHooks)
+ w.mu.RUnlock()
+ for _, hook := range hooks {
+ hook(ctx)
+ }
+
w.log.Info().Int("count", len(rawMetrics)).Msg("Successfully polled and forwarded metrics")
return ctx, nil
}
diff --git a/fodc/agent/testhelper/flightrecorder.go b/fodc/agent/testhelper/flightrecorder.go
index e06170cd7..0f05358d2 100644
--- a/fodc/agent/testhelper/flightrecorder.go
+++ b/fodc/agent/testhelper/flightrecorder.go
@@ -180,6 +180,7 @@ func NewProxyClientWithCollector(
collector,
nil,
nil,
+ nil,
logger,
)
}
@@ -298,6 +299,7 @@ func NewProxyClientWrapper(
clusterCollector,
lifecycleCollector,
nil,
+ nil,
logger,
)
return &ProxyClientWrapper{
@@ -338,6 +340,7 @@ func NewProxyClientWrapperWithCrashDir(
clusterCollector,
nil,
crashWatcher,
+ nil,
logger,
)
return &ProxyClientWrapper{
diff --git a/fodc/agent/testhelper/pressureprofiler.go b/fodc/agent/testhelper/pressureprofiler.go
new file mode 100644
index 000000000..b4c7e915b
--- /dev/null
+++ b/fodc/agent/testhelper/pressureprofiler.go
@@ -0,0 +1,110 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package testhelper
+
+import (
+ "context"
+ "time"
+
+ "github.com/prometheus/client_golang/prometheus"
+
+ "github.com/apache/skywalking-banyandb/fodc/agent/internal/flightrecorder"
+ "github.com/apache/skywalking-banyandb/fodc/agent/internal/pressureprofiler"
+ "github.com/apache/skywalking-banyandb/fodc/agent/internal/proxy"
+ "github.com/apache/skywalking-banyandb/fodc/agent/internal/watchdog"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+ "github.com/apache/skywalking-banyandb/pkg/meter"
+ "github.com/apache/skywalking-banyandb/pkg/meter/prom"
+)
+
+// PressureAgentConfig configures a real agent stack wired for memory-pressure pprof capture.
+type PressureAgentConfig struct {
+ Logger *logger.Logger
+ ProxyAddr string
+ PodName string
+ Role string
+ MetricsURL string
+ PprofPort string
+ Dir string
+ Cooldown time.Duration
+ TriggerPercent int
+}
+
+// PressureAgent bundles a real watchdog + flight recorder + pressure profiler + proxy client,
+// wired exactly as the agent does in production, for end-to-end integration tests. Only the
+// monitored BanyanDB node is external (addressed by MetricsURL / PprofPort).
+type PressureAgent struct {
+ client *proxy.Client
+ wd *watchdog.Watchdog
+}
+
+// NewPressureAgent builds and starts the agent stack: the watchdog polls cfg.MetricsURL into a
+// flight recorder, the profiler evaluates on each poll and captures from cfg.PprofPort, and the
+// proxy client exposes the captured profiles to the proxy. The caller drives the connection with
+// Connect/StartRegistrationStream/StartPressureProfilesStream and tears it down with Stop.
+func NewPressureAgent(ctx context.Context, cfg PressureAgentConfig) (*PressureAgent, error) {
+ fr := flightrecorder.NewFlightRecorder(10 * 1024 * 1024)
+ wd := watchdog.NewWatchdogWithConfig(fr, []string{cfg.MetricsURL}, 200*time.Millisecond,
+ cfg.Role, cfg.PodName, []string{cfg.Role})
+ provider := prom.NewProvider(meter.NewHierarchicalScope("fodc_agent", "_"), prometheus.NewRegistry())
+ pp, err := pressureprofiler.New(pressureprofiler.Config{
+ Dir: cfg.Dir,
+ PprofPort: cfg.PprofPort,
+ PodName: cfg.PodName,
+ RoleProvider: func() string { return cfg.Role },
+ Cooldown: cfg.Cooldown,
+ TriggerPercent: cfg.TriggerPercent,
+ MaxArtifacts: 16,
+ }, fr, provider, cfg.Logger)
+ if err != nil {
+ return nil, err
+ }
+ wd.AddPostPollHook(pp.OnPollComplete)
+ if preRunErr := wd.PreRun(ctx); preRunErr != nil {
+ return nil, preRunErr
+ }
+ wd.Serve()
+
+ client := proxy.NewClient(cfg.ProxyAddr, cfg.Role, cfg.PodName, []string{cfg.Role},
+ map[string]string{"role": cfg.Role}, 2*time.Second, 1*time.Second, fr, nil, nil, nil, pp, cfg.Logger)
+ return &PressureAgent{client: client, wd: wd}, nil
+}
+
+// Connect starts the connection manager and connects the proxy client.
+func (a *PressureAgent) Connect(ctx context.Context) error {
+ a.client.StartConnManager(ctx)
+ return a.client.Connect(ctx)
+}
+
+// StartRegistrationStream starts the agent registration stream.
+func (a *PressureAgent) StartRegistrationStream(ctx context.Context) error {
+ return a.client.StartRegistrationStream(ctx)
+}
+
+// StartPressureProfilesStream starts the pressure profiles stream.
+func (a *PressureAgent) StartPressureProfilesStream(ctx context.Context) error {
+ return a.client.StartPressureProfilesStream(ctx)
+}
+
+// Stop tears the agent down. Disconnect runs first so the proxy client is marked disconnected
+// before its streams error out, preventing a spurious reconnect goroutine (which would race the
+// suite's goroutine-leak check); then the watchdog is stopped.
+func (a *PressureAgent) Stop() {
+ _ = a.client.Disconnect()
+ a.wd.GracefulStop()
+}
diff --git a/fodc/internal/pprofcapture/pprofcapture.go b/fodc/internal/pprofcapture/pprofcapture.go
new file mode 100644
index 000000000..fc40e5ada
--- /dev/null
+++ b/fodc/internal/pprofcapture/pprofcapture.go
@@ -0,0 +1,44 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Package pprofcapture defines the canonical set of pprof profiles the FODC agent captures
+// under memory pressure. It is shared so the agent (which fetches them) and the proxy (which
+// validates download requests) agree on a single source of truth for the profile types.
+package pprofcapture
+
+// Target describes one pprof endpoint captured on every memory-pressure trigger.
+type Target struct {
+ Type string // "heap" | "goroutine"
+ Path string // request path under the pprof base, e.g. "/debug/pprof/heap"
+}
+
+// Targets are the profiles pulled on every trigger: a heap snapshot and a full goroutine
+// dump (debug=0 keeps the compact gzip-protobuf form for go tool pprof).
+var Targets = []Target{
+ {Type: "heap", Path: "/debug/pprof/heap"},
+ {Type: "goroutine", Path: "/debug/pprof/goroutine?debug=0"},
+}
+
+// IsValidType reports whether t is one of the captured profile types.
+func IsValidType(t string) bool {
+ for _, target := range Targets {
+ if target.Type == t {
+ return true
+ }
+ }
+ return false
+}
diff --git a/fodc/proxy/cmd/proxy/main.go b/fodc/proxy/cmd/proxy/main.go
index 2c36bd145..e5122714e 100644
--- a/fodc/proxy/cmd/proxy/main.go
+++ b/fodc/proxy/cmd/proxy/main.go
@@ -33,6 +33,7 @@ import (
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/grpc"
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/lifecycle"
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/metrics"
+ "github.com/apache/skywalking-banyandb/fodc/proxy/internal/pressure"
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/registry"
"github.com/apache/skywalking-banyandb/pkg/logger"
"github.com/apache/skywalking-banyandb/pkg/version"
@@ -129,12 +130,15 @@ func runProxy(_ *cobra.Command, _ []string) error {
metricsAggregator := metrics.NewAggregator(agentRegistry, nil, log)
diagnosticsAggregator := diagnostics.NewAggregator(agentRegistry, nil, log)
+ pressureAggregator := pressure.NewAggregator(agentRegistry, nil, log)
- grpcService := grpc.NewFODCService(agentRegistry, metricsAggregator, clusterStateMgr, lifecycleMgr, diagnosticsAggregator, log, heartbeatInterval)
+ grpcService := grpc.NewFODCService(agentRegistry, metricsAggregator, clusterStateMgr, lifecycleMgr,
+ diagnosticsAggregator, pressureAggregator, log, heartbeatInterval)
metricsAggregator.SetGRPCService(grpcService)
clusterStateMgr.SetGRPCService(grpcService)
lifecycleMgr.SetGRPCService(grpcService)
diagnosticsAggregator.SetGRPCService(grpcService)
+ pressureAggregator.SetGRPCService(grpcService)
grpcServer := grpc.NewServer(grpcService, grpcListenAddr, grpcMaxMsgSize, log)
if startErr := grpcServer.Start(); startErr != nil {
@@ -142,7 +146,8 @@ func runProxy(_ *cobra.Command, _ []string) error {
}
defer grpcServer.Stop()
- apiServer := api.NewServer(metricsAggregator, clusterStateMgr, lifecycleMgr, agentRegistry, diagnosticsAggregator, log)
+ apiServer := api.NewServer(metricsAggregator, clusterStateMgr, lifecycleMgr, agentRegistry,
+ diagnosticsAggregator, pressureAggregator, grpcService, log)
if startErr := apiServer.Start(httpListenAddr, httpReadTimeout, httpWriteTimeout); startErr != nil {
return fmt.Errorf("failed to start HTTP API server: %w", startErr)
}
diff --git a/fodc/proxy/internal/api/server.go b/fodc/proxy/internal/api/server.go
index a8b864be6..4194c6bfe 100644
--- a/fodc/proxy/internal/api/server.go
+++ b/fodc/proxy/internal/api/server.go
@@ -28,13 +28,16 @@ import (
"strings"
"time"
+ "github.com/google/uuid"
"google.golang.org/protobuf/encoding/protojson"
fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+ "github.com/apache/skywalking-banyandb/fodc/internal/pprofcapture"
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/cluster"
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/diagnostics"
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/lifecycle"
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/metrics"
+ "github.com/apache/skywalking-banyandb/fodc/proxy/internal/pressure"
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/registry"
"github.com/apache/skywalking-banyandb/pkg/logger"
)
@@ -48,12 +51,19 @@ var lifecycleGroupMarshaler = protojson.MarshalOptions{
EmitUnpopulated: true,
}
+// ProfileFetcher streams one pressure profile's bytes from an agent, invoking onChunk per slice.
+type ProfileFetcher interface {
+ FetchPressureProfile(ctx context.Context, agentID string, fetch *fodcv1.FetchPressureProfile, onChunk func([]byte) error) error
+}
+
// Server exposes REST and Prometheus-style endpoints for external consumption.
type Server struct {
metricsAggregator *metrics.Aggregator
clusterStateCollector *cluster.Manager
lifecycleManager *lifecycle.Manager
crashDiagnosticsAggregator *diagnostics.Aggregator
+ pressureAggregator *pressure.Aggregator
+ profileFetcher ProfileFetcher
registry *registry.AgentRegistry
server *http.Server
logger *logger.Logger
@@ -67,6 +77,8 @@ func NewServer(
lifecycleManager *lifecycle.Manager,
registry *registry.AgentRegistry,
crashDiagnosticsAggregator *diagnostics.Aggregator,
+ pressureAggregator *pressure.Aggregator,
+ profileFetcher ProfileFetcher,
logger *logger.Logger,
) *Server {
return &Server{
@@ -74,6 +86,8 @@ func NewServer(
clusterStateCollector: clusterStateCollector,
lifecycleManager: lifecycleManager,
crashDiagnosticsAggregator: crashDiagnosticsAggregator,
+ pressureAggregator: pressureAggregator,
+ profileFetcher: profileFetcher,
registry: registry,
logger: logger,
startTime: time.Now(),
@@ -90,6 +104,8 @@ func (s *Server) Start(listenAddr string, readTimeout, writeTimeout time.Duratio
mux.HandleFunc("/cluster/topology", s.handleClusterTopology)
mux.HandleFunc("/cluster/lifecycle", s.handleClusterLifecycle)
mux.HandleFunc("/diagnostics", s.handleDiagnostics)
+ mux.HandleFunc("/pressure-profiles", s.handlePressureProfiles)
+ mux.HandleFunc("/pressure-profiles/{pod_name}/{profile_id}/{type}", s.handlePressureProfileDownload)
s.server = &http.Server{
Addr: listenAddr,
@@ -678,6 +694,126 @@ func (s *Server) handleDiagnostics(w http.ResponseWriter, r *http.Request) {
}
}
+// handlePressureProfiles handles GET /pressure-profiles, listing capture-event metadata.
+func (s *Server) handlePressureProfiles(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ if s.pressureAggregator == nil {
+ http.Error(w, "Pressure aggregator not available", http.StatusServiceUnavailable)
+ return
+ }
+ filter := &pressure.Filter{
+ Role: r.URL.Query().Get("role"),
+ PodName: r.URL.Query().Get("pod_name"),
+ }
+ records, collectErr := s.pressureAggregator.CollectProfiles(r.Context(), filter)
+ if collectErr != nil {
+ s.logger.Error().Err(collectErr).Msg("Failed to collect pressure profiles")
+ http.Error(w, "Failed to collect pressure profiles", http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ if encodeErr := json.NewEncoder(w).Encode(records); encodeErr != nil {
+ s.logger.Error().Err(encodeErr).Msg("Failed to encode pressure profiles response")
+ }
+}
+
+// handlePressureProfileDownload handles GET /pressure-profiles/{pod_name}/{profile_id}/{type},
+// streaming one pprof binary straight from the agent to the client without buffering it in
+// the proxy and without the server-wide write timeout cutting off a large download.
+func (s *Server) handlePressureProfileDownload(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ if s.pressureAggregator == nil || s.profileFetcher == nil {
+ http.Error(w, "Pressure profiles not available", http.StatusServiceUnavailable)
+ return
+ }
+ podName := r.PathValue("pod_name")
+ profileID := r.PathValue("profile_id")
+ profType := r.PathValue("type")
+ if !pprofcapture.IsValidType(profType) {
+ http.Error(w, "Unknown profile type", http.StatusBadRequest)
+ return
+ }
+
+ // Resolve from the cache first; only pay the refresh round-trip on a miss (the cache is
+ // populated by a prior list, or becomes populated by this refresh). This avoids the
+ // fixed ~2s CollectProfiles window on every download.
+ agentID, filePath, role, ok := s.pressureAggregator.LookupForDownload(podName, profileID, profType)
+ if !ok {
+ if _, collectErr := s.pressureAggregator.CollectProfiles(r.Context(), &pressure.Filter{PodName: podName}); collectErr != nil {
+ s.logger.Error().Err(collectErr).Str("pod_name", podName).Msg("Failed to refresh pressure profiles for download")
+ }
+ agentID, filePath, role, ok = s.pressureAggregator.LookupForDownload(podName, profileID, profType)
+ }
+ if !ok {
+ http.Error(w, "Profile not found", http.StatusNotFound)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/octet-stream")
+ // Sanitize + quote every interpolated value (pod/role/profileID come from the untrusted
+ // request path) so they cannot inject Content-Disposition header syntax.
+ filename := fmt.Sprintf("%s-%s-%s-%s.pprof", sanitizeFilenamePart(podName), sanitizeFilenamePart(role), sanitizeFilenamePart(profileID), profType)
+ w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
+
+ // Lift the server-wide WriteTimeout for this streaming handler only; other endpoints stay
+ // protected. If it cannot be lifted, large transfers may be truncated at the timeout.
+ controller := http.NewResponseController(w)
+ if deadlineErr := controller.SetWriteDeadline(time.Time{}); deadlineErr != nil {
+ s.logger.Warn().Err(deadlineErr).Msg("Failed to lift write deadline for pressure profile download; large transfers may truncate")
+ }
+
+ fetch := &fodcv1.FetchPressureProfile{
+ RequestId: uuid.NewString(),
+ ProfileId: profileID,
+ Type: profType,
+ Filepath: filePath,
+ }
+ written := false
+ onChunk := func(data []byte) error {
+ written = true
+ if _, writeErr := w.Write(data); writeErr != nil {
+ return writeErr
+ }
+ _ = controller.Flush()
+ return nil
+ }
+ if fetchErr := s.profileFetcher.FetchPressureProfile(r.Context(), agentID, fetch, onChunk); fetchErr != nil {
+ if !written {
+ // Nothing has been written yet, so the status line is still open: the agent
+ // could not serve the file (e.g. it was evicted between list and download).
+ // Surface a real error instead of an empty 200.
+ w.Header().Del("Content-Disposition")
+ http.Error(w, fmt.Sprintf("Profile not available: %v", fetchErr), http.StatusNotFound)
+ return
+ }
+ // Bytes are already on the wire, so the connection is simply truncated; the client
+ // sees an incomplete download. Log for diagnosis.
+ s.logger.Error().Err(fetchErr).Str("pod_name", podName).Str("profile_id", profileID).
+ Str("type", profType).Msg("Failed to stream pressure profile")
+ }
+}
+
+// sanitizeFilenamePart keeps only filename-safe characters so values interpolated into the
+// Content-Disposition header (pod name, role, profile id taken from the request path) cannot
+// inject header syntax or path separators.
+func sanitizeFilenamePart(s string) string {
+ return strings.Map(func(r rune) rune {
+ switch {
+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '.', r == '_', r == '-':
+ return r
+ default:
+ return '_'
+ }
+ }, s)
+}
+
func marshalLifecycleGroups(groups []*fodcv1.GroupLifecycleInfo) ([]json.RawMessage, error) {
out := make([]json.RawMessage, 0, len(groups))
for _, g := range groups {
diff --git a/fodc/proxy/internal/api/server_test.go b/fodc/proxy/internal/api/server_test.go
index 56dda90f9..954b89cf3 100644
--- a/fodc/proxy/internal/api/server_test.go
+++ b/fodc/proxy/internal/api/server_test.go
@@ -89,7 +89,7 @@ func newTestServer(t *testing.T) (*Server, *registry.AgentRegistry, *mockCluster
mockRequester := &mockClusterDataRequester{}
clusterMgr := cluster.NewManager(testRegistry, mockRequester, testLogger)
mockRequester.clusterMgr = clusterMgr
- server := NewServer(aggregator, clusterMgr, nil, testRegistry, nil, testLogger)
+ server := NewServer(aggregator, clusterMgr, nil, testRegistry, nil, nil, nil, testLogger)
return server, testRegistry, mockRequester
}
@@ -171,7 +171,7 @@ func TestHandleClusterTopology_NoClusterStateCollector(t *testing.T) {
testRegistry := registry.NewAgentRegistry(testLogger, 5*time.Second, 10*time.Second, 100)
mockSender := &mockRequestSender{}
aggregator := metrics.NewAggregator(testRegistry, mockSender, testLogger)
- server := NewServer(aggregator, nil, nil, testRegistry, nil, testLogger)
+ server := NewServer(aggregator, nil, nil, testRegistry, nil, nil, nil, testLogger)
req := httptest.NewRequest(http.MethodGet, "/cluster/topology", nil)
resp := httptest.NewRecorder()
server.handleClusterTopology(resp, req)
@@ -186,7 +186,7 @@ func TestHandleClusterTopology_RequestClusterDataError(t *testing.T) {
aggregator := metrics.NewAggregator(testRegistry, mockSender, testLogger)
mockRequester := &mockClusterDataRequester{requestErr: assert.AnError}
clusterMgr := cluster.NewManager(testRegistry, mockRequester, testLogger)
- server := NewServer(aggregator, clusterMgr, nil, testRegistry, nil, testLogger)
+ server := NewServer(aggregator, clusterMgr, nil, testRegistry, nil, nil, nil, testLogger)
ctx := context.Background()
identity := registry.AgentIdentity{
PodName: "test-pod",
@@ -208,7 +208,7 @@ func TestNewServer(t *testing.T) {
mockSender := &mockRequestSender{}
aggregator := metrics.NewAggregator(testRegistry, mockSender, testLogger)
- server := NewServer(aggregator, nil, nil, testRegistry, nil, testLogger)
+ server := NewServer(aggregator, nil, nil, testRegistry, nil, nil, nil, testLogger)
assert.NotNil(t, server)
assert.Equal(t, aggregator, server.metricsAggregator)
@@ -753,7 +753,7 @@ func TestHandleClusterLifecycle_Success(t *testing.T) {
}
mockLifecycleRequester.podByAgent[agentID] = "test-pod-1"
- server := NewServer(aggregator, nil, lifecycleMgr, testRegistry, nil, testLogger)
+ server := NewServer(aggregator, nil, lifecycleMgr, testRegistry, nil, nil, nil, testLogger)
req := httptest.NewRequest(http.MethodGet, "/cluster/lifecycle", nil)
resp := httptest.NewRecorder()
@@ -779,7 +779,7 @@ func TestHandleClusterLifecycle_NoLifecycleManager(t *testing.T) {
testRegistry := registry.NewAgentRegistry(testLogger, 5*time.Second, 10*time.Second, 100)
mockSender := &mockRequestSender{}
aggregator := metrics.NewAggregator(testRegistry, mockSender, testLogger)
- server := NewServer(aggregator, nil, nil, testRegistry, nil, testLogger)
+ server := NewServer(aggregator, nil, nil, testRegistry, nil, nil, nil, testLogger)
req := httptest.NewRequest(http.MethodGet, "/cluster/lifecycle", nil)
resp := httptest.NewRecorder()
@@ -818,7 +818,7 @@ func TestHandleClusterLifecycle_NoAgents_FlagsErrorInBody(t *testing.T) {
lifecycleMgr := lifecycle.NewManager(testRegistry, mockLifecycleRequester, testLogger)
mockLifecycleRequester.lifecycleMgr = lifecycleMgr
- server := NewServer(aggregator, nil, lifecycleMgr, testRegistry, nil, testLogger)
+ server := NewServer(aggregator, nil, lifecycleMgr, testRegistry, nil, nil, nil, testLogger)
req := httptest.NewRequest(http.MethodGet, "/cluster/lifecycle", nil)
resp := httptest.NewRecorder()
@@ -872,7 +872,7 @@ func runLifecycleHandlerWithGroup(t *testing.T, group *fodcv1.GroupLifecycleInfo
}
mockLifecycleRequester.podByAgent[agentID] = "test-pod-1"
- server := NewServer(aggregator, nil, lifecycleMgr, testRegistry, nil, testLogger)
+ server := NewServer(aggregator, nil, lifecycleMgr, testRegistry, nil, nil, nil, testLogger)
req := httptest.NewRequest(http.MethodGet, "/cluster/lifecycle", nil)
resp := httptest.NewRecorder()
server.handleClusterLifecycle(resp, req)
@@ -1165,7 +1165,7 @@ func TestHandleClusterLifecycle_StatusReportsUseProtoJSON(t *testing.T) {
}
mockLifecycleRequester.podByAgent[agentID] = "test-pod-1"
- server := NewServer(aggregator, nil, lifecycleMgr, testRegistry, nil, testLogger)
+ server := NewServer(aggregator, nil, lifecycleMgr, testRegistry, nil, nil, nil, testLogger)
req := httptest.NewRequest(http.MethodGet, "/cluster/lifecycle", nil)
resp := httptest.NewRecorder()
server.handleClusterLifecycle(resp, req)
diff --git a/fodc/proxy/internal/grpc/pressure_list_test.go b/fodc/proxy/internal/grpc/pressure_list_test.go
new file mode 100644
index 000000000..82e497022
--- /dev/null
+++ b/fodc/proxy/internal/grpc/pressure_list_test.go
@@ -0,0 +1,130 @@
+// Licensed to Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package grpc
+
+import (
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func newListWaiter(agentIDs ...string) *listWaiter {
+ w := &listWaiter{pending: make(map[string]struct{}), done: make(chan struct{})}
+ for _, id := range agentIDs {
+ w.pending[id] = struct{}{}
+ }
+ return w
+}
+
+func assertClosed(t *testing.T, ch <-chan struct{}, within time.Duration) {
+ t.Helper()
+ select {
+ case <-ch:
+ case <-time.After(within):
+ t.Fatal("done channel did not close in time")
+ }
+}
+
+func assertOpen(t *testing.T, ch <-chan struct{}) {
+ t.Helper()
+ select {
+ case <-ch:
+ t.Fatal("done channel closed unexpectedly")
+ default:
+ }
+}
+
+// TestListWaiterAllAckedClosesDone verifies done closes only once every pending agent acks.
+func TestListWaiterAllAckedClosesDone(t *testing.T) {
+ w := newListWaiter("a", "b")
+ w.ack("a")
+ assertOpen(t, w.done)
+ w.ack("b")
+ assertClosed(t, w.done, time.Second)
+}
+
+// TestListWaiterDoubleAck verifies acking the same agent twice is idempotent (no panic, no
+// premature close) and an unknown agent ack is ignored.
+func TestListWaiterDoubleAck(t *testing.T) {
+ w := newListWaiter("a", "b")
+ w.ack("a")
+ w.ack("a") // duplicate
+ w.ack("unknown")
+ assertOpen(t, w.done)
+ w.ack("b")
+ assertClosed(t, w.done, time.Second)
+ w.ack("a") // ack after close must not panic
+}
+
+// TestListWaiterForceDone verifies the TTL backstop closes done regardless of pending, and a
+// later ack does not panic on the already-closed channel.
+func TestListWaiterForceDone(t *testing.T) {
+ w := newListWaiter("a", "b")
+ w.forceDone()
+ assertClosed(t, w.done, time.Second)
+ w.forceDone() // idempotent
+ w.ack("a") // must not panic
+}
+
+// TestCollectListZeroAgents returns an already-closed channel.
+func TestCollectListZeroAgents(t *testing.T) {
+ service, registry := newTestService(t)
+ defer registry.Stop()
+ assertClosed(t, service.CollectList(nil), 50*time.Millisecond)
+}
+
+// TestCollectListDisconnectedAgent acks an agent that has no connection so the wait completes
+// immediately instead of stalling.
+func TestCollectListDisconnectedAgent(t *testing.T) {
+ service, registry := newTestService(t)
+ defer registry.Stop()
+ assertClosed(t, service.CollectList([]string{"ghost"}), time.Second)
+}
+
+// TestCollectListSendFailureAcks acks an agent whose pressure stream is not established (send
+// fails) so the wait completes without a stall.
+func TestCollectListSendFailureAcks(t *testing.T) {
+ service, registry := newTestService(t)
+ defer registry.Stop()
+ service.connectionsMu.Lock()
+ service.connections["agent-x"] = &agentConnection{agentID: "agent-x"} // nil pressureProfilesStream
+ service.connectionsMu.Unlock()
+ assertClosed(t, service.CollectList([]string{"agent-x"}), time.Second)
+}
+
+// TestCleanupConnectionAcksListWaiters pins the fix for the disconnect stall: cleaning up a
+// connection acks the departing agent in every in-flight list waiter.
+func TestCleanupConnectionAcksListWaiters(t *testing.T) {
+ service, registry := newTestService(t)
+ defer registry.Stop()
+ w := newListWaiter("agent-x", "agent-y")
+ service.listMu.Lock()
+ service.listWaiters["req-1"] = w
+ service.listMu.Unlock()
+
+ service.cleanupConnection("agent-x")
+ assertOpen(t, w.done) // agent-y still pending
+ service.cleanupConnection("agent-y")
+ assertClosed(t, w.done, time.Second)
+}
+
+// TestAckListUnknownRequestIsNoop verifies a completion for an unknown request id is dropped.
+func TestAckListUnknownRequestIsNoop(t *testing.T) {
+ service, registry := newTestService(t)
+ defer registry.Stop()
+ assert.NotPanics(t, func() { service.ackList("does-not-exist", "agent-x") })
+}
diff --git a/fodc/proxy/internal/grpc/server_test.go b/fodc/proxy/internal/grpc/server_test.go
index 98f0b683c..288c04f18 100644
--- a/fodc/proxy/internal/grpc/server_test.go
+++ b/fodc/proxy/internal/grpc/server_test.go
@@ -35,7 +35,7 @@ func TestNewServer(t *testing.T) {
testRegistry := registry.NewAgentRegistry(testLogger, 5*time.Second, 10*time.Second, 100)
mockSender := &mockRequestSender{}
aggregator := metrics.NewAggregator(testRegistry, mockSender, testLogger)
- service := NewFODCService(testRegistry, aggregator, nil, nil, nil, testLogger, 30*time.Second)
+ service := NewFODCService(testRegistry, aggregator, nil, nil, nil, nil, testLogger, 30*time.Second)
server := NewServer(service, "localhost:0", 1024*1024, testLogger)
@@ -51,7 +51,7 @@ func TestServer_StartStop(t *testing.T) {
testRegistry := registry.NewAgentRegistry(testLogger, 5*time.Second, 10*time.Second, 100)
mockSender := &mockRequestSender{}
aggregator := metrics.NewAggregator(testRegistry, mockSender, testLogger)
- service := NewFODCService(testRegistry, aggregator, nil, nil, nil, testLogger, 30*time.Second)
+ service := NewFODCService(testRegistry, aggregator, nil, nil, nil, nil, testLogger, 30*time.Second)
server := NewServer(service, "localhost:0", 1024*1024, testLogger)
@@ -69,7 +69,7 @@ func TestServer_Stop_NotStarted(t *testing.T) {
testRegistry := registry.NewAgentRegistry(testLogger, 5*time.Second, 10*time.Second, 100)
mockSender := &mockRequestSender{}
aggregator := metrics.NewAggregator(testRegistry, mockSender, testLogger)
- service := NewFODCService(testRegistry, aggregator, nil, nil, nil, testLogger, 30*time.Second)
+ service := NewFODCService(testRegistry, aggregator, nil, nil, nil, nil, testLogger, 30*time.Second)
server := NewServer(service, "localhost:0", 1024*1024, testLogger)
@@ -82,7 +82,7 @@ func TestServer_Start_InvalidAddress(t *testing.T) {
testRegistry := registry.NewAgentRegistry(testLogger, 5*time.Second, 10*time.Second, 100)
mockSender := &mockRequestSender{}
aggregator := metrics.NewAggregator(testRegistry, mockSender, testLogger)
- service := NewFODCService(testRegistry, aggregator, nil, nil, nil, testLogger, 30*time.Second)
+ service := NewFODCService(testRegistry, aggregator, nil, nil, nil, nil, testLogger, 30*time.Second)
server := NewServer(service, "invalid-address", 1024*1024, testLogger)
diff --git a/fodc/proxy/internal/grpc/service.go b/fodc/proxy/internal/grpc/service.go
index 3bb65bc6a..47acd8a19 100644
--- a/fodc/proxy/internal/grpc/service.go
+++ b/fodc/proxy/internal/grpc/service.go
@@ -26,6 +26,7 @@ import (
"sync"
"time"
+ "github.com/google/uuid"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
@@ -37,6 +38,7 @@ import (
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/diagnostics"
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/lifecycle"
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/metrics"
+ "github.com/apache/skywalking-banyandb/fodc/proxy/internal/pressure"
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/registry"
"github.com/apache/skywalking-banyandb/pkg/logger"
)
@@ -47,9 +49,27 @@ type agentConnection struct {
clusterStateStream fodcv1.FODCService_StreamClusterTopologyServer
lifecycleStream fodcv1.FODCService_StreamLifecycleServer
crashDiagnosticsStream fodcv1.FODCService_StreamCrashDiagnosticsServer
+ pressureProfilesStream fodcv1.FODCService_StreamPressureProfilesServer
+ pendingFetches map[string]*fetchWaiter
lastActivity time.Time
agentID string
mu sync.RWMutex
+ fetchMu sync.Mutex
+}
+
+// fetchWaiter delivers the chunks of one in-flight download to the HTTP handler that
+// issued the fetch. done is closed when that handler stops reading so deliverChunk drops
+// late chunks instead of blocking; the chunk channel itself is never closed.
+type fetchWaiter struct {
+ ch chan *fodcv1.PressureProfileChunk
+ done chan struct{}
+ closeOnce sync.Once
+}
+
+// close signals the fetch is over; safe to call from both unregisterFetch and a
+// disconnect-time cancellation without double-closing the channel.
+func (w *fetchWaiter) close() {
+ w.closeOnce.Do(func() { close(w.done) })
}
// updateActivity updates the last activity time.
@@ -176,6 +196,103 @@ func (ac *agentConnection) sendDiagnosticsRequest() error {
return nil
}
+// setPressureProfilesStream sets the pressure profiles stream.
+func (ac *agentConnection) setPressureProfilesStream(stream fodcv1.FODCService_StreamPressureProfilesServer) {
+ ac.mu.Lock()
+ defer ac.mu.Unlock()
+ ac.pressureProfilesStream = stream
+}
+
+// hasPressureProfilesStream reports whether the pressure profiles stream is established.
+func (ac *agentConnection) hasPressureProfilesStream() bool {
+ ac.mu.RLock()
+ defer ac.mu.RUnlock()
+ return ac.pressureProfilesStream != nil
+}
+
+// sendListProfiles asks the agent to stream its capture-event metadata.
+func (ac *agentConnection) sendListProfiles(requestID string) error {
+ ac.mu.RLock()
+ defer ac.mu.RUnlock()
+ if ac.pressureProfilesStream == nil {
+ return fmt.Errorf("pressure profiles stream not established for agent ID: %s", ac.agentID)
+ }
+ resp := &fodcv1.StreamPressureProfilesResponse{
+ Command: &fodcv1.StreamPressureProfilesResponse_ListProfiles{
+ ListProfiles: &fodcv1.ListProfiles{RequestId: requestID},
+ },
+ }
+ if sendErr := ac.pressureProfilesStream.Send(resp); sendErr != nil {
+ return fmt.Errorf("failed to send list profiles request: %w", sendErr)
+ }
+ return nil
+}
+
+// sendFetchProfile asks the agent to stream one profile's bytes.
+func (ac *agentConnection) sendFetchProfile(fetch *fodcv1.FetchPressureProfile) error {
+ ac.mu.RLock()
+ defer ac.mu.RUnlock()
+ if ac.pressureProfilesStream == nil {
+ return fmt.Errorf("pressure profiles stream not established for agent ID: %s", ac.agentID)
+ }
+ resp := &fodcv1.StreamPressureProfilesResponse{
+ Command: &fodcv1.StreamPressureProfilesResponse_FetchProfile{FetchProfile: fetch},
+ }
+ if sendErr := ac.pressureProfilesStream.Send(resp); sendErr != nil {
+ return fmt.Errorf("failed to send fetch profile request: %w", sendErr)
+ }
+ return nil
+}
+
+// registerFetch creates a waiter for the chunks of one download, keyed by request id.
+func (ac *agentConnection) registerFetch(requestID string) *fetchWaiter {
+ ac.mu.Lock()
+ defer ac.mu.Unlock()
+ if ac.pendingFetches == nil {
+ ac.pendingFetches = make(map[string]*fetchWaiter)
+ }
+ waiter := &fetchWaiter{
+ ch: make(chan *fodcv1.PressureProfileChunk, 4),
+ done: make(chan struct{}),
+ }
+ ac.pendingFetches[requestID] = waiter
+ return waiter
+}
+
+// unregisterFetch removes the waiter and signals deliverChunk to stop delivering.
+func (ac *agentConnection) unregisterFetch(requestID string) {
+ ac.mu.Lock()
+ defer ac.mu.Unlock()
+ if waiter, ok := ac.pendingFetches[requestID]; ok {
+ waiter.close()
+ delete(ac.pendingFetches, requestID)
+ }
+}
+
+// cancelPendingFetches closes every in-flight fetch waiter so blocked FetchPressureProfile
+// calls return immediately instead of hanging until the chunk timeout; called on disconnect.
+func (ac *agentConnection) cancelPendingFetches() {
+ ac.mu.Lock()
+ defer ac.mu.Unlock()
+ for _, waiter := range ac.pendingFetches {
+ waiter.close()
+ }
+}
+
+// deliverChunk routes one received chunk to the waiting download handler.
+func (ac *agentConnection) deliverChunk(chunk *fodcv1.PressureProfileChunk) {
+ ac.mu.RLock()
+ waiter := ac.pendingFetches[chunk.RequestId]
+ ac.mu.RUnlock()
+ if waiter == nil {
+ return
+ }
+ select {
+ case waiter.ch <- chunk:
+ case <-waiter.done:
+ }
+}
+
// FODCService implements the FODC gRPC service.
type FODCService struct {
fodcv1.UnimplementedFODCServiceServer
@@ -184,12 +301,52 @@ type FODCService struct {
clusterStateManager *cluster.Manager
lifecycleManager *lifecycle.Manager
crashDiagnosticsAggregator *diagnostics.Aggregator
+ pressureAggregator *pressure.Aggregator
logger *logger.Logger
connections map[string]*agentConnection
+ listWaiters map[string]*listWaiter
connectionsMu sync.RWMutex
+ listMu sync.Mutex
heartbeatInterval time.Duration
}
+// listWaiter tracks one CollectList request: it closes done once every agent that was
+// successfully sent the list command has reported ListComplete (or been dropped on a send
+// failure / disconnect), so the aggregator returns without waiting out the full timeout.
+type listWaiter struct {
+ pending map[string]struct{}
+ done chan struct{}
+ closed bool
+ mu sync.Mutex
+}
+
+// ack removes one agent from the pending set, closing done when the set empties.
+func (w *listWaiter) ack(agentID string) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ delete(w.pending, agentID)
+ if len(w.pending) == 0 {
+ w.closeLocked()
+ }
+}
+
+// forceDone closes done unconditionally. It is the TTL backstop that releases the waiter (and
+// any caller still parked on it) even if some agent never acks; in normal operation the
+// aggregator's own listTimeout caps latency well before the TTL fires.
+func (w *listWaiter) forceDone() {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ w.closeLocked()
+}
+
+// closeLocked closes done exactly once. Callers must hold w.mu.
+func (w *listWaiter) closeLocked() {
+ if !w.closed {
+ w.closed = true
+ close(w.done)
+ }
+}
+
// NewFODCService creates a new FODCService instance.
func NewFODCService(
registry *registry.AgentRegistry,
@@ -197,6 +354,7 @@ func NewFODCService(
clusterStateManager *cluster.Manager,
lifecycleManager *lifecycle.Manager,
crashDiagnosticsAggregator *diagnostics.Aggregator,
+ pressureAggregator *pressure.Aggregator,
logger *logger.Logger,
heartbeatInterval time.Duration,
) *FODCService {
@@ -206,8 +364,10 @@ func NewFODCService(
clusterStateManager: clusterStateManager,
lifecycleManager: lifecycleManager,
crashDiagnosticsAggregator: crashDiagnosticsAggregator,
+ pressureAggregator: pressureAggregator,
logger: logger,
connections: make(map[string]*agentConnection),
+ listWaiters: make(map[string]*listWaiter),
heartbeatInterval: heartbeatInterval,
}
}
@@ -437,8 +597,17 @@ func (s *FODCService) cleanupConnection(agentID string) {
}
s.connectionsMu.Lock()
- defer s.connectionsMu.Unlock()
+ conn := s.connections[agentID]
delete(s.connections, agentID)
+ s.connectionsMu.Unlock()
+
+ if conn != nil {
+ conn.cancelPendingFetches()
+ }
+ s.ackDepartedAgent(agentID)
+ if s.pressureAggregator != nil {
+ s.pressureAggregator.RemoveAgent(agentID)
+ }
s.logger.Debug().Str("agent_id", agentID).Msg("Cleaned up agent connection")
}
@@ -653,6 +822,17 @@ func (s *FODCService) HasCrashDiagnosticsStream(agentID string) bool {
return conn.hasCrashDiagnosticsStream()
}
+// HasPressureProfilesStream reports whether the given agent currently has a pressure profiles stream.
+func (s *FODCService) HasPressureProfilesStream(agentID string) bool {
+ s.connectionsMu.RLock()
+ defer s.connectionsMu.RUnlock()
+ conn, exists := s.connections[agentID]
+ if !exists || conn == nil {
+ return false
+ }
+ return conn.hasPressureProfilesStream()
+}
+
// StreamCrashDiagnostics handles bi-directional crash diagnostics streaming.
func (s *FODCService) StreamCrashDiagnostics(stream fodcv1.FODCService_StreamCrashDiagnosticsServer) error {
ctx := stream.Context()
@@ -732,3 +912,227 @@ func (s *FODCService) RequestDiagnostics(agentID string) error {
}
return agentConn.sendDiagnosticsRequest()
}
+
+// fetchChunkTimeout bounds the wait for each download chunk; it resets per chunk, so a
+// large but steadily-streaming profile never trips it.
+const fetchChunkTimeout = 30 * time.Second
+
+// StreamPressureProfiles handles the bi-directional memory-pressure pprof stream: agents
+// reply to list/fetch commands with metadata records or binary chunks.
+func (s *FODCService) StreamPressureProfiles(stream fodcv1.FODCService_StreamPressureProfilesServer) error {
+ ctx := stream.Context()
+ agentID := s.getAgentIDFromContext(ctx)
+ if agentID == "" {
+ agentID = s.getAgentIDFromPeer(ctx)
+ if agentID != "" {
+ s.logger.Warn().Str("agent_id", agentID).
+ Msg("Agent ID not found in metadata, using peer address fallback (this may be unreliable)")
+ }
+ }
+ if agentID == "" {
+ s.logger.Error().Msg("Agent ID not found in context metadata or peer address for pressure profiles stream")
+ return status.Errorf(codes.Unauthenticated, "agent ID not found in context or peer address")
+ }
+
+ s.connectionsMu.Lock()
+ existingConn, exists := s.connections[agentID]
+ if exists {
+ existingConn.setPressureProfilesStream(stream)
+ existingConn.updateActivity()
+ } else {
+ s.connections[agentID] = &agentConnection{
+ agentID: agentID,
+ pressureProfilesStream: stream,
+ lastActivity: time.Now(),
+ }
+ }
+ s.connectionsMu.Unlock()
+
+ // round accumulates the current list round's records; on ListComplete it is swapped into the
+ // cache in one shot and reset. Keeping it goroutine-local means a mid-round disconnect simply
+ // discards it (no orphan state), and the deferred cleanup runs on this same goroutine after
+ // the loop, so it can never race a ListComplete swap.
+ var round []*fodcv1.PressureProfileRecord
+ if s.pressureAggregator != nil {
+ defer s.pressureAggregator.RemoveAgent(agentID)
+ }
+
+ for {
+ req, recvErr := stream.Recv()
+ if errors.Is(recvErr, io.EOF) {
+ s.logger.Debug().Str("agent_id", agentID).Msg("Pressure profiles stream closed by agent")
+ return nil
+ }
+ if recvErr != nil {
+ if errors.Is(recvErr, context.Canceled) || errors.Is(recvErr, context.DeadlineExceeded) {
+ s.logger.Debug().Err(recvErr).Str("agent_id", agentID).Msg("Pressure profiles stream closed")
+ } else if st, ok := status.FromError(recvErr); ok && (st.Code() == codes.Canceled || st.Code() == codes.DeadlineExceeded) {
+ s.logger.Debug().Err(recvErr).Str("agent_id", agentID).Msg("Pressure profiles stream closed")
+ } else {
+ s.logger.Error().Err(recvErr).Str("agent_id", agentID).Msg("Error receiving pressure profiles")
+ }
+ return recvErr
+ }
+ s.handlePressurePayload(agentID, req, &round)
+ }
+}
+
+// handlePressurePayload routes one stream message: a metadata record to the aggregator,
+// or a download chunk to the waiting fetch handler.
+func (s *FODCService) handlePressurePayload(agentID string, req *fodcv1.StreamPressureProfilesRequest, round *[]*fodcv1.PressureProfileRecord) {
+ switch payload := req.Payload.(type) {
+ case *fodcv1.StreamPressureProfilesRequest_Record:
+ // Accumulate the round locally; it is committed to the cache on ListComplete.
+ *round = append(*round, payload.Record)
+ case *fodcv1.StreamPressureProfilesRequest_Chunk:
+ s.connectionsMu.RLock()
+ conn := s.connections[agentID]
+ s.connectionsMu.RUnlock()
+ if conn != nil {
+ conn.deliverChunk(payload.Chunk)
+ }
+ case *fodcv1.StreamPressureProfilesRequest_ListComplete:
+ // Commit the accumulated round into the cache (replacing the agent's whole set, so evicted
+ // events drop out) before waking the waiting CollectProfiles, then reset the accumulator.
+ if s.pressureAggregator != nil {
+ if agentInfo, getErr := s.registry.GetAgentByID(agentID); getErr != nil {
+ s.logger.Error().Err(getErr).Str("agent_id", agentID).Msg("Failed to get agent info for pressure profile list")
+ } else {
+ s.pressureAggregator.ReplaceAgentProfiles(agentID, agentInfo, *round)
+ }
+ }
+ *round = nil
+ s.ackList(payload.ListComplete.RequestId, agentID)
+ }
+}
+
+// collectListTTL bounds how long a list waiter lingers in the registry, independent of the
+// aggregator's own wait timeout, so a request whose agents never all ack does not leak.
+const collectListTTL = 30 * time.Second
+
+// CollectList sends a list_profiles command (under one request id) to every agent and returns a
+// channel closed once each successfully-contacted agent has reported ListComplete. Agents that
+// cannot be reached are dropped immediately so they never hold the channel open.
+func (s *FODCService) CollectList(agentIDs []string) <-chan struct{} {
+ if len(agentIDs) == 0 {
+ done := make(chan struct{})
+ close(done)
+ return done
+ }
+ requestID := uuid.NewString()
+ waiter := &listWaiter{pending: make(map[string]struct{}), done: make(chan struct{})}
+ for _, id := range agentIDs {
+ waiter.pending[id] = struct{}{}
+ }
+
+ s.listMu.Lock()
+ s.listWaiters[requestID] = waiter
+ s.listMu.Unlock()
+ // Remove the registry entry as soon as the waiter completes (all agents acked), and fall
+ // back to collectListTTL to force-unblock and clean up if some agent never acks. This keeps
+ // waiters/timers from lingering the full TTL under frequent list calls.
+ timer := time.NewTimer(collectListTTL)
+ go func() {
+ select {
+ case <-waiter.done:
+ timer.Stop()
+ case <-timer.C:
+ waiter.forceDone()
+ }
+ s.listMu.Lock()
+ delete(s.listWaiters, requestID)
+ s.listMu.Unlock()
+ }()
+
+ for _, id := range agentIDs {
+ s.connectionsMu.RLock()
+ conn, exists := s.connections[id]
+ s.connectionsMu.RUnlock()
+ if !exists {
+ waiter.ack(id)
+ continue
+ }
+ if sendErr := conn.sendListProfiles(requestID); sendErr != nil {
+ s.logger.Info().Err(sendErr).Str("agent_id", id).Msg("Failed to send list profiles request, skipping")
+ waiter.ack(id)
+ }
+ }
+ return waiter.done
+}
+
+// ackList records that an agent finished streaming its list for the given request id.
+func (s *FODCService) ackList(requestID, agentID string) {
+ s.listMu.Lock()
+ waiter := s.listWaiters[requestID]
+ s.listMu.Unlock()
+ if waiter != nil {
+ waiter.ack(agentID)
+ }
+}
+
+// ackDepartedAgent acks a disconnecting agent in every in-flight list waiter: it will never
+// send ListComplete, so without this CollectProfiles would stall the full listTimeout on each
+// disconnect.
+func (s *FODCService) ackDepartedAgent(agentID string) {
+ s.listMu.Lock()
+ defer s.listMu.Unlock()
+ for _, waiter := range s.listWaiters {
+ waiter.ack(agentID)
+ }
+}
+
+// FetchPressureProfile streams one profile's bytes from an agent, invoking onChunk for
+// each data slice. Only one fetch per agent runs at a time so a slow download never head-
+// of-line blocks list metadata.
+func (s *FODCService) FetchPressureProfile(ctx context.Context, agentID string, fetch *fodcv1.FetchPressureProfile, onChunk func([]byte) error) error {
+ s.connectionsMu.RLock()
+ agentConn, exists := s.connections[agentID]
+ s.connectionsMu.RUnlock()
+ if !exists {
+ return fmt.Errorf("agent connection not found for agent ID: %s", agentID)
+ }
+
+ agentConn.fetchMu.Lock()
+ defer agentConn.fetchMu.Unlock()
+
+ waiter := agentConn.registerFetch(fetch.RequestId)
+ defer agentConn.unregisterFetch(fetch.RequestId)
+
+ if sendErr := agentConn.sendFetchProfile(fetch); sendErr != nil {
+ return sendErr
+ }
+
+ // One timer reused across chunks (Reset per chunk) rather than a fresh time.After each
+ // iteration, which would leak a timer per chunk for the duration of a large download.
+ timer := time.NewTimer(fetchChunkTimeout)
+ defer timer.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-waiter.done:
+ return fmt.Errorf("agent %s disconnected during profile fetch", agentID)
+ case <-timer.C:
+ return fmt.Errorf("timed out waiting for profile chunk from agent ID: %s", agentID)
+ case chunk := <-waiter.ch:
+ if chunk.Error != "" {
+ return fmt.Errorf("agent failed to serve profile: %s", chunk.Error)
+ }
+ if len(chunk.Data) > 0 {
+ if writeErr := onChunk(chunk.Data); writeErr != nil {
+ return writeErr
+ }
+ }
+ if chunk.Last {
+ return nil
+ }
+ if !timer.Stop() {
+ select {
+ case <-timer.C:
+ default:
+ }
+ }
+ timer.Reset(fetchChunkTimeout)
+ }
+ }
+}
diff --git a/fodc/proxy/internal/grpc/service_test.go b/fodc/proxy/internal/grpc/service_test.go
index d0e8fa89d..b2c770da0 100644
--- a/fodc/proxy/internal/grpc/service_test.go
+++ b/fodc/proxy/internal/grpc/service_test.go
@@ -221,7 +221,7 @@ func newTestService(t *testing.T) (*FODCService, *registry.AgentRegistry) {
testRegistry := registry.NewAgentRegistry(testLogger, 5*time.Second, 10*time.Second, 100)
mockSender := &mockRequestSender{}
aggregator := metrics.NewAggregator(testRegistry, mockSender, testLogger)
- service := NewFODCService(testRegistry, aggregator, nil, nil, nil, testLogger, 30*time.Second)
+ service := NewFODCService(testRegistry, aggregator, nil, nil, nil, nil, testLogger, 30*time.Second)
return service, testRegistry
}
@@ -238,7 +238,7 @@ func TestNewFODCService(t *testing.T) {
mockSender := &mockRequestSender{}
aggregator := metrics.NewAggregator(testRegistry, mockSender, testLogger)
- service := NewFODCService(testRegistry, aggregator, nil, nil, nil, testLogger, 30*time.Second)
+ service := NewFODCService(testRegistry, aggregator, nil, nil, nil, nil, testLogger, 30*time.Second)
assert.NotNil(t, service)
assert.Equal(t, testRegistry, service.registry)
diff --git a/fodc/proxy/internal/integration/agent_reconnection_test.go b/fodc/proxy/internal/integration/agent_reconnection_test.go
index 614f5b20a..8ab0eb841 100644
--- a/fodc/proxy/internal/integration/agent_reconnection_test.go
+++ b/fodc/proxy/internal/integration/agent_reconnection_test.go
@@ -62,7 +62,7 @@ var _ = Describe("Test Case 3: Agent Reconnection", func() {
heartbeatInterval = 2 * time.Second
agentRegistry = registry.NewAgentRegistry(testLogger, heartbeatTimeout, cleanupTimeout, 100)
metricsAggregator = metricsproxy.NewAggregator(agentRegistry, nil, testLogger)
- grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, nil, nil, testLogger, heartbeatInterval)
+ grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, nil, nil, nil, testLogger, heartbeatInterval)
metricsAggregator.SetGRPCService(grpcService)
grpcListener, listenErr := net.Listen("tcp", "localhost:0")
@@ -78,7 +78,7 @@ var _ = Describe("Test Case 3: Agent Reconnection", func() {
Expect(httpListenErr).NotTo(HaveOccurred())
proxyHTTPAddr = httpListener.Addr().String()
_ = httpListener.Close()
- httpServer = api.NewServer(metricsAggregator, nil, nil, agentRegistry, nil, testLogger)
+ httpServer = api.NewServer(metricsAggregator, nil, nil, agentRegistry, nil, nil, nil, testLogger)
Expect(httpServer.Start(proxyHTTPAddr, 10*time.Second, 10*time.Second)).To(Succeed())
Eventually(func() error {
diff --git a/fodc/proxy/internal/integration/agent_registration_metrics_flow_test.go b/fodc/proxy/internal/integration/agent_registration_metrics_flow_test.go
index a3ee5b0d6..8bafd7bd7 100644
--- a/fodc/proxy/internal/integration/agent_registration_metrics_flow_test.go
+++ b/fodc/proxy/internal/integration/agent_registration_metrics_flow_test.go
@@ -62,7 +62,7 @@ var _ = Describe("Test Case 1: Agent Registration and Metrics Flow", func() {
heartbeatInterval := 2 * time.Second
agentRegistry = registry.NewAgentRegistry(testLogger, heartbeatTimeout, cleanupTimeout, 100)
metricsAggregator = metricsproxy.NewAggregator(agentRegistry, nil, testLogger)
- grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, nil, nil, testLogger, heartbeatInterval)
+ grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, nil, nil, nil, testLogger, heartbeatInterval)
metricsAggregator.SetGRPCService(grpcService)
// Start gRPC server on random port
@@ -81,7 +81,7 @@ var _ = Describe("Test Case 1: Agent Registration and Metrics Flow", func() {
Expect(httpListenErr).NotTo(HaveOccurred())
proxyHTTPAddr = httpListener.Addr().String()
_ = httpListener.Close() // Close listener so port is available for server
- httpServer = api.NewServer(metricsAggregator, nil, nil, agentRegistry, nil, testLogger)
+ httpServer = api.NewServer(metricsAggregator, nil, nil, agentRegistry, nil, nil, nil, testLogger)
// Start HTTP server using the address from the listener
Expect(httpServer.Start(proxyHTTPAddr, 10*time.Second, 10*time.Second)).To(Succeed())
diff --git a/fodc/proxy/internal/integration/cluster_topology_integration_test.go b/fodc/proxy/internal/integration/cluster_topology_integration_test.go
index 174880b05..98ace25b0 100644
--- a/fodc/proxy/internal/integration/cluster_topology_integration_test.go
+++ b/fodc/proxy/internal/integration/cluster_topology_integration_test.go
@@ -76,7 +76,7 @@ var _ = Describe("Cluster Topology Integration", func() {
clusterManager = cluster.NewManager(agentRegistry, nil, testLogger)
metricsAggregator = metricsproxy.NewAggregator(agentRegistry, nil, testLogger)
- grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, clusterManager, nil, nil, testLogger, heartbeatInterval)
+ grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, clusterManager, nil, nil, nil, testLogger, heartbeatInterval)
metricsAggregator.SetGRPCService(grpcService)
clusterManager.SetGRPCService(grpcService)
@@ -93,7 +93,7 @@ var _ = Describe("Cluster Topology Integration", func() {
Expect(httpListenErr).NotTo(HaveOccurred())
proxyHTTPAddr = httpListener.Addr().String()
_ = httpListener.Close()
- httpServer = api.NewServer(metricsAggregator, clusterManager, nil, agentRegistry, nil, testLogger)
+ httpServer = api.NewServer(metricsAggregator, clusterManager, nil, agentRegistry, nil, nil, nil, testLogger)
Expect(httpServer.Start(proxyHTTPAddr, 10*time.Second, 10*time.Second)).To(Succeed())
Eventually(func() error {
diff --git a/fodc/proxy/internal/integration/diagnostic_test.go b/fodc/proxy/internal/integration/diagnostic_test.go
index cd9aa9f9d..7f0cceaa8 100644
--- a/fodc/proxy/internal/integration/diagnostic_test.go
+++ b/fodc/proxy/internal/integration/diagnostic_test.go
@@ -81,7 +81,7 @@ var _ = Describe("Diagnostic Integration", func() {
lifecycleMgr = proxylifecycle.NewManager(agentRegistry, nil, testLogger)
metricsAgg = metricsproxy.NewAggregator(agentRegistry, nil, testLogger)
diagnosticsAgg = diagnostics.NewAggregator(agentRegistry, nil, testLogger)
- grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAgg, nil, lifecycleMgr, diagnosticsAgg, testLogger, heartbeatInterval)
+ grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAgg, nil, lifecycleMgr, diagnosticsAgg, nil, testLogger, heartbeatInterval)
metricsAgg.SetGRPCService(grpcService)
lifecycleMgr.SetGRPCService(grpcService)
diagnosticsAgg.SetGRPCService(grpcService)
@@ -99,7 +99,7 @@ var _ = Describe("Diagnostic Integration", func() {
Expect(httpListenErr).NotTo(HaveOccurred())
proxyHTTPAddr = httpListener.Addr().String()
_ = httpListener.Close()
- httpServer = api.NewServer(metricsAgg, nil, lifecycleMgr, agentRegistry, diagnosticsAgg, testLogger)
+ httpServer = api.NewServer(metricsAgg, nil, lifecycleMgr, agentRegistry, diagnosticsAgg, nil, nil, testLogger)
Expect(httpServer.Start(proxyHTTPAddr, 10*time.Second, 10*time.Second)).To(Succeed())
Eventually(func() error {
diff --git a/fodc/proxy/internal/integration/failure_scenarios_test.go b/fodc/proxy/internal/integration/failure_scenarios_test.go
index 0abb7a412..f8cac993f 100644
--- a/fodc/proxy/internal/integration/failure_scenarios_test.go
+++ b/fodc/proxy/internal/integration/failure_scenarios_test.go
@@ -68,7 +68,7 @@ func setupFailureFixture() *failureFixture {
reg := registry.NewAgentRegistry(testLogger, heartbeatTimeout, cleanupTimeout, 100)
agg := metricsproxy.NewAggregator(reg, nil, testLogger)
- svc := grpcproxy.NewFODCService(reg, agg, nil, nil, nil, testLogger, heartbeatInterval)
+ svc := grpcproxy.NewFODCService(reg, agg, nil, nil, nil, nil, testLogger, heartbeatInterval)
agg.SetGRPCService(svc)
grpcListener, listenErr := net.Listen("tcp", "localhost:0")
@@ -82,7 +82,7 @@ func setupFailureFixture() *failureFixture {
Expect(httpErr).NotTo(HaveOccurred())
httpAddr := httpListener.Addr().String()
_ = httpListener.Close()
- httpSrv := api.NewServer(agg, nil, nil, reg, nil, testLogger)
+ httpSrv := api.NewServer(agg, nil, nil, reg, nil, nil, nil, testLogger)
Expect(httpSrv.Start(httpAddr, 10*time.Second, 10*time.Second)).To(Succeed())
Eventually(func() error {
@@ -329,7 +329,7 @@ var _ = Describe("Failure Scenarios", func() {
Expect(agent.client.Disconnect()).To(Succeed())
fixture.grpcServer.Stop()
- fixture.service = grpcproxy.NewFODCService(fixture.registry, fixture.aggregator, nil, nil, nil, fixture.logger, 2*time.Second)
+ fixture.service = grpcproxy.NewFODCService(fixture.registry, fixture.aggregator, nil, nil, nil, nil, fixture.logger, 2*time.Second)
fixture.aggregator.SetGRPCService(fixture.service)
fixture.grpcServer = grpcproxy.NewServer(fixture.service, fixture.proxyGRPCAddr, 4194304, fixture.logger)
Expect(fixture.grpcServer.Start()).To(Succeed())
diff --git a/fodc/proxy/internal/integration/full_proxy_workflow_test.go b/fodc/proxy/internal/integration/full_proxy_workflow_test.go
index fc9b3784f..41a6ce644 100644
--- a/fodc/proxy/internal/integration/full_proxy_workflow_test.go
+++ b/fodc/proxy/internal/integration/full_proxy_workflow_test.go
@@ -68,7 +68,7 @@ var _ = Describe("Full FODC Proxy Workflow", func() {
heartbeatInterval := 2 * time.Second
agentRegistry = registry.NewAgentRegistry(testLogger, heartbeatTimeout, cleanupTimeout, 100)
metricsAggregator = metricsproxy.NewAggregator(agentRegistry, nil, testLogger)
- grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, nil, nil, testLogger, heartbeatInterval)
+ grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, nil, nil, nil, testLogger, heartbeatInterval)
metricsAggregator.SetGRPCService(grpcService)
grpcListener, listenErr := net.Listen("tcp", "localhost:0")
@@ -84,7 +84,7 @@ var _ = Describe("Full FODC Proxy Workflow", func() {
Expect(httpListenErr).NotTo(HaveOccurred())
proxyHTTPAddr = httpListener.Addr().String()
_ = httpListener.Close()
- httpServer = api.NewServer(metricsAggregator, nil, nil, agentRegistry, nil, testLogger)
+ httpServer = api.NewServer(metricsAggregator, nil, nil, agentRegistry, nil, nil, nil, testLogger)
Expect(httpServer.Start(proxyHTTPAddr, 10*time.Second, 10*time.Second)).To(Succeed())
Eventually(func() error {
diff --git a/fodc/proxy/internal/integration/high_availability_scalability_test.go b/fodc/proxy/internal/integration/high_availability_scalability_test.go
index 3de308755..e490ce8d7 100644
--- a/fodc/proxy/internal/integration/high_availability_scalability_test.go
+++ b/fodc/proxy/internal/integration/high_availability_scalability_test.go
@@ -75,7 +75,7 @@ var _ = Describe("High Availability and Scalability", func() {
agentRegistry = registry.NewAgentRegistry(testLogger, heartbeatTimeout, cleanupTimeout, 1000)
metricsAggregator = metricsproxy.NewAggregator(agentRegistry, nil, testLogger)
- grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, nil, nil, testLogger, heartbeatInterval)
+ grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, nil, nil, nil, testLogger, heartbeatInterval)
metricsAggregator.SetGRPCService(grpcService)
grpcListener, listenErr := net.Listen("tcp", "localhost:0")
@@ -91,7 +91,7 @@ var _ = Describe("High Availability and Scalability", func() {
Expect(httpListenErr).NotTo(HaveOccurred())
proxyHTTPAddr = httpListener.Addr().String()
_ = httpListener.Close()
- httpServer = api.NewServer(metricsAggregator, nil, nil, agentRegistry, nil, testLogger)
+ httpServer = api.NewServer(metricsAggregator, nil, nil, agentRegistry, nil, nil, nil, testLogger)
Expect(httpServer.Start(proxyHTTPAddr, 30*time.Second, 30*time.Second)).To(Succeed())
Eventually(func() error {
diff --git a/fodc/proxy/internal/integration/lifecycle_integration_test.go b/fodc/proxy/internal/integration/lifecycle_integration_test.go
index b0b65e9bf..4bfb67f65 100644
--- a/fodc/proxy/internal/integration/lifecycle_integration_test.go
+++ b/fodc/proxy/internal/integration/lifecycle_integration_test.go
@@ -75,7 +75,7 @@ var _ = Describe("Lifecycle Integration", func() {
lifecycleMgr = proxylifecycle.NewManager(agentRegistry, nil, testLogger)
metricsAggregator = metricsproxy.NewAggregator(agentRegistry, nil, testLogger)
- grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, lifecycleMgr, nil, testLogger, heartbeatInterval)
+ grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, lifecycleMgr, nil, nil, testLogger, heartbeatInterval)
metricsAggregator.SetGRPCService(grpcService)
lifecycleMgr.SetGRPCService(grpcService)
@@ -92,7 +92,7 @@ var _ = Describe("Lifecycle Integration", func() {
Expect(httpListenErr).NotTo(HaveOccurred())
proxyHTTPAddr = httpListener.Addr().String()
_ = httpListener.Close()
- httpServer = api.NewServer(metricsAggregator, nil, lifecycleMgr, agentRegistry, nil, testLogger)
+ httpServer = api.NewServer(metricsAggregator, nil, lifecycleMgr, agentRegistry, nil, nil, nil, testLogger)
Expect(httpServer.Start(proxyHTTPAddr, 10*time.Second, 10*time.Second)).To(Succeed())
Eventually(func() error {
diff --git a/fodc/proxy/internal/integration/metrics_time_window_test.go b/fodc/proxy/internal/integration/metrics_time_window_test.go
index e51c47c17..db1c0440a 100644
--- a/fodc/proxy/internal/integration/metrics_time_window_test.go
+++ b/fodc/proxy/internal/integration/metrics_time_window_test.go
@@ -76,7 +76,7 @@ var _ = Describe("Test Case 2: Metrics Time Window", func() {
heartbeatInterval := 2 * time.Second
agentRegistry = registry.NewAgentRegistry(testLogger, heartbeatTimeout, cleanupTimeout, 100)
metricsAggregator = metricsproxy.NewAggregator(agentRegistry, nil, testLogger)
- grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, nil, nil, testLogger, heartbeatInterval)
+ grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, nil, nil, nil, testLogger, heartbeatInterval)
metricsAggregator.SetGRPCService(grpcService)
grpcListener, listenErr := net.Listen("tcp", "localhost:0")
@@ -92,7 +92,7 @@ var _ = Describe("Test Case 2: Metrics Time Window", func() {
Expect(httpListenErr).NotTo(HaveOccurred())
proxyHTTPAddr = httpListener.Addr().String()
_ = httpListener.Close()
- httpServer = api.NewServer(metricsAggregator, nil, nil, agentRegistry, nil, testLogger)
+ httpServer = api.NewServer(metricsAggregator, nil, nil, agentRegistry, nil, nil, nil, testLogger)
// Use longer timeouts to accommodate aggregator's timeout calculation:
// timeout = (endTime - startTime) + 5 seconds
// For time windows up to ~20 seconds, we need at least 25 seconds write timeout
diff --git a/fodc/proxy/internal/integration/multiple_agents_roles_test.go b/fodc/proxy/internal/integration/multiple_agents_roles_test.go
index 8a2c347f3..79cd46213 100644
--- a/fodc/proxy/internal/integration/multiple_agents_roles_test.go
+++ b/fodc/proxy/internal/integration/multiple_agents_roles_test.go
@@ -68,7 +68,7 @@ var _ = Describe("Test Case 4: Multiple Agents and Roles", func() {
heartbeatInterval := 2 * time.Second
agentRegistry = registry.NewAgentRegistry(testLogger, heartbeatTimeout, cleanupTimeout, 100)
metricsAggregator = metricsproxy.NewAggregator(agentRegistry, nil, testLogger)
- grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, nil, nil, testLogger, heartbeatInterval)
+ grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAggregator, nil, nil, nil, nil, testLogger, heartbeatInterval)
metricsAggregator.SetGRPCService(grpcService)
grpcListener, listenErr := net.Listen("tcp", "localhost:0")
@@ -84,7 +84,7 @@ var _ = Describe("Test Case 4: Multiple Agents and Roles", func() {
Expect(httpListenErr).NotTo(HaveOccurred())
proxyHTTPAddr = httpListener.Addr().String()
_ = httpListener.Close()
- httpServer = api.NewServer(metricsAggregator, nil, nil, agentRegistry, nil, testLogger)
+ httpServer = api.NewServer(metricsAggregator, nil, nil, agentRegistry, nil, nil, nil, testLogger)
Expect(httpServer.Start(proxyHTTPAddr, 10*time.Second, 10*time.Second)).To(Succeed())
Eventually(func() error {
diff --git a/fodc/proxy/internal/integration/pressure_profile_test.go b/fodc/proxy/internal/integration/pressure_profile_test.go
new file mode 100644
index 000000000..18216921b
--- /dev/null
+++ b/fodc/proxy/internal/integration/pressure_profile_test.go
@@ -0,0 +1,246 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package integration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+
+ "github.com/apache/skywalking-banyandb/fodc/agent/testhelper"
+ "github.com/apache/skywalking-banyandb/fodc/proxy/internal/api"
+ grpcproxy "github.com/apache/skywalking-banyandb/fodc/proxy/internal/grpc"
+ proxylifecycle "github.com/apache/skywalking-banyandb/fodc/proxy/internal/lifecycle"
+ metricsproxy "github.com/apache/skywalking-banyandb/fodc/proxy/internal/metrics"
+ "github.com/apache/skywalking-banyandb/fodc/proxy/internal/pressure"
+ "github.com/apache/skywalking-banyandb/fodc/proxy/internal/registry"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+)
+
+// This is the in-process ("code way") counterpart of the Kind real-process e2e: it wires the
+// real watchdog -> flight recorder -> pressure profiler -> agent proxy client against a real
+// proxy (gRPC + HTTP), with only the BanyanDB node replaced by an httptest stub that serves
+// /metrics and the pprof endpoints. A low trigger percentage forces a capture deterministically.
+var _ = Describe("Pressure Profile Integration", func() {
+ var (
+ proxyGRPCAddr string
+ proxyHTTPAddr string
+ grpcServer *grpcproxy.Server
+ httpServer *api.Server
+ agentRegistry *registry.AgentRegistry
+ metricsAgg *metricsproxy.Aggregator
+ pressureAgg *pressure.Aggregator
+ grpcService *grpcproxy.FODCService
+ lifecycleMgr *proxylifecycle.Manager
+ httpClient *http.Client
+ testLogger *logger.Logger
+ banyandStub *httptest.Server
+ heapBytes []byte
+ gorBytes []byte
+ )
+
+ BeforeEach(func() {
+ testLogger = logger.GetLogger("test", "pressure-integration")
+ httpClient = &http.Client{Timeout: 10 * time.Second}
+
+ heartbeatTimeout := 5 * time.Second
+ cleanupTimeout := 10 * time.Second
+ heartbeatInterval := 2 * time.Second
+ agentRegistry = registry.NewAgentRegistry(testLogger, heartbeatTimeout, cleanupTimeout, 100)
+ lifecycleMgr = proxylifecycle.NewManager(agentRegistry, nil, testLogger)
+ metricsAgg = metricsproxy.NewAggregator(agentRegistry, nil, testLogger)
+ pressureAgg = pressure.NewAggregator(agentRegistry, nil, testLogger)
+ grpcService = grpcproxy.NewFODCService(agentRegistry, metricsAgg, nil, lifecycleMgr, nil, pressureAgg, testLogger, heartbeatInterval)
+ metricsAgg.SetGRPCService(grpcService)
+ lifecycleMgr.SetGRPCService(grpcService)
+ pressureAgg.SetGRPCService(grpcService)
+
+ grpcListener, listenErr := net.Listen("tcp", "localhost:0")
+ Expect(listenErr).NotTo(HaveOccurred())
+ proxyGRPCAddr = grpcListener.Addr().String()
+ _ = grpcListener.Close()
+ grpcServer = grpcproxy.NewServer(grpcService, proxyGRPCAddr, 4194304, testLogger)
+ Expect(grpcServer.Start()).To(Succeed())
+ time.Sleep(100 * time.Millisecond)
+
+ httpListener, httpListenErr := net.Listen("tcp", "localhost:0")
+ Expect(httpListenErr).NotTo(HaveOccurred())
+ proxyHTTPAddr = httpListener.Addr().String()
+ _ = httpListener.Close()
+ httpServer = api.NewServer(metricsAgg, nil, lifecycleMgr, agentRegistry, nil, pressureAgg, grpcService, testLogger)
+ Expect(httpServer.Start(proxyHTTPAddr, 10*time.Second, 10*time.Second)).To(Succeed())
+ Eventually(func() error {
+ resp, healthErr := httpClient.Get(fmt.Sprintf("http://%s/health", proxyHTTPAddr))
+ if healthErr != nil {
+ return healthErr
+ }
+ resp.Body.Close()
+ return nil
+ }, "10s", "100ms").Should(Succeed())
+
+ // Stub BanyanDB node: real /metrics text plus real pprof bytes.
+ heapBytes = []byte("HEAP-PPROF-" + strings.Repeat("h", 4096))
+ gorBytes = []byte("GOROUTINE-PPROF-" + strings.Repeat("g", 1024))
+ mux := http.NewServeMux()
+ mux.HandleFunc("/metrics", func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = io.WriteString(w, "# HELP process_resident_memory_bytes Resident memory size in bytes.\n"+
+ "# TYPE process_resident_memory_bytes gauge\n"+
+ "process_resident_memory_bytes 500\n"+
+ "# HELP banyandb_memory_protector_cgroup_limit_bytes Cgroup memory limit in bytes.\n"+
+ "# TYPE banyandb_memory_protector_cgroup_limit_bytes gauge\n"+
+ "banyandb_memory_protector_cgroup_limit_bytes 1000\n")
+ })
+ mux.HandleFunc("/debug/pprof/heap", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(heapBytes) })
+ mux.HandleFunc("/debug/pprof/goroutine", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(gorBytes) })
+ banyandStub = httptest.NewServer(mux)
+ })
+
+ AfterEach(func() {
+ if banyandStub != nil {
+ banyandStub.Close()
+ }
+ if httpServer != nil {
+ _ = httpServer.Stop()
+ }
+ if grpcServer != nil {
+ grpcServer.Stop()
+ }
+ if agentRegistry != nil {
+ agentRegistry.Stop()
+ }
+ })
+
+ stubPort := func() string {
+ u, parseErr := url.Parse(banyandStub.URL)
+ Expect(parseErr).NotTo(HaveOccurred())
+ return u.Port()
+ }
+
+ getProfiles := func() []pressure.AggregatedPressureProfile {
+ resp, getErr := httpClient.Get(fmt.Sprintf("http://%s/pressure-profiles", proxyHTTPAddr))
+ Expect(getErr).NotTo(HaveOccurred())
+ defer resp.Body.Close()
+ Expect(resp.StatusCode).To(Equal(http.StatusOK))
+ var records []pressure.AggregatedPressureProfile
+ Expect(json.NewDecoder(resp.Body).Decode(&records)).To(Succeed())
+ return records
+ }
+
+ download := func(pod, profileID, profType string) (int, []byte, string) {
+ resp, getErr := httpClient.Get(fmt.Sprintf("http://%s/pressure-profiles/%s/%s/%s", proxyHTTPAddr, pod, profileID, profType))
+ Expect(getErr).NotTo(HaveOccurred())
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(resp.Body)
+ return resp.StatusCode, body, resp.Header.Get("Content-Disposition")
+ }
+
+ startAgent := func(podName, dir string) func() {
+ agentCtx, agentCancel := context.WithCancel(context.Background())
+ agent, newErr := testhelper.NewPressureAgent(agentCtx, testhelper.PressureAgentConfig{
+ Logger: testLogger,
+ ProxyAddr: proxyGRPCAddr,
+ PodName: podName,
+ Role: "standalone",
+ MetricsURL: banyandStub.URL + "/metrics",
+ PprofPort: stubPort(),
+ Dir: dir,
+ Cooldown: time.Hour, // capture exactly once for a deterministic assertion
+ TriggerPercent: 1, // 500/1000 = 50% >= 1% -> always triggers
+ })
+ Expect(newErr).NotTo(HaveOccurred())
+ Expect(agent.Connect(agentCtx)).To(Succeed())
+ Expect(agent.StartRegistrationStream(agentCtx)).To(Succeed())
+ Expect(agent.StartPressureProfilesStream(agentCtx)).To(Succeed())
+
+ Eventually(func(g Gomega) {
+ agents := agentRegistry.ListAgents()
+ found := false
+ for _, agentInfo := range agents {
+ if agentInfo.AgentIdentity.PodName == podName {
+ found = true
+ g.Expect(grpcService.HasPressureProfilesStream(agentInfo.AgentID)).To(BeTrue())
+ }
+ }
+ g.Expect(found).To(BeTrue())
+ }, "10s", "100ms").Should(Succeed())
+
+ return func() {
+ agent.Stop()
+ agentCancel()
+ }
+ }
+
+ It("captures pprof under memory pressure and serves it end-to-end via the proxy", func() {
+ dir := GinkgoT().TempDir()
+ podName := "banyand-standalone-0"
+ stop := startAgent(podName, dir)
+ defer stop()
+
+ By("listing the captured event via GET /pressure-profiles")
+ var records []pressure.AggregatedPressureProfile
+ Eventually(func(g Gomega) {
+ records = getProfiles()
+ g.Expect(records).To(HaveLen(1))
+ g.Expect(records[0].Profiles).To(HaveLen(2))
+ }, "20s", "500ms").Should(Succeed())
+
+ rec := records[0]
+ Expect(rec.PodName).To(Equal(podName))
+ Expect(rec.Role).To(Equal("standalone"))
+ Expect(rec.RSSBytes).To(Equal(uint64(500)))
+ Expect(rec.CgroupLimitBytes).To(Equal(uint64(1000)))
+ Expect(rec.ThresholdBytes).To(Equal(uint64(10))) // 1000 * 1 / 100
+
+ By("downloading each profile via GET /pressure-profiles/{pod}/{id}/{type}")
+ heapStatus, heapDL, heapCD := download(podName, rec.ProfileID, "heap")
+ Expect(heapStatus).To(Equal(http.StatusOK))
+ Expect(heapDL).To(Equal(heapBytes))
+ Expect(heapCD).To(ContainSubstring(fmt.Sprintf("%s-standalone-%s-heap.pprof", podName, rec.ProfileID)))
+
+ gorStatus, gorDL, _ := download(podName, rec.ProfileID, "goroutine")
+ Expect(gorStatus).To(Equal(http.StatusOK))
+ Expect(gorDL).To(Equal(gorBytes))
+
+ By("verifying the captured files exist on the agent's disk")
+ entries, readErr := os.ReadDir(filepath.Join(dir, rec.ProfileID))
+ Expect(readErr).NotTo(HaveOccurred())
+ names := make(map[string]bool)
+ for _, e := range entries {
+ names[e.Name()] = true
+ }
+ Expect(names["heap.pprof"]).To(BeTrue())
+ Expect(names["goroutine.pprof"]).To(BeTrue())
+ Expect(names["meta.json"]).To(BeTrue())
+
+ By("returning 404 for an unknown profile id")
+ missingStatus, _, _ := download(podName, "20000101T000000.000000000Z", "heap")
+ Expect(missingStatus).To(Equal(http.StatusNotFound))
+ })
+})
diff --git a/fodc/proxy/internal/integration/prometheus_integration_test.go b/fodc/proxy/internal/integration/prometheus_integration_test.go
index dfa1f45c6..b50c1f9ee 100644
--- a/fodc/proxy/internal/integration/prometheus_integration_test.go
+++ b/fodc/proxy/internal/integration/prometheus_integration_test.go
@@ -57,7 +57,7 @@ func newPromFixture() *promFixture {
reg := registry.NewAgentRegistry(testLogger, heartbeatTimeout, cleanupTimeout, 100)
agg := metricsproxy.NewAggregator(reg, nil, testLogger)
- svc := grpcproxy.NewFODCService(reg, agg, nil, nil, nil, testLogger, heartbeatInterval)
+ svc := grpcproxy.NewFODCService(reg, agg, nil, nil, nil, nil, testLogger, heartbeatInterval)
agg.SetGRPCService(svc)
grpcListener, err := net.Listen("tcp", "localhost:0")
@@ -71,7 +71,7 @@ func newPromFixture() *promFixture {
Expect(err).NotTo(HaveOccurred())
httpAddr := httpListener.Addr().String()
_ = httpListener.Close()
- httpSrv := api.NewServer(agg, nil, nil, reg, nil, testLogger)
+ httpSrv := api.NewServer(agg, nil, nil, reg, nil, nil, nil, testLogger)
Expect(httpSrv.Start(httpAddr, 10*time.Second, 10*time.Second)).To(Succeed())
Eventually(func() error {
diff --git a/fodc/proxy/internal/pressure/aggregator.go b/fodc/proxy/internal/pressure/aggregator.go
new file mode 100644
index 000000000..c65e5cf51
--- /dev/null
+++ b/fodc/proxy/internal/pressure/aggregator.go
@@ -0,0 +1,269 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Package pressure aggregates memory-pressure pprof profile metadata from all agents.
+package pressure
+
+import (
+ "context"
+ "strings"
+ "sync"
+ "time"
+
+ fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+ "github.com/apache/skywalking-banyandb/fodc/proxy/internal/registry"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+)
+
+// listTimeout bounds how long CollectProfiles waits for agents to finish streaming their
+// metadata. It is a fallback only: the collection normally returns as soon as every contacted
+// agent signals completion, well before this elapses.
+const listTimeout = 10 * time.Second
+
+// ProfileInfo is one pprof profile's metadata in the HTTP list response.
+type ProfileInfo struct {
+ Type string `json:"type"`
+ Filename string `json:"filename"`
+ Filepath string `json:"filepath"`
+ Format string `json:"format"`
+ SizeBytes int64 `json:"size_bytes"`
+}
+
+// AggregatedPressureProfile enriches a capture event with the agent's identity.
+type AggregatedPressureProfile struct {
+ CapturedAt time.Time `json:"captured_at"`
+ AgentID string `json:"agent_id"`
+ PodName string `json:"pod_name"`
+ Role string `json:"role"`
+ ProfileID string `json:"profile_id"`
+ SourceEndpoint string `json:"source_endpoint"`
+ Profiles []ProfileInfo `json:"profiles"`
+ RSSBytes uint64 `json:"rss_bytes"`
+ CgroupLimitBytes uint64 `json:"cgroup_limit_bytes"`
+ ThresholdBytes uint64 `json:"threshold_bytes"`
+ TriggerPercent uint32 `json:"trigger_percent"`
+}
+
+// Filter narrows the listed/collected profiles by role and pod name.
+type Filter struct {
+ Role string
+ PodName string
+}
+
+// RequestSender drives the agents to stream their profile metadata. CollectList sends a
+// list command to every given agent under one request and returns a channel closed once all
+// of them have signaled completion.
+type RequestSender interface {
+ CollectList(agentIDs []string) <-chan struct{}
+}
+
+// Aggregator keeps a dedup cache of capture-event metadata nested by agentID -> profileID.
+// On each list request it pulls fresh metadata from every matching agent, waits a short
+// window, then returns the cache snapshot. The authoritative copy lives on the agent disk.
+type Aggregator struct {
+ registry *registry.AgentRegistry
+ grpcService RequestSender
+ // cache is the live, queryable set: agentID -> profileID -> record. Each agent's whole set
+ // is replaced in one shot on ListComplete (ReplaceAgentProfiles), so events the agent has
+ // evicted from its disk drop out instead of lingering as unservable entries. The per-round
+ // accumulation lives in the pressure stream handler's local state, not here.
+ cache map[string]map[string]*AggregatedPressureProfile
+ log *logger.Logger
+ cacheMu sync.RWMutex
+ mu sync.RWMutex
+}
+
+// NewAggregator creates a new Aggregator instance.
+func NewAggregator(reg *registry.AgentRegistry, grpcService RequestSender, log *logger.Logger) *Aggregator {
+ return &Aggregator{
+ registry: reg,
+ grpcService: grpcService,
+ log: log,
+ cache: make(map[string]map[string]*AggregatedPressureProfile),
+ }
+}
+
+// SetGRPCService sets the gRPC service used to request profiles from agents.
+func (a *Aggregator) SetGRPCService(grpcService RequestSender) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.grpcService = grpcService
+}
+
+// RemoveAgent drops all cached events for an agent (called on disconnect).
+func (a *Aggregator) RemoveAgent(agentID string) {
+ a.cacheMu.Lock()
+ defer a.cacheMu.Unlock()
+ delete(a.cache, agentID)
+}
+
+// ReplaceAgentProfiles replaces an agent's whole cached set with the records of its just-completed
+// list round, enriched with the agent's pod name and role. An empty round drops the agent's entry.
+// Called on ListComplete with the records accumulated by the pressure stream handler for that round,
+// so events the agent has evicted from its disk drop out instead of lingering as unservable entries.
+func (a *Aggregator) ReplaceAgentProfiles(agentID string, agentInfo *registry.AgentInfo, records []*fodcv1.PressureProfileRecord) {
+ byProfile := make(map[string]*AggregatedPressureProfile, len(records))
+ for _, record := range records {
+ if record == nil {
+ continue
+ }
+ byProfile[record.ProfileId] = buildAggregated(agentID, agentInfo, record)
+ }
+
+ a.cacheMu.Lock()
+ defer a.cacheMu.Unlock()
+ if len(byProfile) == 0 {
+ delete(a.cache, agentID)
+ return
+ }
+ a.cache[agentID] = byProfile
+}
+
+// buildAggregated converts one wire record into a cache entry enriched with the agent's identity.
+func buildAggregated(agentID string, agentInfo *registry.AgentInfo, record *fodcv1.PressureProfileRecord) *AggregatedPressureProfile {
+ profiles := make([]ProfileInfo, 0, len(record.Profiles))
+ for _, p := range record.Profiles {
+ profiles = append(profiles, ProfileInfo{
+ Type: p.Type,
+ Filename: p.Filename,
+ Filepath: p.Filepath,
+ Format: p.Format,
+ SizeBytes: p.SizeBytes,
+ })
+ }
+ agg := &AggregatedPressureProfile{
+ AgentID: agentID,
+ PodName: agentInfo.AgentIdentity.PodName,
+ Role: agentInfo.AgentIdentity.Role,
+ ProfileID: record.ProfileId,
+ SourceEndpoint: record.SourceEndpoint,
+ RSSBytes: record.RssBytes,
+ CgroupLimitBytes: record.CgroupLimitBytes,
+ TriggerPercent: record.TriggerPercent,
+ ThresholdBytes: record.ThresholdBytes,
+ Profiles: profiles,
+ }
+ if record.CapturedAt != nil {
+ agg.CapturedAt = record.CapturedAt.AsTime()
+ }
+ return agg
+}
+
+// CollectProfiles triggers a refresh from all matching agents, waits a short window for
+// their metadata to arrive, then returns the current cache snapshot.
+func (a *Aggregator) CollectProfiles(ctx context.Context, filter *Filter) ([]*AggregatedPressureProfile, error) {
+ a.mu.RLock()
+ grpcService := a.grpcService
+ a.mu.RUnlock()
+ if grpcService == nil {
+ a.log.Warn().Msg("Pressure gRPC service not configured yet, returning cached snapshot")
+ return a.snapshotCache(filter), nil
+ }
+
+ agents := a.getFilteredAgents(filter)
+ // Nothing to request when no agent matched, so nothing new will arrive: skip the wait.
+ if len(agents) == 0 {
+ return a.snapshotCache(filter), nil
+ }
+ agentIDs := make([]string, 0, len(agents))
+ for _, agentInfo := range agents {
+ agentIDs = append(agentIDs, agentInfo.AgentID)
+ }
+
+ // Return as soon as every contacted agent has finished streaming its metadata; listTimeout
+ // is only a fallback for an agent that never reports completion (e.g. it disconnected).
+ select {
+ case <-grpcService.CollectList(agentIDs):
+ case <-time.After(listTimeout):
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+
+ return a.snapshotCache(filter), nil
+}
+
+// LookupForDownload resolves a download target: the agent currently online for podName
+// (download routes by the stable pod name, not the volatile agent id), and the on-disk
+// filepath of the requested profile from the cache.
+func (a *Aggregator) LookupForDownload(podName, profileID, profType string) (agentID, filepath, role string, ok bool) {
+ agents := a.getFilteredAgents(&Filter{PodName: podName})
+ if len(agents) == 0 {
+ return "", "", "", false
+ }
+ agentID = agents[0].AgentID
+ role = agents[0].AgentIdentity.Role
+
+ a.cacheMu.RLock()
+ defer a.cacheMu.RUnlock()
+ // Keyed by the currently-online agent_id, so a stale entry from a previous connection (the
+ // agent gets a fresh agent_id on reconnect) can never be served.
+ rec := a.cache[agentID][profileID]
+ if rec == nil || !strings.EqualFold(rec.PodName, podName) {
+ return "", "", "", false
+ }
+ for _, p := range rec.Profiles {
+ if p.Type == profType {
+ return agentID, p.Filepath, role, true
+ }
+ }
+ return "", "", "", false
+}
+
+// snapshotCache returns a copy of all cached events matching the filter.
+func (a *Aggregator) snapshotCache(filter *Filter) []*AggregatedPressureProfile {
+ a.cacheMu.RLock()
+ defer a.cacheMu.RUnlock()
+
+ result := make([]*AggregatedPressureProfile, 0)
+ for _, byProfile := range a.cache {
+ for _, rec := range byProfile {
+ if filter != nil {
+ if filter.Role != "" && !strings.EqualFold(rec.Role, filter.Role) {
+ continue
+ }
+ if filter.PodName != "" && !strings.EqualFold(rec.PodName, filter.PodName) {
+ continue
+ }
+ }
+ result = append(result, rec)
+ }
+ }
+ return result
+}
+
+// getFilteredAgents returns the registered agents matching the filter.
+func (a *Aggregator) getFilteredAgents(filter *Filter) []*registry.AgentInfo {
+ if filter == nil {
+ return a.registry.ListAgents()
+ }
+ var agents []*registry.AgentInfo
+ if filter.Role != "" {
+ agents = a.registry.ListAgentsByRole(filter.Role)
+ } else {
+ agents = a.registry.ListAgents()
+ }
+ if filter.PodName != "" {
+ filtered := make([]*registry.AgentInfo, 0)
+ for _, agentInfo := range agents {
+ if strings.EqualFold(agentInfo.AgentIdentity.PodName, filter.PodName) {
+ filtered = append(filtered, agentInfo)
+ }
+ }
+ agents = filtered
+ }
+ return agents
+}
diff --git a/fodc/proxy/internal/pressure/aggregator_test.go b/fodc/proxy/internal/pressure/aggregator_test.go
new file mode 100644
index 000000000..6f273f376
--- /dev/null
+++ b/fodc/proxy/internal/pressure/aggregator_test.go
@@ -0,0 +1,99 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package pressure
+
+import (
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+ "github.com/apache/skywalking-banyandb/fodc/proxy/internal/registry"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+)
+
+func newTestAggregator(t *testing.T) *Aggregator {
+ t.Helper()
+ require.NoError(t, logger.Init(logger.Logging{Env: "dev", Level: "error"}))
+ reg := registry.NewAgentRegistry(logger.GetLogger("test"), time.Minute, 2*time.Minute, 10)
+ return NewAggregator(reg, nil, logger.GetLogger("test"))
+}
+
+func agentInfo(podName string) *registry.AgentInfo {
+ return ®istry.AgentInfo{AgentIdentity: registry.AgentIdentity{PodName: podName, Role: "ROLE_DATA"}}
+}
+
+func record(profileID string) *fodcv1.PressureProfileRecord {
+ return &fodcv1.PressureProfileRecord{ProfileId: profileID}
+}
+
+func profileIDs(records []*AggregatedPressureProfile) map[string]struct{} {
+ out := make(map[string]struct{}, len(records))
+ for _, r := range records {
+ out[r.ProfileID] = struct{}{}
+ }
+ return out
+}
+
+func recs(ids ...string) []*fodcv1.PressureProfileRecord {
+ out := make([]*fodcv1.PressureProfileRecord, 0, len(ids))
+ for _, id := range ids {
+ out = append(out, record(id))
+ }
+ return out
+}
+
+// TestReplaceAgentProfilesDropsEvicted pins the stale-cache fix: a later round that no longer
+// reports a profile drops it from the cache, and an empty round removes the agent entirely.
+func TestReplaceAgentProfilesDropsEvicted(t *testing.T) {
+ a := newTestAggregator(t)
+ info := agentInfo("pod-1")
+
+ a.ReplaceAgentProfiles("agent-1", info, recs("evt-a", "evt-b"))
+ assert.Equal(t, map[string]struct{}{"evt-a": {}, "evt-b": {}}, profileIDs(a.snapshotCache(nil)))
+
+ // evt-a was evicted on the agent's disk, so the next round reports only evt-b.
+ a.ReplaceAgentProfiles("agent-1", info, recs("evt-b"))
+ assert.Equal(t, map[string]struct{}{"evt-b": {}}, profileIDs(a.snapshotCache(nil)), "evicted evt-a must be dropped")
+
+ // An empty round drops the agent's entry entirely.
+ a.ReplaceAgentProfiles("agent-1", info, nil)
+ assert.Empty(t, a.snapshotCache(nil))
+}
+
+// TestReplaceAgentProfilesIsPerAgent verifies replacing one agent's set does not disturb another's.
+func TestReplaceAgentProfilesIsPerAgent(t *testing.T) {
+ a := newTestAggregator(t)
+ a.ReplaceAgentProfiles("agent-1", agentInfo("pod-1"), recs("a1"))
+ a.ReplaceAgentProfiles("agent-2", agentInfo("pod-2"), recs("a2"))
+ assert.Equal(t, map[string]struct{}{"a1": {}, "a2": {}}, profileIDs(a.snapshotCache(nil)))
+
+ a.ReplaceAgentProfiles("agent-1", agentInfo("pod-1"), nil)
+ assert.Equal(t, map[string]struct{}{"a2": {}}, profileIDs(a.snapshotCache(nil)))
+}
+
+// TestRemoveAgent drops the agent's cached set on disconnect.
+func TestRemoveAgent(t *testing.T) {
+ a := newTestAggregator(t)
+ a.ReplaceAgentProfiles("agent-1", agentInfo("pod-1"), recs("a1"))
+ assert.NotEmpty(t, a.snapshotCache(nil))
+ a.RemoveAgent("agent-1")
+ assert.Empty(t, a.snapshotCache(nil))
+}
diff --git a/test/e2e-v2/cases/fodc-pressure/banyandb-cluster.yaml b/test/e2e-v2/cases/fodc-pressure/banyandb-cluster.yaml
new file mode 100644
index 000000000..49f05ca82
--- /dev/null
+++ b/test/e2e-v2/cases/fodc-pressure/banyandb-cluster.yaml
@@ -0,0 +1,98 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Minimal topology for the memory-pressure pprof e2e: a single standalone BanyanDB
+# node co-located with a fodc-agent sidecar, plus the fodc-proxy (deployed
+# separately). The pressure check only needs ONE node that (a) has a cgroup memory
+# limit so banyandb_memory_protector_cgroup_limit_bytes is non-zero, and (b) serves
+# pprof + cluster-state gRPC so the agent resolves a role and connects to the proxy.
+# Standalone keeps it to a single pod: no etcd, no node-discovery file, no second
+# node, and no BanyanDB Service (the agent reaches banyand over localhost in the
+# shared pod; only the fodc-proxy needs a Service).
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: banyandb-standalone
+ labels:
+ app: banyandb-standalone
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app: banyandb-standalone
+ template:
+ metadata:
+ labels:
+ app: banyandb-standalone
+ spec:
+ shareProcessNamespace: true
+ containers:
+ - name: banyand
+ image: apache/skywalking-banyandb:latest
+ imagePullPolicy: IfNotPresent
+ args:
+ - standalone
+ ports:
+ - { name: grpc, containerPort: 17912 }
+ - { name: metrics, containerPort: 2121 }
+ - { name: pprof, containerPort: 6060 }
+ # A cgroup memory limit is the whole point: it makes the protector expose a
+ # non-zero banyandb_memory_protector_cgroup_limit_bytes for the agent to read.
+ resources:
+ limits:
+ memory: 512Mi
+ cpu: "1"
+ requests:
+ memory: 256Mi
+ cpu: "250m"
+ - name: fodc-agent
+ image: apache/skywalking-banyandb-fodc-agent:latest
+ imagePullPolicy: IfNotPresent
+ args:
+ - --poll-metrics-ports=2121
+ - --poll-metrics-interval=2s
+ - --cluster-state-ports=17912
+ - --cluster-state-poll-interval=10s
+ - --proxy-addr=fodc-proxy:17912
+ - --prometheus-listen-addr=:9090
+ - --heartbeat-interval=5s
+ - --pod-name=$(POD_NAME)
+ # trigger-percent=1: any RSS above 1% of the memory limit captures, so a
+ # capture fires deterministically without artificially stressing memory.
+ - --pressure-profiler-trigger-percent=1
+ - --pressure-profiler-pprof-port=6060
+ - --pressure-profiler-cooldown=10s
+ - --pressure-profiler-dir=/tmp/pressure-profiles
+ env:
+ - name: POD_NAME
+ valueFrom:
+ fieldRef:
+ fieldPath: metadata.name
+ ports:
+ - { name: fodc-metrics, containerPort: 9090 }
+ volumeMounts:
+ # Writable volume for captured pprof profiles (agent rootfs is read-only).
+ - name: pressure-profiles
+ mountPath: /tmp/pressure-profiles
+ resources:
+ limits:
+ memory: 256Mi
+ cpu: "500m"
+ requests:
+ memory: 64Mi
+ cpu: "100m"
+ volumes:
+ - name: pressure-profiles
+ emptyDir: {}
diff --git a/test/e2e-v2/cases/fodc-pressure/check-pressure.sh b/test/e2e-v2/cases/fodc-pressure/check-pressure.sh
new file mode 100755
index 000000000..8d7b0ce5d
--- /dev/null
+++ b/test/e2e-v2/cases/fodc-pressure/check-pressure.sh
@@ -0,0 +1,123 @@
+#!/bin/bash
+
+# Licensed to Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# End-to-end verification of the memory-pressure pprof feature against a real
+# BanyanDB cluster + fodc-agent + fodc-proxy. All diagnostics go to stderr so the
+# only stdout on success is the single line "status: passed" that infra-e2e
+# compares against expected/pressure-status.yml; any failed assertion exits non-zero.
+
+set -euo pipefail
+
+NS=${NS:-default}
+AGENT_CONTAINER=${AGENT_CONTAINER:-fodc-agent}
+# infra-e2e exposes service/fodc-proxy:17913 and sets these env vars (dashes -> underscores).
+PROXY_HOST=${service_fodc_proxy_host:-127.0.0.1}
+PROXY_PORT=${service_fodc_proxy_17913:-17913}
+PROXY_HTTP="http://${PROXY_HOST}:${PROXY_PORT}"
+MAX_WAIT=${MAX_WAIT:-180}
+SLEEP=${SLEEP:-5}
+
+log() { echo "[check-pressure] $*" >&2; }
+
+POD="$(kubectl get pod -n "${NS}" -l app=banyandb-standalone -o jsonpath='{.items[0].metadata.name}')"
+[ -n "${POD}" ] || { log "no banyandb-standalone pod found"; exit 1; }
+log "using data pod ${POD}, proxy ${PROXY_HTTP}"
+
+# 1) Wait until the agent reports at least one capture via its own /metrics.
+deadline=$((SECONDS + MAX_WAIT))
+captured=0
+while [ "${SECONDS}" -lt "${deadline}" ]; do
+ # `|| true` keeps a transient kubectl/wget failure (pod not ready yet) from tripping
+ # `set -e`/pipefail and aborting the poll loop instead of retrying.
+ total="$(kubectl exec -n "${NS}" "${POD}" -c "${AGENT_CONTAINER}" -- sh -c 'wget -qO- http://localhost:9090/metrics' 2>/dev/null \
+ | awk '/^fodc_agent_pressure_capture_total/ {print $2; exit}' || true)"
+ if [ -n "${total}" ] && awk -v v="${total}" 'BEGIN { exit (v >= 1) ? 0 : 1 }'; then
+ captured=1
+ log "fodc_agent_pressure_capture_total=${total}"
+ break
+ fi
+ sleep "${SLEEP}"
+done
+if [ "${captured}" != 1 ]; then
+ log "no pressure capture observed within ${MAX_WAIT}s; recent agent logs:"
+ kubectl logs -n "${NS}" "${POD}" -c "${AGENT_CONTAINER}" --tail=100 >&2 || true
+ exit 1
+fi
+
+# 2) The captured profile files exist on the agent's volume.
+evtdir="$(kubectl exec -n "${NS}" "${POD}" -c "${AGENT_CONTAINER}" -- sh -c 'ls -d /tmp/pressure-profiles/*/ 2>/dev/null | head -1' | tr -d '\r')"
+[ -n "${evtdir}" ] || { log "no capture event directory on agent volume"; exit 1; }
+files="$(kubectl exec -n "${NS}" "${POD}" -c "${AGENT_CONTAINER}" -- sh -c "ls '${evtdir}'")"
+for f in heap.pprof goroutine.pprof meta.json; do
+ echo "${files}" | grep -q "${f}" || { log "missing ${f} in ${evtdir}"; exit 1; }
+done
+log "event dir ${evtdir} has heap.pprof, goroutine.pprof, meta.json"
+
+# 3) meta.json reflects a real cgroup limit and both profiles.
+meta="$(kubectl exec -n "${NS}" "${POD}" -c "${AGENT_CONTAINER}" -- sh -c "cat '${evtdir}meta.json'")"
+echo "${meta}" | python3 -c '
+import sys, json
+m = json.load(sys.stdin)
+assert m["cgroupLimitBytes"] > 0, "cgroupLimitBytes must be positive (cgroup limit set)"
+assert m["rssBytes"] > 0, "rssBytes must be positive"
+assert len(m["profiles"]) == 2, "expected heap + goroutine"
+'
+log "meta.json: cgroupLimitBytes>0, 2 profiles"
+
+# 4) The proxy lists the event metadata over HTTP.
+list="$(curl -sf "${PROXY_HTTP}/pressure-profiles")"
+echo "${list}" | python3 -c '
+import sys, json
+recs = json.load(sys.stdin)
+assert len(recs) >= 1, "proxy listed no pressure profiles"
+r = next(x for x in recs if len(x["profiles"]) == 2)
+assert r["cgroup_limit_bytes"] > 0
+heap = next(p for p in r["profiles"] if p["type"] == "heap")
+assert heap["size_bytes"] > 0, "listed heap size_bytes must be positive"
+with open("/tmp/pp_target.txt", "w") as fh:
+ fh.write(r["pod_name"] + " " + r["profile_id"] + " " + str(heap["size_bytes"]) + "\n")
+'
+read -r TARGET_POD TARGET_ID TARGET_HEAP_SIZE < /tmp/pp_target.txt
+log "proxy /pressure-profiles lists pod=${TARGET_POD} id=${TARGET_ID} heap_size=${TARGET_HEAP_SIZE}"
+
+# 5) Download a profile through the proxy and confirm it is a complete, valid pprof.
+# No -f: capture the status code ourselves so a non-200 surfaces clearly (the || only trips
+# on a transport-level failure, e.g. connection refused).
+http_code="$(curl -s -o /tmp/pressure-heap.pprof -w '%{http_code}' \
+ "${PROXY_HTTP}/pressure-profiles/${TARGET_POD}/${TARGET_ID}/heap")" \
+ || { log "heap download request failed (curl exit $?)"; exit 1; }
+[ "${http_code}" = "200" ] || { log "heap download returned HTTP ${http_code}, want 200; body:"; cat /tmp/pressure-heap.pprof >&2 || true; exit 1; }
+
+# The body must be non-empty and its byte count must match the size the proxy advertised in
+# the listing, proving the whole stream arrived rather than a truncated or empty body.
+[ -s /tmp/pressure-heap.pprof ] || { log "downloaded heap profile is empty"; exit 1; }
+dl_size="$(wc -c < /tmp/pressure-heap.pprof | tr -d ' ')"
+[ "${dl_size}" = "${TARGET_HEAP_SIZE}" ] \
+ || { log "downloaded heap size ${dl_size} != advertised ${TARGET_HEAP_SIZE}"; exit 1; }
+
+# Parse it with pprof, keeping the output and checking the exit status explicitly (piping to
+# /dev/null would hide a parse failure). A real heap profile exposes an "inuse_space" sample
+# type, so assert on the content too, not just the exit code.
+if ! raw="$(go tool pprof -raw /tmp/pressure-heap.pprof 2>&1)"; then
+ log "go tool pprof failed to parse heap.pprof: ${raw}"
+ exit 1
+fi
+grep -q "Samples:" <<<"${raw}" || { log "pprof output has no 'Samples:' section: ${raw}"; exit 1; }
+grep -q "inuse_space" <<<"${raw}" || { log "pprof output missing heap 'inuse_space' sample type"; exit 1; }
+log "downloaded heap.pprof OK: ${dl_size} bytes, matches listing, valid pprof with inuse_space"
+
+echo "status: passed"
diff --git a/test/e2e-v2/cases/fodc-pressure/e2e.yaml b/test/e2e-v2/cases/fodc-pressure/e2e.yaml
new file mode 100644
index 000000000..92545e8c8
--- /dev/null
+++ b/test/e2e-v2/cases/fodc-pressure/e2e.yaml
@@ -0,0 +1,68 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# FODC memory-pressure pprof e2e: a real 1:1 BanyanDB liaison/data cluster (each
+# node has a cgroup memory limit, so banyandb_memory_protector_cgroup_limit_bytes is
+# non-zero), a fodc-agent sidecar per node with the pressure profiler enabled at
+# trigger-percent=1 (any RSS above 1% of the limit captures), and a fodc-proxy.
+# No OAP/load apps are needed: the trigger fires on memory usage, not traffic.
+# It reuses the shared manifests under cases/fodc/. check-pressure.sh verifies the
+# full chain: real capture on disk -> proxy list metadata -> proxy stream-download
+# -> the downloaded bytes parse as a valid pprof.
+
+setup:
+ env: kind
+ file: ../fodc/kind.yaml
+ timeout: 20m
+ init-system-environment: ../../script/env
+ kind:
+ import-images:
+ - apache/skywalking-banyandb:latest
+ - apache/skywalking-banyandb-fodc-agent:latest
+ - apache/skywalking-banyandb-fodc-proxy:latest
+ expose-ports:
+ - namespace: default
+ resource: service/fodc-proxy
+ port: 17913
+ steps:
+ - name: set PATH
+ command: export PATH=/tmp/skywalking-infra-e2e/bin:$PATH
+ - name: install yq
+ command: bash test/e2e-v2/script/prepare/setup-e2e-shell/install.sh yq
+ - name: install kubectl
+ command: bash test/e2e-v2/script/prepare/setup-e2e-shell/install.sh kubectl
+ - name: Deploy FODC proxy
+ command: kubectl apply -f test/e2e-v2/cases/fodc/fodc-proxy.yaml
+ - name: Deploy standalone BanyanDB with FODC agent sidecar
+ command: kubectl apply -f test/e2e-v2/cases/fodc-pressure/banyandb-cluster.yaml
+ - name: Wait for all workloads to be ready
+ command: |
+ kubectl rollout status deployment/fodc-proxy --timeout=180s
+ kubectl rollout status deployment/banyandb-standalone --timeout=300s
+ wait:
+ - namespace: default
+ resource: deployment/fodc-proxy
+ for: condition=available
+ - namespace: default
+ resource: deployment/banyandb-standalone
+ for: condition=available
+
+verify:
+ retry:
+ count: 20
+ interval: 10s
+ cases:
+ - query: bash test/e2e-v2/cases/fodc-pressure/check-pressure.sh
+ expected: expected/pressure-status.yml
diff --git a/test/e2e-v2/cases/fodc-pressure/expected/pressure-status.yml b/test/e2e-v2/cases/fodc-pressure/expected/pressure-status.yml
new file mode 100644
index 000000000..4ee44bd2b
--- /dev/null
+++ b/test/e2e-v2/cases/fodc-pressure/expected/pressure-status.yml
@@ -0,0 +1,16 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+status: passed