diff --git a/docs/API.md b/docs/API.md index 99335b34..4a38b906 100644 --- a/docs/API.md +++ b/docs/API.md @@ -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 diff --git a/docs/performance-tuning.md b/docs/performance-tuning.md index 1cd71fcd..74fb9c9e 100644 --- a/docs/performance-tuning.md +++ b/docs/performance-tuning.md @@ -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. --- diff --git a/docs/proc-stats-flow.md b/docs/proc-stats-flow.md index e5f4c827..8e27951a 100644 --- a/docs/proc-stats-flow.md +++ b/docs/proc-stats-flow.md @@ -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)` | diff --git a/internal/app/app.go b/internal/app/app.go index cd3a7946..546ad98f 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -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) diff --git a/internal/coordinator/background.go b/internal/coordinator/background.go index 7a079735..0da71e13 100644 --- a/internal/coordinator/background.go +++ b/internal/coordinator/background.go @@ -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 { @@ -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 { diff --git a/internal/coordinator/procfs_query_identity.go b/internal/coordinator/procfs_query_identity.go new file mode 100644 index 00000000..6809ffd7 --- /dev/null +++ b/internal/coordinator/procfs_query_identity.go @@ -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() + } +} diff --git a/internal/coordinator/procfs_query_identity_test.go b/internal/coordinator/procfs_query_identity_test.go new file mode 100644 index 00000000..fc6cde3d --- /dev/null +++ b/internal/coordinator/procfs_query_identity_test.go @@ -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) + }) + } +} diff --git a/internal/utils/procfs.go b/internal/utils/procfs.go index d40e3919..1e4594bf 100644 --- a/internal/utils/procfs.go +++ b/internal/utils/procfs.go @@ -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 diff --git a/internal/utils/procfs_getprocinfo_test.go b/internal/utils/procfs_getprocinfo_test.go index 466343ff..40b19862 100644 --- a/internal/utils/procfs_getprocinfo_test.go +++ b/internal/utils/procfs_getprocinfo_test.go @@ -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) + } +} diff --git a/web/src/hooks/useApi.ts b/web/src/hooks/useApi.ts index f4ab462a..1b58e382 100644 --- a/web/src/hooks/useApi.ts +++ b/web/src/hooks/useApi.ts @@ -25,6 +25,7 @@ import { useState, useEffect, useCallback, useRef } from "react"; export function useApi( fetcher: () => Promise, deps: unknown[] = [], + pollIntervalMs = 0, ) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); @@ -58,5 +59,11 @@ export function useApi( 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 }; } diff --git a/web/src/pages/QueryDetailPage.tsx b/web/src/pages/QueryDetailPage.tsx index 95d62040..1a27ce75 100644 --- a/web/src/pages/QueryDetailPage.tsx +++ b/web/src/pages/QueryDetailPage.tsx @@ -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, @@ -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(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; @@ -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(); for (const cell of cells) { @@ -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, @@ -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", @@ -316,7 +324,7 @@ export default function QueryDetailPage() { {query && ( <> - +