Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,7 @@ Process-level information collected from `/proc` filesystem for each Apache Clou
| `proc_status` | `ProcStatus` | Contents of `/proc/pid/status`. |
| `proc_io` | `ProcIO` | Contents of `/proc/pid/io`. |
| `proc_spill` | `ProcSpill` | Spill file information. |
| `ccnt` | `int32` | Apache Cloudberry command count parsed from cmdline (-1 if not available). |
| `ccnt` | `int32` | Apache Cloudberry command count, normally parsed from cmdline (-1 if unavailable). Active coordinator samples can be reconciled with collector query identity when the title lags by one. |
| `slice_id` | `int64` | Apache Cloudberry slice ID parsed from cmdline (-1 if not available). |

### RuntimeMetrics
Expand Down
2 changes: 2 additions & 0 deletions docs/performance-tuning.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,8 @@ When enabled, the coordinator periodically queries each segment host for `/proc/
- The cluster has many segment hosts and the extra gRPC calls add noticeable load.
- You are running on a non-Linux platform where `/proc` is unavailable.

The process inventory is refreshed at the same cadence as procfs samples. The query runtime matrix polls every five seconds while the query is running, but it can only display processes discovered by these samples. Queries shorter than the configured sampling interval may not appear. Coordinator command counts are reconciled only against an active collector query on the same backend when the process title lags by one. The backend and command identity must remain unchanged from before collection through reconciliation; otherwise the original sample identity is retained. When the query is reported complete, the matrix fetches its data once more before stopping polling.

**Adjust the interval** to balance freshness vs. load. A shorter interval gives more responsive EMA values but increases gRPC traffic to segment hosts.

---
Expand Down
2 changes: 1 addition & 1 deletion docs/proc-stats-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ Apache Cloudberry coordinator.
| Item | Location |
|------|----------|
| Cloudberry/GP6 query text | `cloudberryAllSessionsQuery` / `gp6AllSessionsQuery` in [internal/gp/stat_activity/lister.go](../internal/gp/stat_activity/lister.go) |
| Polling cadence | `WithBackgroundAllSessionsCollectionInterval` (default `60s`, see `newBackgroundAllSessions` in [internal/gp/stat_activity/lister.go](../internal/gp/stat_activity/lister.go)) |
| Polling cadence | The running agent sets `WithBackgroundAllSessionsCollectionInterval` from `procfs_refresh_interval` (default `60s`; standalone lister default also `60s`, see `newBackgroundAllSessions` in [internal/gp/stat_activity/lister.go](../internal/gp/stat_activity/lister.go)) |
| Cache TTL | `WithBackgroundAllSessionsCacheTTL` (default `600s`) |
| Row type | `SessionPid{GpSegmentId, Pid, SessId, BackendType}` in [internal/gp/stat_activity/models.go](../internal/gp/stat_activity/models.go) |
| Read accessor | `Lister.ListAllSessions(ctx)` |
Expand Down
6 changes: 5 additions & 1 deletion internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,11 @@ func Run(ctx context.Context, configFile string) error {
coordinatorConnection := gp.NewConnection(baseApp.L(), &cfg.CoordinatorConnection, nil)

coordinatorSentinel := coordinator_sentinel.NewSentinel(baseApp.L(), coordinatorConnection)
statActivityLister := stat_activity.NewLister(baseApp.L(), coordinatorConnection)
var activityOptions []stat_activity.Option
if cfg.ProcfsEnabled {
activityOptions = append(activityOptions, stat_activity.WithBackgroundAllSessionsCollectionInterval(cfg.ProcfsRefreshInterval))
}
statActivityLister := stat_activity.NewLister(baseApp.L(), coordinatorConnection, activityOptions...)
workFileLister := workfile_usage.NewLister(baseApp.L(), coordinatorConnection)
backgroundStorage := coordinator.NewBackgroundStorage(logger, sessionsStorage, rqStorage, aggStorage, procfsStorage, statActivityLister, workFileLister)

Expand Down
2 changes: 2 additions & 0 deletions internal/coordinator/background.go
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,7 @@ func (bs *BackgroundStorage) RefreshProcfs(ctx context.Context, procfsRefreshInt
go func() {
hostStatsCh <- procfsGatherer.GatherHostStatForHosts(ctx, nPullers, portn, procfsRefreshInterval, msgSize, storage.GetConfiguredHostnames())
}()
identityBefore := snapshotCoordinatorProcfsIdentity(bs.SessionStorage)
result, err := procfsGatherer.GatherProcfsStat(ctx, nPullers, portn, procfsRefreshInterval, msgSize, !extendedProcfsStat)
hostStats := <-hostStatsCh
if err != nil {
Expand All @@ -908,6 +909,7 @@ func (bs *BackgroundStorage) RefreshProcfs(ctx context.Context, procfsRefreshInt
enrichWithWorkfileUsage(result, usageEntries)
}

correlateCoordinatorProcfs(result, bs.SessionStorage, identityBefore)
bs.procfsStorage.RegisterProcfsStatWithHostStat(currTime, result, hostStats, procfsGatherer.LastHostsExpected(), procfsGatherer.LastHostsResponded())
// measure only successful latencies
if metrics.YagpccMetrics != nil {
Expand Down
81 changes: 81 additions & 0 deletions internal/coordinator/procfs_query_identity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// 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.

package coordinator

import (
"strings"

pbm "github.com/apache/cloudberry-command-center/api/proto/agent_coordinator"
pbc "github.com/apache/cloudberry-command-center/api/proto/common"
"github.com/apache/cloudberry-command-center/internal/gp"
)

// Keep the session object as well as PID/command identity: a replaced session
// must not inherit a sample collected for an earlier backend.
type coordinatorProcfsIdentity struct {
session *gp.SessionInfo
pid int64
ccnt int32
}

func snapshotCoordinatorProcfsIdentity(sessions *gp.SessionsStorage) map[gp.SessionKey]coordinatorProcfsIdentity {
snapshot := make(map[gp.SessionKey]coordinatorProcfsIdentity)
if sessions == nil {
return snapshot
}
for key, info := range sessions.GetSessions() {
info.SessionLock.RLock()
activity := info.SessionData.GpStatInfo
ccnt := gp.GetRunningCcnt(&info.SessionData, pbm.RunningQueryType_RQT_TOP)
if activity != nil && len(info.SessionData.RunningQueries.Ccnts) > 0 && ccnt > 0 {
snapshot[key] = coordinatorProcfsIdentity{session: info, pid: int64(activity.Pid), ccnt: ccnt}
}
info.SessionLock.RUnlock()
}
return snapshot
}

// A simple-protocol QD title can precede CreateQueryDesc's command increment.
// Correct only that one-step lag when collector state identifies a running
// query on the same backend before and after collection. Never change QE,
// idle, unknown, unrelated or concurrently changed rows.
func correlateCoordinatorProcfs(procs []*pbc.GpPidProcInfo, sessions *gp.SessionsStorage, before map[gp.SessionKey]coordinatorProcfsIdentity) {
if sessions == nil {
return
}
for _, proc := range procs {
if proc == nil || proc.GpSegmentId != -1 || proc.Ccnt < 0 || proc.State == "" || strings.HasPrefix(strings.ToLower(proc.State), "idle") {
continue
}
key := gp.SessionKey{SessID: int(proc.SessId)}
previous, captured := before[key]
if !captured {
continue
}
info, ok := sessions.GetSession(key)
if !ok {
continue
}
info.SessionLock.RLock()
activity := info.SessionData.GpStatInfo
ccnt := gp.GetRunningCcnt(&info.SessionData, pbm.RunningQueryType_RQT_TOP)
if previous.session == info && previous.pid == proc.Pid && previous.ccnt == ccnt && activity != nil && int64(activity.Pid) == proc.Pid && len(info.SessionData.RunningQueries.Ccnts) > 0 && ccnt > 0 && proc.Ccnt == ccnt-1 {
proc.Ccnt = ccnt
}
info.SessionLock.RUnlock()
}
}
88 changes: 88 additions & 0 deletions internal/coordinator/procfs_query_identity_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// 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.

package coordinator

import (
pbc "github.com/apache/cloudberry-command-center/api/proto/common"
"github.com/apache/cloudberry-command-center/internal/gp"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"testing"
)

func TestCoordinatorProcfsIdentity(t *testing.T) {
for _, tc := range []struct {
name string
segment int64
pid int64
ccnt int32
state string
running bool
want int32
}{
{"simple query lag", -1, 42, 1, "SELECT", true, 2},
{"already exact", -1, 42, 2, "SELECT", true, 2},
{"older command", -1, 42, 0, "SELECT", true, 0},
{"different backend", -1, 43, 1, "SELECT", true, 1},
{"idle", -1, 42, 1, "idle", true, 1},
{"unknown state", -1, 42, 1, "", true, 1},
{"unknown command", -1, 42, -1, "SELECT", true, -1},
{"executor", 0, 42, 1, "SELECT", true, 1},
{"completed query", -1, 42, 1, "SELECT", false, 1},
} {
t.Run(tc.name, func(t *testing.T) {
s := gp.NewSessionsStorage(zap.NewNop().Sugar(), nil, nil)
require.NoError(t, s.RefreshSessionList([]*gp.GpStatActivity{{SessID: 10, Pid: 42, Usename: "test"}}, true))
info, ok := s.GetSession(gp.SessionKey{SessID: 10})
require.True(t, ok)
if tc.running {
info.SessionData.RunningQueries.SetCurrentQuery(2, 0)
}
proc := &pbc.GpPidProcInfo{GpSegmentId: tc.segment, SessId: 10, Pid: tc.pid, Ccnt: tc.ccnt, State: tc.state}
correlateCoordinatorProcfs([]*pbc.GpPidProcInfo{proc}, s, snapshotCoordinatorProcfsIdentity(s))
require.Equal(t, tc.want, proc.Ccnt)
})
}
}

func TestCoordinatorProcfsIdentityChangesDuringCollection(t *testing.T) {
for _, change := range []string{"next command", "completed", "backend changed", "started during collection"} {
t.Run(change, func(t *testing.T) {
s := gp.NewSessionsStorage(zap.NewNop().Sugar(), nil, nil)
require.NoError(t, s.RefreshSessionList([]*gp.GpStatActivity{{SessID: 10, Pid: 42, Usename: "test"}}, true))
info, ok := s.GetSession(gp.SessionKey{SessID: 10})
require.True(t, ok)
if change != "started during collection" {
info.SessionData.RunningQueries.SetCurrentQuery(2, 0)
}
before := snapshotCoordinatorProcfsIdentity(s)
proc := &pbc.GpPidProcInfo{GpSegmentId: -1, SessId: 10, Pid: 42, Ccnt: 2, State: "SELECT"}
info.SessionLock.Lock()
switch change {
case "next command", "started during collection":
info.SessionData.RunningQueries.SetCurrentQuery(3, 0)
case "completed":
info.SessionData.RunningQueries.Ccnts = nil
case "backend changed":
info.SessionData.GpStatInfo.Pid = 43
}
info.SessionLock.Unlock()
correlateCoordinatorProcfs([]*pbc.GpPidProcInfo{proc}, s, before)
require.Equal(t, int32(2), proc.Ccnt)
})
}
}
3 changes: 3 additions & 0 deletions internal/utils/procfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,9 @@ func getProcInfoWithMode(logger *zap.SugaredLogger, proc procfs.Proc, pid, gpSeg
if ccnt, ok := ParseCmdLineCommandCount(info.Cmdline); ok {
info.Ccnt = ccnt
info.SliceId = ProcfsQuerySegmentSliceID
if gpSegmentID == -1 {
info.SliceId = 0
}
}
if sliceID, ok := ParseCmdLineSliceID(info.Cmdline); ok {
info.SliceId = sliceID
Expand Down
19 changes: 19 additions & 0 deletions internal/utils/procfs_getprocinfo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -478,3 +478,22 @@ func TestGetProcInfo_MultiWordCmdline(t *testing.T) {
// Not a session cmdline, so state should be empty.
assert.Empty(t, info.State)
}

func TestCoordinatorDefaultSlice(t *testing.T) {
for _, tc := range []struct {
cmdline string
want int64
}{
{"postgres: con21 cmd2 SELECT", 0},
{"postgres: con21 cmd2 slice3 SELECT", 3},
} {
fake := newFakeProcDir(t, 42)
fake.writeFile(t, "cmdline", tc.cmdline)
fake.writeFile(t, "stat", sampleStat(42))
fake.writeFile(t, "status", sampleStatus(42))
fake.writeFile(t, "io", sampleIO())
info, err := getProcInfo(zap.NewNop().Sugar(), fake.proc(t), 42, -1, 21)
require.NoError(t, err)
require.Equal(t, tc.want, info.SliceId)
}
}
7 changes: 7 additions & 0 deletions web/src/hooks/useApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { useState, useEffect, useCallback, useRef } from "react";
export function useApi<T>(
fetcher: () => Promise<T>,
deps: unknown[] = [],
pollIntervalMs = 0,
) {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
Expand Down Expand Up @@ -58,5 +59,11 @@ export function useApi<T>(
refresh();
}, [refresh]);

useEffect(() => {
if (pollIntervalMs <= 0 || loading) return;
const timer = window.setTimeout(refresh, pollIntervalMs);
return () => window.clearTimeout(timer);
}, [pollIntervalMs, loading, refresh]);

return { data, loading, error, refresh };
}
20 changes: 14 additions & 6 deletions web/src/pages/QueryDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import {
Empty,
} from "antd";
import { ArrowLeftOutlined, StopOutlined, SwapOutlined } from "@ant-design/icons";
import { Fragment, useState } from "react";
import { Fragment, useEffect, useState } from "react";
import { useApi } from "../hooks/useApi";
import {
getQuery,
Expand Down Expand Up @@ -82,13 +82,14 @@ function runtimeCellColor(metrics: RuntimeMetrics | null | undefined, maxCPU: nu
return "#d7edca";
}

function RuntimeMetricsMatrix({ ssid, ccnt }: { ssid: number; ccnt: number }) {
function RuntimeMetricsMatrix({ ssid, ccnt, completed }: { ssid: number; ccnt: number; completed: boolean }) {
const { mode } = useTheme();
const colors = getColors(mode);
const [selectedCell, setSelectedCell] = useState<RuntimeMetricsCell | null>(null);
const [selectedCellKey, setSelectedCell] = useState<{ sliceId: number; segindex: number } | null>(null);
const { data, loading, error } = useApi(
() => getQueryRunningMetrics(ssid, ccnt),
[ssid, ccnt],
[ssid, ccnt, completed],
completed ? 0 : 5000,
);

const response = data as QueryRunningMetricsResponse | null;
Expand All @@ -101,6 +102,7 @@ function RuntimeMetricsMatrix({ ssid, ccnt }: { ssid: number; ccnt: number }) {
const segindexes = Array.from(new Set(response?.segindex ?? [])).sort((a, b) => a - b);
const sliceIds = Array.from(new Set(response?.sliceId ?? [])).sort((a, b) => a - b);

const selectedCell = selectedCellKey ? cellMap.get(`${selectedCellKey.sliceId}:${selectedCellKey.segindex}`) : null;
const selectedMetrics = selectedCell?.runtimeMetrics ?? null;
const maxCPUBySlice = new Map<number, number>();
for (const cell of cells) {
Expand Down Expand Up @@ -151,7 +153,7 @@ function RuntimeMetricsMatrix({ ssid, ccnt }: { ssid: number; ccnt: number }) {
key={`${sliceId}-${segindex}`}
type="button"
disabled={!cell}
onClick={() => cell && setSelectedCell(cell)}
onClick={() => cell && setSelectedCell({ sliceId: cell.sliceId, segindex: cell.segindex })}
style={{
height: 56,
borderRadius: 6,
Expand Down Expand Up @@ -264,6 +266,12 @@ export default function QueryDetailPage() {

const query = data?.query;

useEffect(() => {
if (!query || query.completed || loading) return;
const timer = window.setTimeout(refresh, 5000);
return () => window.clearTimeout(timer);
}, [query, loading, refresh]);

const handleTerminate = () => {
Modal.confirm({
title: "Terminate Query",
Expand Down Expand Up @@ -316,7 +324,7 @@ export default function QueryDetailPage() {
<Spin spinning={loading}>
{query && (
<>
<RuntimeMetricsMatrix ssid={Number(ssid)} ccnt={Number(ccnt)} />
<RuntimeMetricsMatrix key={`${ssid}/${ccnt}`} ssid={Number(ssid)} ccnt={Number(ccnt)} completed={query.completed} />

<Card
title="Query Info"
Expand Down