diff --git a/README.md b/README.md index 21157432..2659feb8 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Full documentation lives at **[valkey-admin.valkey.io](https://valkey-admin.valk - **[Cluster Topology](https://valkey-admin.valkey.io/features/cluster-topology/)** — Visual map of shards, primaries, and replicas with per-node metrics. - **[Activity](https://valkey-admin.valkey.io/features/activity/)** — Hot Keys monitoring plus Command Logs (slow commands, large requests, large replies) aggregated across the cluster. - **[OpenTelemetry Export](https://valkey-admin.valkey.io/features/otel-export/)** — Push memory, keyspace and CPU metrics over OTLP to Prometheus and other backends. Turn it on with `METRICS_OTEL_ENABLED=true`. -- **[AI Assistants (MCP)](https://valkey-admin.valkey.io/features/mcp/)** — Read-only MCP server that lets assistants such as Claude Code and Cursor read server info, big keys, and hot keys. +- **[AI Assistants (MCP)](https://valkey-admin.valkey.io/features/mcp/)** — Read-only MCP server that lets assistants such as Claude Code and Cursor read server info, big keys, hot keys, and command logs. ## Compatibility diff --git a/apps/frontend/src/components/activity-view/command-log-table.tsx b/apps/frontend/src/components/activity-view/command-log-table.tsx index 7dfaa724..498a89f5 100644 --- a/apps/frontend/src/components/activity-view/command-log-table.tsx +++ b/apps/frontend/src/components/activity-view/command-log-table.tsx @@ -10,40 +10,14 @@ import { Typography } from "../ui/typography" import { CustomTooltip } from "../ui/tooltip" import { NodeErrorsBanner } from "./hotkeys/hot-keys-banners" import { NodeFilterDropdown } from "./hotkeys/node-filter-dropdown" +import type { CommandLogRow, CommandLogType } from "@common/src/commandlogs" type SortOrder = typeof SORT_ORDER.ASC | typeof SORT_ORDER.DESC type SortField = typeof SORT_FIELD.TIMESTAMP | typeof SORT_FIELD.METRIC -interface SlowLogEntry { - id: string - ts: number - duration_us: number - argv: string[] - addr: string - client: string -} - -interface LargeLogEntry { - id: string - ts: number - size: number - argv: string[] - addr: string - client: string -} - -interface LogGroup { - ts: number - metric: string - values: (SlowLogEntry | LargeLogEntry)[] - nodeId: string, -} - -type LogType = "slow" | "large-request" | "large-reply" - interface CommandLogTableProps { - data: LogGroup[] | null - logType: LogType + data: CommandLogRow[] | null + logType: CommandLogType nodeErrors?: { nodeId: string; error: string }[] isCluster?: boolean } @@ -99,7 +73,6 @@ export function CommandLogTable({ data, logType, nodeErrors, isCluster }: Comman logGroup.values.map((entry) => ({ ...entry, groupTs: logGroup.ts, - nodeId: entry.nodeId ?? (logGroup).nodeId, })), ) diff --git a/apps/frontend/src/state/valkey-features/commandlogs/commandLogsSlice.test.ts b/apps/frontend/src/state/valkey-features/commandlogs/commandLogsSlice.test.ts index e318e594..50cbf890 100644 --- a/apps/frontend/src/state/valkey-features/commandlogs/commandLogsSlice.test.ts +++ b/apps/frontend/src/state/valkey-features/commandlogs/commandLogsSlice.test.ts @@ -13,7 +13,7 @@ describe("commandLogsSlice", () => { it("keys the standalone pending entry by the db-less nodeId", () => { const state = commandLogsReducer( initialState, - commandLogsRequested({ connectionId: "host-6379-db0" }), + commandLogsRequested({ connectionId: "host-6379-db0", commandLogType: COMMANDLOG_TYPE.SLOW }), ) expect(state["host-6379"]).toBeDefined() @@ -24,11 +24,11 @@ describe("commandLogsSlice", () => { it("collapses two connections to the same node on different dbs into one entry", () => { const afterDb0 = commandLogsReducer( initialState, - commandLogsRequested({ connectionId: "host-6379-db0" }), + commandLogsRequested({ connectionId: "host-6379-db0", commandLogType: COMMANDLOG_TYPE.SLOW }), ) const afterDb1 = commandLogsReducer( afterDb0, - commandLogsRequested({ connectionId: "host-6379-db1" }), + commandLogsRequested({ connectionId: "host-6379-db1", commandLogType: COMMANDLOG_TYPE.SLOW }), ) expect(Object.keys(afterDb1)).toEqual(["host-6379"]) @@ -37,7 +37,7 @@ describe("commandLogsSlice", () => { it("keys the cluster pending entry by clusterId", () => { const state = commandLogsReducer( initialState, - commandLogsRequested({ connectionId: "node-1-db0", clusterId: "cluster-1" }), + commandLogsRequested({ connectionId: "node-1-db0", clusterId: "cluster-1", commandLogType: COMMANDLOG_TYPE.SLOW }), ) expect(state["cluster-1"]).toBeDefined() @@ -83,28 +83,28 @@ describe("commandLogsSlice", () => { it("keys a standalone error by nodeId", () => { const seeded = commandLogsReducer( initialState, - commandLogsRequested({ connectionId: "host-6379-db0" }), + commandLogsRequested({ connectionId: "host-6379-db0", commandLogType: COMMANDLOG_TYPE.SLOW }), ) const state = commandLogsReducer( seeded, - commandLogsError({ nodeId: "host-6379", error: { message: "boom" } }), + commandLogsError({ nodeId: "host-6379", error: "boom" }), ) - expect(state["host-6379"].error).toEqual({ message: "boom" }) + expect(state["host-6379"].error).toBe("boom") expect(state["host-6379"].loading).toBe(false) }) it("keys a cluster error by clusterId", () => { const seeded = commandLogsReducer( initialState, - commandLogsRequested({ connectionId: "node-1-db0", clusterId: "cluster-1" }), + commandLogsRequested({ connectionId: "node-1-db0", clusterId: "cluster-1", commandLogType: COMMANDLOG_TYPE.SLOW }), ) const state = commandLogsReducer( seeded, - commandLogsError({ clusterId: "cluster-1", error: { message: "boom" } }), + commandLogsError({ nodeId: "node-1", clusterId: "cluster-1", error: "boom" }), ) - expect(state["cluster-1"].error).toEqual({ message: "boom" }) + expect(state["cluster-1"].error).toBe("boom") }) }) }) diff --git a/apps/frontend/src/state/valkey-features/commandlogs/commandLogsSlice.ts b/apps/frontend/src/state/valkey-features/commandlogs/commandLogsSlice.ts index 26602fea..09a9af4f 100644 --- a/apps/frontend/src/state/valkey-features/commandlogs/commandLogsSlice.ts +++ b/apps/frontend/src/state/valkey-features/commandlogs/commandLogsSlice.ts @@ -1,14 +1,18 @@ -import { createSlice } from "@reduxjs/toolkit" -import { type JSONObject } from "@common/src/json-utils" +import { createSlice, type PayloadAction } from "@reduxjs/toolkit" import { VALKEY } from "@common/src/constants.ts" import { toNodeId } from "@common/src/connection-id.ts" import * as R from "ramda" import { COMMANDLOG_TYPE } from "@common/src/constants.ts" +import type { + CommandLogRow, + CommandLogsErrorPayload, + CommandLogsFulfilledPayload, + CommandLogsRequestPayload, + CommandLogType +} from "@common/src/commandlogs.ts" import type { NodeError } from "@common/src/node-results.ts" import type { RootState } from "@/store.ts" -type CommandLogType = typeof COMMANDLOG_TYPE.SLOW | typeof COMMANDLOG_TYPE.LARGE_REQUEST | typeof COMMANDLOG_TYPE.LARGE_REPLY - // `targetId` is the state key: `clusterId` for a cluster aggregate or the // db-less `nodeId` for a standalone node. export const selectCommandLogs = @@ -21,44 +25,12 @@ export const selectCommandLogsNodeErrors = (state: RootState) => R.path([VALKEY.COMMANDLOGS.name, targetId, "nodeErrors"], state) ?? [] -interface CommandLogSlowEntry { - id: string - ts: number - duration_us: number - argv: string[] - addr: string - client: string -} - -interface CommandLogLargeEntry { - id: string - ts: number - size: number - argv: string[] - addr: string - client: string -} - -interface CommandLogEntry { - ts: number, - metric: string, - values: CommandLogLargeEntry[] -} - interface CommandLogState { // Keyed by `targetId`: `clusterId` (cluster) or `nodeId` (standalone). [targetId: string]: { - logs: { - slow: Array<{ - ts: number - metric: string - values: CommandLogSlowEntry[] - }> - [COMMANDLOG_TYPE.LARGE_REPLY]: CommandLogEntry[], - [COMMANDLOG_TYPE.LARGE_REQUEST]: CommandLogEntry[], - } + logs: Record count: number - error?: JSONObject | null + error?: string | null loading?: boolean nodeErrors?: NodeError[] } @@ -70,7 +42,7 @@ const commandLogsSlice = createSlice({ name: "commandLogs", initialState: initialCommandLogsState, reducers: { - commandLogsRequested: (state, action) => { + commandLogsRequested: (state, action: PayloadAction) => { const { connectionId, clusterId } = action.payload // Standalone command logs state is node-level. const targetId = clusterId ?? toNodeId(connectionId) @@ -87,10 +59,9 @@ const commandLogsSlice = createSlice({ } state[targetId].loading = true }, - commandLogsFulfilled: (state, action) => { - const { parsedResponse, nodeErrors } = action.payload - const targetId = action.payload.clusterId ?? action.payload.nodeId - const commandLogType: CommandLogType = action.payload.commandLogType + commandLogsFulfilled: (state, action: PayloadAction) => { + const { parsedResponse, nodeErrors, commandLogType } = action.payload + const targetId = "clusterId" in action.payload ? action.payload.clusterId : action.payload.nodeId const { rows, count } = parsedResponse if (!state[targetId]) { state[targetId] = { @@ -108,7 +79,7 @@ const commandLogsSlice = createSlice({ state[targetId].loading = false state[targetId].nodeErrors = nodeErrors ?? [] }, - commandLogsError: (state, action) => { + commandLogsError: (state, action: PayloadAction) => { const { error } = action.payload const targetId = action.payload.clusterId ?? action.payload.nodeId if (state[targetId]) { diff --git a/apps/mcp/README.md b/apps/mcp/README.md index 26058ad2..98ef6cb8 100644 --- a/apps/mcp/README.md +++ b/apps/mcp/README.md @@ -96,9 +96,12 @@ The `VALKEY_*` connection variables apply only in header mode, to requests that | `get_server_info` | INFO and memory data | None | Yes | Connected node only | | `get_big_keys` | Largest keys by memory | `topN` (default 20), `scanLimit` per node (default 10000) | Yes | All nodes | | `get_hot_keys` | Most frequently accessed keys | `count` (default 20) | No | All nodes | +| `get_command_logs` | Recent slow commands, large requests or large replies, largest first | `type` (`slow`, `large-request` or `large-reply`, default `slow`), `count` (default 20, max 100) | Yes | All nodes | `get_hot_keys` requires cluster mode, `cluster-slot-stats-enabled yes` and an LFU `maxmemory-policy` such as `allkeys-lfu`. +`get_command_logs` reads `COMMANDLOG`, which needs Valkey 8.1 or later. Each node keeps its latest entries per log, so results show recent activity, not a time range. Results include the command name and argument count only, never the arguments, so key names and values stay out. + `get_big_keys` adds load to each node it scans. `scanLimit` applies per node, so a three-node cluster with the default limit can scan up to about 30,000 keys. ## Add it to your AI assistant @@ -178,7 +181,7 @@ The rule starts with `reset`, so it always produces the same read-only user, eve | `@read`, `@connection` | Big keys (`SCAN`, `TYPE`, `TTL`, `MEMORY USAGE`, `OBJECT FREQ`), connecting | | `INFO`, `MEMORY STATS` | Server info and the dashboard data | | `CLUSTER SLOTS`, `CLUSTER SLOT-STATS` | Finding cluster nodes, hot keys | -| `COMMANDLOG GET`, `COMMAND INFO` | The metrics collector | +| `COMMANDLOG GET`, `COMMAND INFO` | The metrics collector, command logs | Writes, `FLUSHALL`, `CONFIG GET`, `CONFIG SET`, `KEYS`, `MONITOR`, `CLIENT KILL` and the other admin commands stay blocked. @@ -209,6 +212,7 @@ If a cluster result is correct, `nodeId` shows keys from more than one node and | `Cannot reach Valkey Admin at ...` | Start the Valkey Admin server and check `VALKEY_ADMIN_URL`. If it is running, add the MCP origin to its `VALKEY_ADMIN_ALLOWED_WS_ORIGINS`, because a rejected origin shows this same error | | `No reply from Valkey Admin for ...` | The request passed the 10-second limit. Lower `scanLimit` and try again | | `Hot keys use cluster slot stats, which need ...` | Apply the settings listed in the error | +| `Command logs need Valkey 8.1 or later ...` | `get_command_logs` needs Valkey 8.1 or later. Upgrade the nodes, or use the other tools | | `Metrics server not started` | Metrics are still starting. Tools retry for a few seconds, so try again shortly | | `NOPERM ...` | The Valkey user lacks a command the tools use. See [Read-only Valkey user](#read-only-valkey-user) | diff --git a/apps/mcp/src/admin-client.ts b/apps/mcp/src/admin-client.ts index 8c0eb7b8..c9ce706b 100644 --- a/apps/mcp/src/admin-client.ts +++ b/apps/mcp/src/admin-client.ts @@ -31,6 +31,7 @@ const READ_ONLY_ACTIONS = new Set([ VALKEY.STATS.setData, VALKEY.BIGKEYS.bigKeysRequested, VALKEY.HOTKEYS.hotKeysRequested, + VALKEY.COMMANDLOGS.commandLogsRequested, ]) const CONNECT_REPLIES = [ diff --git a/apps/mcp/src/index.ts b/apps/mcp/src/index.ts index b8a2cd16..e14af45c 100644 --- a/apps/mcp/src/index.ts +++ b/apps/mcp/src/index.ts @@ -15,6 +15,7 @@ import { loadConfig } from "./config" import { registerBigKeys } from "./tools/big-keys" +import { registerCommandLogs } from "./tools/command-logs" import { registerHotKeys } from "./tools/hot-keys" import { registerServerInfo } from "./tools/server-info" @@ -33,6 +34,7 @@ const main = () => { registerServerInfo(server, admin) registerBigKeys(server, admin) registerHotKeys(server, admin) + registerCommandLogs(server, admin) return server }, { onerror }) const handle = toNodeHandler(mcp, { onerror }) diff --git a/apps/mcp/src/tools/command-logs.ts b/apps/mcp/src/tools/command-logs.ts new file mode 100644 index 00000000..cae682aa --- /dev/null +++ b/apps/mcp/src/tools/command-logs.ts @@ -0,0 +1,177 @@ +// The get_command_logs tool: recent slow commands, large requests or large replies, +// as on the Valkey Admin command logs page. On a cluster it merges every node. +import { + COMMANDLOG_TYPE, + VALKEY, + type CommandLogRow, + type CommandLogType, + type CommandLogsErrorPayload, + type CommandLogsFulfilledPayload, + type CommandLogsRequestPayload, + type CommandLogsResponse, + type LargeCommandLogEntry, + type NodeError, + type SlowCommandLogEntry +} from "valkey-common" +import { z } from "zod" +import { METRICS_NOT_STARTED, NotReadyError, retryWhileNotReady } from "./not-ready" +import { toolResult } from "./tool-result" +import type { AdminClient } from "../admin-client" +import type { McpServer } from "@modelcontextprotocol/server" + +type ParsedCommandLogs = Pick & { rows: Pick[] } + +const METRICS_URI_NOT_FOUND = "Metrics server URI not found" +const NEEDS_COMMANDLOG = "Command logs need Valkey 8.1 or later, which adds the COMMANDLOG command" +const TRUNCATED_ARGS = /^\.\.\. \((\d+) more arguments\)$/ +// Fetch every retained entry, since the collector keeps them newest first and +// cuts to the requested count before this tool can sort by duration or size. +const FETCH_COUNT = 100 + +const inputSchema = z.object({ + type: z.enum([COMMANDLOG_TYPE.SLOW, COMMANDLOG_TYPE.LARGE_REQUEST, COMMANDLOG_TYPE.LARGE_REPLY] satisfies CommandLogType[]) + .default(COMMANDLOG_TYPE.SLOW) + .describe("Which log to read: slow commands, large requests or large replies"), + count: z.number().int().min(1).max(100).default(20) + .describe("How many entries to return, largest duration or size first"), +}) + +const nodeErrorSchema = z.object({ + nodeId: z.string(), + error: z.string(), +}) satisfies z.ZodType + +const logEntryBaseSchema = z.object({ + id: z.string(), + ts: z.number(), + argv: z.array(z.string()).default([]), + addr: z.string(), + client: z.string(), + nodeId: z.string().optional(), +}) + +const slowEntrySchema = logEntryBaseSchema.extend({ + duration_us: z.number(), +}) satisfies z.ZodType + +const largeEntrySchema = logEntryBaseSchema.extend({ + size: z.number(), +}) satisfies z.ZodType + +const logEntrySchema = z.union([slowEntrySchema, largeEntrySchema]) + +const responseSchema = z.object({ + rows: z.array(z.object({ values: z.array(logEntrySchema).default([]) })).default([]), + nodeId: z.string().optional(), +}) satisfies z.ZodType + +const fulfilledPayloadSchema = z.object({ + parsedResponse: responseSchema, + nodeErrors: z.array(nodeErrorSchema).optional(), +}) satisfies z.ZodType< + Pick & { + parsedResponse: ParsedCommandLogs + } +> + +const errorPayloadSchema = z.object({ + error: z.string(), +}) satisfies z.ZodType> + +const entrySchema = z.object({ + id: z.string(), + timestamp: z.number().describe("When the command ran, in milliseconds since the epoch"), + durationMicroseconds: z.number().optional().describe("Execution time, for slow commands"), + sizeBytes: z.number().optional().describe("Request or reply size, for large requests and large replies"), + command: z.string().describe("Command name only. Arguments are never returned, so key names and values stay out"), + argumentCount: z.number(), + clientAddress: z.string(), + clientName: z.string(), + nodeId: z.string().optional(), +}) + +const outputSchema = z.object({ + type: inputSchema.shape.type.unwrap(), + entries: z.array(entrySchema), + nodeErrors: z.array(nodeErrorSchema), +}) + +const isMissingCommandLog = (error: string) => /unknown command/i.test(error) + +// Counts arguments without returning them. Valkey truncates long argv to +// "... (N more arguments)", so that marker adds N instead of counting as one. +const countArguments = (argv: string[]) => { + const truncated = TRUNCATED_ARGS.exec(argv.at(-1) ?? "") + return truncated ? argv.length - 2 + Number(truncated[1]) : Math.max(argv.length - 1, 0) +} + +const toEntry = (entry: z.infer, fallbackNodeId?: string) => { + const nodeId = entry.nodeId ?? fallbackNodeId + return { + id: entry.id, + timestamp: entry.ts, + ...("duration_us" in entry ? { durationMicroseconds: entry.duration_us } : { sizeBytes: entry.size }), + command: (entry.argv[0] ?? "").toUpperCase(), + argumentCount: countArguments(entry.argv), + clientAddress: entry.addr, + clientName: entry.client, + ...(nodeId !== undefined && { nodeId }), + } +} + +const rank = (entry: z.infer) => entry.durationMicroseconds ?? entry.sizeBytes ?? entry.timestamp + +// Requests one command log type, passing the cluster ID so the server queries +// every node, and returns the largest entries first. Throws NotReadyError while +// collectors are starting, either as the whole reply's error or when every node +// fails with that error. +const fetchCommandLogs = async (admin: AdminClient, { type, count }: z.infer) => { + const reply = await admin.request( + VALKEY.COMMANDLOGS.commandLogsRequested, + ({ clusterId }) => { + const payload: CommandLogsRequestPayload = { connectionId: admin.connectionId, clusterId, commandLogType: type, count: FETCH_COUNT } + return { ...payload } + }, + [VALKEY.COMMANDLOGS.commandLogsFulfilled, VALKEY.COMMANDLOGS.commandLogsError], + ) + if (reply.type === VALKEY.COMMANDLOGS.commandLogsError) { + const message = errorPayloadSchema.safeParse(reply.payload).data?.error ?? "Valkey Admin could not load command logs" + if (message === METRICS_NOT_STARTED || message === METRICS_URI_NOT_FOUND) throw new NotReadyError(METRICS_NOT_STARTED) + throw new Error(isMissingCommandLog(message) ? NEEDS_COMMANDLOG : message) + } + const { parsedResponse, nodeErrors = [] } = fulfilledPayloadSchema.parse(reply.payload) + const entries = parsedResponse.rows + .flatMap((row) => row.values) + .map((value) => toEntry(value, parsedResponse.nodeId)) + .sort((a, b) => rank(b) - rank(a)) + .slice(0, count) + if (entries.length === 0 && nodeErrors.length > 0) { + if (nodeErrors.every(({ error }) => error === METRICS_NOT_STARTED)) throw new NotReadyError(METRICS_NOT_STARTED) + if (nodeErrors.every(({ error }) => isMissingCommandLog(error))) throw new Error(NEEDS_COMMANDLOG) + } + const result: z.infer = { type, entries, nodeErrors } + return result +} + +// Registers get_command_logs on the MCP server. +export const registerCommandLogs = (server: McpServer, admin: AdminClient) => + server.registerTool( + "get_command_logs", + { + title: "Command logs (via Valkey Admin)", + description: + "Returns recent slow commands, large requests or large replies from COMMANDLOG, as shown on the Valkey Admin command logs page, " + + "largest duration or size first. In cluster mode it covers every node. Each node keeps its latest 50 entries per log, " + + "so this shows recent activity, not a time range. Returns the command name and argument count only, never the arguments. " + + "Requires Valkey 8.1 or later.", + inputSchema, + outputSchema, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + }, + async (input) => toolResult(await retryWhileNotReady(() => fetchCommandLogs(admin, input))), + ) diff --git a/apps/metrics/config.yml b/apps/metrics/config.yml index b31ccabd..81afd28d 100644 --- a/apps/metrics/config.yml +++ b/apps/metrics/config.yml @@ -17,7 +17,8 @@ collector: # Each epic controls its own storage retention: # data_retention_mb – max disk space (MB) for this epic's .ndjson files. # Oldest files are evicted when the budget is exceeded. -# data_retention_days – files older than this (by birthtime) are deleted +# data_retention_days – files older than this (by creation time, or last +# write time where the filesystem has none) are deleted # during the daily cleanup sweep. epics: - name: "memory" diff --git a/apps/metrics/src/effects/ndjson-cleaner.js b/apps/metrics/src/effects/ndjson-cleaner.js index fef9a0b1..dfdaf00a 100644 --- a/apps/metrics/src/effects/ndjson-cleaner.js +++ b/apps/metrics/src/effects/ndjson-cleaner.js @@ -3,6 +3,7 @@ import path from "node:path" import { timer } from "rxjs" import { exhaustMap } from "rxjs/operators" import { METRICS_EVICTION_POLICY, MILLISECONDS_IN_A_DAY } from "../../../../common/src/constants.js" +import { fileCreatedAt } from "../utils/helpers.js" import { createLogger } from "../utils/logger.js" const log = createLogger("ndjson-cleaner") @@ -30,7 +31,7 @@ export const setupNdjsonCleaner = ( cfg ) => { // filter out files that are expired based on their epic's retention .then((filesWithStats) => filesWithStats.reduce((acc, { stats, fileName }) => { const days = retentionForFile(fileName, retentionByPrefix) - if (days >= 0 && stats.birthtime < Date.now() - days * MILLISECONDS_IN_A_DAY) acc.push(fileName) + if (days >= 0 && fileCreatedAt(stats) < Date.now() - days * MILLISECONDS_IN_A_DAY) acc.push(fileName) return acc }, [])) // delete expired files diff --git a/apps/metrics/src/effects/ndjson-cleaner.test.js b/apps/metrics/src/effects/ndjson-cleaner.test.js index 3357233a..e9ff89b3 100644 --- a/apps/metrics/src/effects/ndjson-cleaner.test.js +++ b/apps/metrics/src/effects/ndjson-cleaner.test.js @@ -47,6 +47,20 @@ describe("ndjson-cleaner", () => { }) describe("retention policy", () => { + it("keeps a fresh file whose filesystem records no creation time, as in Docker", async () => { + fs.promises.readdir.mockResolvedValue(["memory_20250615_0.ndjson"]) + fs.promises.stat.mockResolvedValue({ birthtime: new Date(0), mtime: new Date("2025-06-15T11:00:00.000Z") }) + + const { setupNdjsonCleaner, stopNdjsonCleaner } = await import("./ndjson-cleaner.js") + setupNdjsonCleaner(cfg) + + await vi.advanceTimersByTimeAsync(0) + + expect(fs.promises.unlink).not.toHaveBeenCalled() + + stopNdjsonCleaner() + }) + it("deletes only expired .ndjson files", async () => { // 2025-06-15 now, 30-day retention → cutoff = 2025-05-16 // memory has old birthtime (expired), cpu has recent birthtime (kept) diff --git a/apps/metrics/src/effects/ndjson-streamer.js b/apps/metrics/src/effects/ndjson-streamer.js index 1c587109..9d7e031c 100644 --- a/apps/metrics/src/effects/ndjson-streamer.js +++ b/apps/metrics/src/effects/ndjson-streamer.js @@ -4,7 +4,7 @@ import path from "node:path" import { MILLISECONDS_IN_A_DAY } from "valkey-common" import { getConfig } from "../config.js" import { EPIC_KINDS } from "../utils/constants.js" -import { dayStr, parseSeq } from "../utils/helpers.js" +import { dayStr, fileCreatedAt, parseSeq } from "../utils/helpers.js" // Read per call rather than at import time so a config reload is picked up. const dataDir = () => getConfig().server.data_dir @@ -19,7 +19,7 @@ const filePathsFor = async (prefix, dates) => { allFiles.map(async (file) => { const filePath = path.join(dir, file) const stat = await fs.promises.stat(filePath) - return { file, filePath, birthtime: stat.birthtime, seq: parseSeq(file) } + return { file, filePath, birthtime: fileCreatedAt(stat), seq: parseSeq(file) } }), ) diff --git a/apps/metrics/src/effects/ndjson-streamer.test.js b/apps/metrics/src/effects/ndjson-streamer.test.js index 255389ec..d07c3e19 100644 --- a/apps/metrics/src/effects/ndjson-streamer.test.js +++ b/apps/metrics/src/effects/ndjson-streamer.test.js @@ -77,6 +77,17 @@ describe("ndjson-streamer", () => { }) describe("streamNdjson", () => { + it("reads today's file when the filesystem records no creation time, as in Docker", async () => { + fs.promises.stat.mockResolvedValue({ birthtime: new Date(0), mtime: new Date() }) + readline.createInterface.mockReturnValue(createAsyncIterator(createNdjsonLines(3))) + + const { streamNdjson } = await import("./ndjson-streamer.js") + const result = await streamNdjson("test_prefix") + + expect(fs.createReadStream).toHaveBeenCalledTimes(1) + expect(result).toHaveLength(3) + }) + it("should read from yesterday and today files", async () => { const lines = createNdjsonLines(5) readline.createInterface.mockReturnValue(createAsyncIterator(lines)) diff --git a/apps/metrics/src/effects/ndjson-writer.js b/apps/metrics/src/effects/ndjson-writer.js index e6cd0a5b..aa770a90 100644 --- a/apps/metrics/src/effects/ndjson-writer.js +++ b/apps/metrics/src/effects/ndjson-writer.js @@ -1,7 +1,7 @@ import fs from "node:fs" import path from "node:path" import * as R from "ramda" -import { dayStr, parseSeq } from "../utils/helpers.js" +import { dayStr, fileCreatedAt, parseSeq } from "../utils/helpers.js" const discoverMaxSeq = async (dataDir, filePrefix, day) => { const fileNames = await fs.promises.readdir(dataDir).catch(() => []) @@ -22,7 +22,7 @@ const listPrefixFiles = async (dataDir, filePrefix) => { const withStats = await Promise.all( matched.map(async (fileName) => { const stat = await fs.promises.stat(path.join(dataDir, fileName)) - return { fileName, birthtime: stat.birthtime, seq: parseSeq(fileName) } + return { fileName, birthtime: fileCreatedAt(stat), seq: parseSeq(fileName) } }), ) diff --git a/apps/metrics/src/handlers/commandlog-handler.js b/apps/metrics/src/handlers/commandlog-handler.js index f5a00ade..e5543363 100644 --- a/apps/metrics/src/handlers/commandlog-handler.js +++ b/apps/metrics/src/handlers/commandlog-handler.js @@ -45,7 +45,7 @@ export const getCommandLogs = async (req, res, nodeId) => { const count = Number(req.query.count) || 100 const rows = await getCommandLogRows(commandlogType) const limitedRows = Array.isArray(rows) - ? rows.map((row) => ({ ...row, values: row.values?.slice(0, count) ?? [] })).filter((row) => row.values.length > 0) + ? rows.filter(Boolean).map((row) => ({ ...row, values: row.values?.slice(0, count) ?? [] })).filter((row) => row.values.length > 0) : rows // Add minimum (1) and maximum (500) boundaries for rows requested return res.json({ count: Math.max(1, Math.min(500, count)), rows: limitedRows, lastUpdatedAt, nodeId }) diff --git a/apps/metrics/src/handlers/commandlog-handler.test.js b/apps/metrics/src/handlers/commandlog-handler.test.js new file mode 100644 index 00000000..0f136219 --- /dev/null +++ b/apps/metrics/src/handlers/commandlog-handler.test.js @@ -0,0 +1,36 @@ +import { describe, it, expect, vi, afterEach } from "vitest" +import { COMMANDLOG_TYPE } from "../utils/constants.js" + +vi.mock("../init-collectors.js", () => ({ + getCollectorMeta: vi.fn(() => ({ lastUpdatedAt: 1000, nextCycleAt: 2000 })), +})) + +vi.mock("../effects/ndjson-streamer.js", () => ({ + commandlog_slow: vi.fn(), + commandlog_large_request: vi.fn(), + commandlog_large_reply: vi.fn(), +})) + +const makeRes = () => { + const res = { status: vi.fn(), json: vi.fn() } + res.status.mockReturnValue(res) + return res +} + +describe("getCommandLogs", () => { + afterEach(() => { + vi.clearAllMocks() + }) + + it("returns no rows instead of failing when no entries have been saved yet", async () => { + const Streamer = await import("../effects/ndjson-streamer.js") + Streamer.commandlog_slow.mockResolvedValue([null]) + const { getCommandLogs } = await import("./commandlog-handler.js") + const res = makeRes() + + await getCommandLogs({ query: { type: COMMANDLOG_TYPE.SLOW, count: "10" } }, res, "node-1") + + expect(res.status).not.toHaveBeenCalled() + expect(res.json).toHaveBeenCalledWith({ count: 10, rows: [], lastUpdatedAt: 1000, nodeId: "node-1" }) + }) +}) diff --git a/apps/metrics/src/utils/helpers.js b/apps/metrics/src/utils/helpers.js index 6db32bc6..1c364777 100644 --- a/apps/metrics/src/utils/helpers.js +++ b/apps/metrics/src/utils/helpers.js @@ -3,6 +3,10 @@ import { COMMANDLOG_TYPE } from "../utils/constants.js" export const dayStr = (d) => new Date(d).toISOString().slice(0, 10).replace(/-/g, "") +// Some filesystems, such as Docker's, record no creation time, so Node reports 0 (1970). +// Fall back to the last write time there, or every data file looks expired. +export const fileCreatedAt = (stat) => (stat.birthtime?.getTime() > 0 ? stat.birthtime : stat.mtime) + export const parseSeq = (fileName) => { const match = fileName.match(/_(\d+)\.ndjson$/) return match ? Number(match[1]) : 0 diff --git a/apps/server/src/actions/commandLogs.ts b/apps/server/src/actions/commandLogs.ts index 307cb6d7..9b9f042d 100644 --- a/apps/server/src/actions/commandLogs.ts +++ b/apps/server/src/actions/commandLogs.ts @@ -1,50 +1,21 @@ import { type WebSocket } from "ws" -import { VALKEY, COMMANDLOG_TYPE, type AggregateReplyId, type NodeError, toNodeId, buildUrl } from "valkey-common" +import { + VALKEY, + type AggregateReplyId, + type CommandLogEntry, + type CommandLogType, + type CommandLogsResponse, + type NodeError, + toNodeId, + buildUrl +} from "valkey-common" import * as R from "ramda" import { withDeps, Deps, collectorFeaturesDisabled, KUBERNETES_METRICS_UNAVAILABLE } from "./utils" -type CommandLogType = typeof COMMANDLOG_TYPE.SLOW | typeof COMMANDLOG_TYPE.LARGE_REQUEST | typeof COMMANDLOG_TYPE.LARGE_REPLY - -type CommandLogsSlowResponse = { - count: number - rows: Array<{ - ts: number - metric: string - values: Array<{ - id: string - ts: number - duration_us: number - argv: string[] - addr: string - client: string - }> - }>, - checkAt: number -} - -type CommandLogsLargeResponse = { - count: number - rows: Array<{ - ts: number - metric: string - values: Array<{ - id: string - ts: number - size: number - argv: string[] - addr: string - client: string - }> - }>, - checkAt: number -} - -type CommandLogResponse = (CommandLogsLargeResponse | CommandLogsSlowResponse) & { nodeId?: string } - const sendCommandLogsFulfilled = ( ws: WebSocket, replyId: AggregateReplyId, // Commandlogs aggregates all cluster nodes into one result - parsedResponse: CommandLogsSlowResponse | CommandLogsLargeResponse, + parsedResponse: CommandLogsResponse, commandLogType: CommandLogType, nodeErrors?: NodeError[], ) => { @@ -80,19 +51,19 @@ const sendCommandLogsError = ( ) } -const fetchCommandLogs = async (metricsServerURI: string, commandLogType: CommandLogType, count: number): Promise => { +const fetchCommandLogs = async (metricsServerURI: string, commandLogType: CommandLogType, count: number): Promise => { const url = buildUrl(metricsServerURI, "/commandlog", { type: commandLogType, count }) const initialResponse = await fetch(url) if (!initialResponse.ok) { const body = await initialResponse.json().catch(() => ({})) as { error?: string } throw new Error(body.error ?? `HTTP ${initialResponse.status}`) } - const parsed: CommandLogResponse = await initialResponse.json() as CommandLogResponse + const parsed = await initialResponse.json() as CommandLogsResponse if (parsed.checkAt) { const delay = parsed.checkAt - Date.now() await new Promise((resolve) => setTimeout(resolve, delay)) const dataResponse = await fetch(url) - return await dataResponse.json() as CommandLogResponse + return await dataResponse.json() as CommandLogsResponse } return parsed } @@ -126,7 +97,7 @@ export const commandLogsRequested = withDeps( }) const settled = await Promise.all(promises) - const results = settled.filter((r): r is CommandLogResponse => !!r && "rows" in r) + const results = settled.filter((r): r is CommandLogsResponse => !!r && "rows" in r) const nodeErrors = nodes ? settled.filter((r): r is NodeError => !!r && "error" in r) : [] if (!nodes) { @@ -135,12 +106,12 @@ export const commandLogsRequested = withDeps( } const sortedValues = R.pipe( - R.chain((r: CommandLogResponse) => (r.rows ?? []).map((row) => ({ row, nodeId: r.nodeId }))), - R.chain(({ row, nodeId }) => (row.values ?? []).map((v) => ({ ...v, nodeId }))), + R.chain((r: CommandLogsResponse) => (r.rows ?? []).map((row) => ({ row, nodeId: r.nodeId }))), + R.chain(({ row, nodeId }): CommandLogEntry[] => (row.values ?? []).map((v) => ({ ...v, nodeId }))), R.sort( R.descend( - (v: { duration_us?: number; size?: number; ts: number }) => - v.duration_us ?? v.size ?? v.ts, + (v: CommandLogEntry) => + "duration_us" in v ? v.duration_us : v.size ?? v.ts, ), ), )(results) @@ -150,7 +121,7 @@ export const commandLogsRequested = withDeps( sendCommandLogsFulfilled( ws, { clusterId: clusterId as string }, - { rows: [{ ts: Date.now(), metric: commandLogType, values: limitedValues }], count: totalCount, checkAt: 0 } as CommandLogResponse, + { rows: [{ ts: Date.now(), metric: commandLogType, values: limitedValues }], count: totalCount, checkAt: 0 }, commandLogType, nodeErrors, ) diff --git a/common/src/commandlogs.ts b/common/src/commandlogs.ts new file mode 100644 index 00000000..0daa2aa8 --- /dev/null +++ b/common/src/commandlogs.ts @@ -0,0 +1,57 @@ +import type { COMMANDLOG_TYPE } from "./constants" +import type { NodeError } from "./node-results" +import type { AggregateReplyId } from "./reply-id" + +export type CommandLogType = typeof COMMANDLOG_TYPE[keyof typeof COMMANDLOG_TYPE] + +export interface CommandLogsRequestPayload { + connectionId: string + clusterId?: string + commandLogType: CommandLogType + count?: number +} + +interface CommandLogEntryBase { + id: string + ts: number + argv: string[] + addr: string + client: string + nodeId?: string +} + +export interface SlowCommandLogEntry extends CommandLogEntryBase { + duration_us: number +} + +export interface LargeCommandLogEntry extends CommandLogEntryBase { + size: number +} + +export type CommandLogEntry = SlowCommandLogEntry | LargeCommandLogEntry + +export interface CommandLogRow { + ts: number + metric: string + values: CommandLogEntry[] +} + +export interface CommandLogsResponse { + count: number + rows: CommandLogRow[] + checkAt?: number | null + lastUpdatedAt?: number | null + nodeId?: string +} + +export type CommandLogsFulfilledPayload = AggregateReplyId & { + parsedResponse: CommandLogsResponse + commandLogType: CommandLogType + nodeErrors?: NodeError[] +} + +export interface CommandLogsErrorPayload { + nodeId: string + clusterId?: string + error: string +} diff --git a/common/src/index.ts b/common/src/index.ts index d53680eb..12bbda7d 100644 --- a/common/src/index.ts +++ b/common/src/index.ts @@ -1,5 +1,6 @@ export * from "./bigkeys" export * from "./bytes-conversion" +export * from "./commandlogs" export * from "./command-restrictions" export * from "./cache-hit-ratio" export * from "./node-results" diff --git a/docs-site/src/content/docs/configuration/metrics.md b/docs-site/src/content/docs/configuration/metrics.md index 9c7fd5c4..c483eb86 100644 --- a/docs-site/src/content/docs/configuration/metrics.md +++ b/docs-site/src/content/docs/configuration/metrics.md @@ -43,7 +43,7 @@ Each entry in the `epics` array describes one collection stream. The fields belo | `name` | The epic's only identifier. It selects the collector implementation, prefixes the NDJSON files written under `DATA_DIR`, and labels the epic in logs and the orchestrator registry. One of `memory`, `cpu`, `slowlog_len`, `commandlog_slow`, `commandlog_large_request`, `commandlog_large_reply`, `monitor`. | required | | `poll_ms` | How often (ms) the collector runs. An integer from `1000` to `3600000`. | varies per epic | | `data_retention_mb` | Max disk space (MB) this epic's NDJSON files may use. Oldest files are evicted when the budget is exceeded. | `10` | -| `data_retention_days` | Files older than this (by birthtime) are deleted during the daily cleanup sweep. | `30` | +| `data_retention_days` | Files older than this are deleted during the daily cleanup sweep. Age is measured from the file's creation time, or from its last write where the filesystem does not record creation time, as in Docker. | `30` | Names must match `^[a-z0-9_]+$`; the metrics process refuses to start on anything else, because the name becomes part of a file path. An epic whose name is not one of the values above collects nothing and is dropped at load with an error logged. diff --git a/docs-site/src/content/docs/features/mcp.md b/docs-site/src/content/docs/features/mcp.md index 73b9d66a..31fa2191 100644 --- a/docs-site/src/content/docs/features/mcp.md +++ b/docs-site/src/content/docs/features/mcp.md @@ -3,7 +3,7 @@ title: AI Assistants (MCP) description: Let AI assistants such as Claude Code and Cursor read Valkey data through Valkey Admin --- -Valkey Admin includes a read-only [MCP](https://modelcontextprotocol.io) server. AI assistants that support MCP, such as Claude Code and Cursor, can use it to read server info, big keys and hot keys from your Valkey deployments. +Valkey Admin includes a read-only [MCP](https://modelcontextprotocol.io) server. AI assistants that support MCP, such as Claude Code and Cursor, can use it to read server info, big keys, hot keys and command logs from your Valkey deployments. ``` AI assistant --HTTP--> MCP server --WebSocket--> Valkey Admin server --> Valkey @@ -20,9 +20,12 @@ The MCP server needs Web mode. It is not available in the desktop app, or in Kub | `get_server_info` | INFO and memory data | None | Yes | Connected node only | | `get_big_keys` | Largest keys by memory | `topN` (default 20), `scanLimit` per node (default 10000) | Yes | All nodes | | `get_hot_keys` | Most frequently accessed keys | `count` (default 20) | No | All nodes | +| `get_command_logs` | Recent slow commands, large requests or large replies, largest first | `type` (`slow`, `large-request` or `large-reply`, default `slow`), `count` (default 20, max 100) | Yes | All nodes | `get_hot_keys` requires cluster mode, `cluster-slot-stats-enabled yes` and an LFU `maxmemory-policy` such as `allkeys-lfu`. See [Hot Slots Detection](/features/activity/#hot-slots-detection-recommended). +`get_command_logs` reads `COMMANDLOG`, which needs Valkey 8.1 or later. Each node keeps its latest entries per log, so results show recent activity, not a time range. Results include the command name and argument count only, never the arguments, so key names and values stay out. See [Command Logs](/features/activity/#command-logs). + `get_big_keys` adds load to each node it scans. `scanLimit` applies per node, so a three-node cluster with the default limit can scan up to about 30,000 keys. ## Enable it in Docker @@ -112,6 +115,7 @@ Valkey Admin itself has no authentication, so keep publishing port `8080` on loo | `503` from `/mcp` | The MCP server is not running. The Valkey Admin server log says why: a missing token or targets, a short token or an invalid target entry | | `No reply from Valkey Admin for ...` | The request passed the 10-second limit. Lower `scanLimit` and try again | | `Hot keys use cluster slot stats, which need ...` | Apply the settings listed in the error | +| `Command logs need Valkey 8.1 or later ...` | `get_command_logs` needs Valkey 8.1 or later. Upgrade the nodes, or use the other tools | | `Metrics server not started` | Metrics are still starting. Try again in a few seconds | | `NOPERM ...` | The Valkey user lacks a command the tools use. See [Read-only Valkey user](#read-only-valkey-user) | | `WRONGPASS ...` | Check `VALKEY_ADMIN_MCP_USERNAME` and `VALKEY_ADMIN_MCP_PASSWORD`, and that the user exists on every node |