// Typed Infrastructure Queries // // Host-centric aggregations built on top of OTel hostmetrics data that lands // in metrics_gauge. Conventions (OTel semantic-conventions for hostmetrics): // // - system.cpu.utilization gauge, 0..1, attributes: cpu, state // - system.memory.utilization gauge, 0..1, attributes: state // - system.filesystem.usage sum, bytes, attributes: device, mode, mountpoint, type, state // (state used/free/reserved; semconv renamed it system.filesystem.state) // - system.filesystem.utilization gauge, 0..1, attributes: device, mode, mountpoint, type // (off by default in the hostmetrics receiver, which sets no state; // some shippers add state=used) // - system.cpu.load_average.1m|5m|15m gauge, absolute, no attributes // - system.network.io cumulative sum, bytes, attributes: device, direction // (semconv renamed direction to network.io.direction) // // Host identity is carried on the ResourceAttributes map under `host.name`. import type { DateTime } from "effect" import * as CH from "@maple-dev/effect-orm/expr" import * as T from "@maple-dev/effect-orm/clickhouse" import { param, table } from "@maple-dev/effect-orm/clickhouse" import { from, fromQuery, fromUnion, type ColumnAccessor } from "@maple-dev/effect-orm/clickhouse" import { unionAll, type CHUnionQuery } from "@maple-dev/effect-orm/clickhouse" import { MetricsGauge, MetricsSum, orgIdParam, utcSecondsParam } from "../tables" import { containerRuntimeExpr, deploymentEnvExpr } from "@maple/domain/tinybird/semconv-renames" import { avgIfOrZero, facetAttrExpr, maxIfOrZero, type FacetOutput } from "./query-helpers" import { finiteOrZero } from "./format" import { metricDeltaExpr } from "./metrics" const HOSTMETRIC_NAMES = [ "system.cpu.utilization", "system.memory.utilization", "system.filesystem.utilization", "system.cpu.load_average.15m", ] as const // Per-state CPU values sum to 1 per core, so busy share is 1 - avg(idle). // Averaging every non-idle state instead divides a fully busy host by ~7. // A host with no idle samples falls back to idle = 1, i.e. 0% busy. const hostCpuPctExpr = ($: ColumnAccessor) => CH.greatest_( CH.lit(1).sub( CH.ifNotFinite( CH.avgIf( $.Value, $.MetricName.eq("system.cpu.utilization").and($.Attributes.get("state").eq("idle")), ), 1, ), ), CH.lit(0), ) // Read-only and virtual mounts (snap squashfs, container overlays) always report ~100%. const PSEUDO_FS_TYPES = ["squashfs", "overlay", "tmpfs", "devtmpfs", "iso9660", "ramfs"] as const interface AttributeMap { get(key: string): CH.Expr } // The hostmetrics receiver sends `state`, `mountpoint`, `type` and `device`; current semconv // names them `system.filesystem.state` (…`.mountpoint`, `.type`) and `system.device`. Map get // returns '' for a missing key, so a point carrying neither name reads ''. const renamedAttr = (attributes: AttributeMap, current: string, legacy: string) => CH.coalesce(CH.nullIf(attributes.get(current), ""), attributes.get(legacy)) const filesystemAttr = (attributes: AttributeMap, key: "state" | "mountpoint" | "type") => renamedAttr(attributes, `system.filesystem.${key}`, key) const filesystemDevice = (attributes: AttributeMap) => renamedAttr(attributes, "system.device", "device") // Utilization rows carry no state from the receiver; shippers that split them by state keep `used`. const FILESYSTEM_USED_STATES = ["used", ""] as const const FILESYSTEM_USAGE_STATES = ["used", "free", "reserved"] as const interface FilesystemPointsOpts { hostName?: string search?: string } /** * Used fraction per (host, mountpoint, sample time), from whichever metric the host sends. * `system.filesystem.usage` is on by default and splits bytes by state, so its fraction is * used / (used + free + reserved) over the rows of one scrape. `system.filesystem.utilization` * is opt-in and already is that fraction. A host sending both yields matching points twice, * which leaves averages and maxima unchanged. */ function filesystemUsedFractionPoints(opts: FilesystemPointsOpts) { const hostConditions = (resourceAttributes: AttributeMap) => [ CH.when(opts.hostName, (v: string) => resourceAttributes.get("host.name").eq(v)), CH.when(opts.search, (v: string) => CH.positionCaseInsensitive(resourceAttributes.get("host.name"), CH.lit(v)).gt(0), ), ] const fromUsage = from(MetricsSum) .select(($) => ({ hostName: $.ResourceAttributes.get("host.name"), mountpoint: filesystemAttr($.Attributes, "mountpoint"), device: CH.any_(filesystemDevice($.Attributes)), sampleTime: $.TimeUnix, usedFraction: finiteOrZero( CH.sumIf($.Value, filesystemAttr($.Attributes, "state").eq("used")).div(CH.sum($.Value)), ), })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get("host.name").neq(""), $.MetricName.eq("system.filesystem.usage"), CH.inList(filesystemAttr($.Attributes, "state"), FILESYSTEM_USAGE_STATES), CH.notInList(filesystemAttr($.Attributes, "type"), PSEUDO_FS_TYPES), ...hostConditions($.ResourceAttributes), ]) .groupBy("hostName", "mountpoint", "sampleTime") const fromUtilization = from(MetricsGauge) .select(($) => ({ hostName: $.ResourceAttributes.get("host.name"), mountpoint: filesystemAttr($.Attributes, "mountpoint"), device: filesystemDevice($.Attributes), sampleTime: $.TimeUnix, usedFraction: $.Value, })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get("host.name").neq(""), $.MetricName.eq("system.filesystem.utilization"), CH.inList(filesystemAttr($.Attributes, "state"), FILESYSTEM_USED_STATES), CH.notInList(filesystemAttr($.Attributes, "type"), PSEUDO_FS_TYPES), ...hostConditions($.ResourceAttributes), ]) return fromUnion(unionAll(fromUsage, fromUtilization), "filesystem_points") } // Headline disk %: the fullest real mount per host. function hostDiskPctQuery(opts: FilesystemPointsOpts) { return filesystemUsedFractionPoints(opts) .select(($) => ({ hostName: $.hostName, diskPct: CH.max_($.usedFraction) })) .groupBy("hostName") } // List hosts — one row per host.name with latest-window headline gauges export interface ListHostsOpts { search?: string limit?: number offset?: number } export interface ListHostsOutput { readonly hostName: string readonly osType: string readonly hostArch: string readonly cloudProvider: string readonly lastSeen: DateTime.Utc readonly cpuPct: number readonly memoryPct: number readonly diskPct: number readonly load15: number } export function listHostsQuery(opts: ListHostsOpts = {}) { const hosts = from(MetricsGauge) .select(($) => ({ hostName: $.ResourceAttributes.get("host.name"), osType: CH.any_($.ResourceAttributes.get("os.type")), hostArch: CH.any_($.ResourceAttributes.get("host.arch")), cloudProvider: CH.any_($.ResourceAttributes.get("cloud.provider")), lastSeen: CH.max_($.TimeUnix), cpuPct: hostCpuPctExpr($), memoryPct: avgIfOrZero( $.Value, $.MetricName.eq("system.memory.utilization").and($.Attributes.get("state").eq("used")), ), load15: avgIfOrZero($.Value, $.MetricName.eq("system.cpu.load_average.15m")), })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get("host.name").neq(""), $.MetricName.in_(...HOSTMETRIC_NAMES), CH.when(opts.search, (v: string) => CH.positionCaseInsensitive($.ResourceAttributes.get("host.name"), CH.lit(v)).gt(0), ), ]) .groupBy("hostName") .orderBy(["lastSeen", "desc"]) .limit(opts.limit ?? 200) .offset(opts.offset ?? 0) return fromQuery(hosts, "hosts") .leftJoinQuery(hostDiskPctQuery({ search: opts.search }), "disk", (host, disk) => host.hostName.eq(disk.hostName), ) .select(($) => ({ hostName: $.hostName, osType: $.osType, hostArch: $.hostArch, cloudProvider: $.cloudProvider, lastSeen: $.lastSeen, cpuPct: $.cpuPct, memoryPct: $.memoryPct, diskPct: finiteOrZero($.disk.diskPct), load15: $.load15, })) .orderBy(["lastSeen", "desc"]) .format("JSON") } // Host detail summary — single host, latest-window headline gauges + uptime export interface HostDetailSummaryOpts { hostName: string } export interface HostDetailSummaryOutput { readonly hostName: string readonly osType: string readonly hostArch: string readonly cloudProvider: string readonly cloudRegion: string /** The `src_` id of the source the host last reported through, `""` before sources stamped it. */ readonly sourceId: string readonly firstSeen: DateTime.Utc readonly lastSeen: DateTime.Utc readonly cpuPct: number readonly memoryPct: number readonly diskPct: number readonly load15: number } export function hostDetailSummaryQuery(opts: HostDetailSummaryOpts) { const host = from(MetricsGauge) .select(($) => ({ hostName: $.ResourceAttributes.get("host.name"), osType: CH.any_($.ResourceAttributes.get("os.type")), hostArch: CH.any_($.ResourceAttributes.get("host.arch")), cloudProvider: CH.any_($.ResourceAttributes.get("cloud.provider")), cloudRegion: CH.any_($.ResourceAttributes.get("cloud.region")), sourceId: CH.argMax($.ResourceAttributes.get("maple_source_id"), $.TimeUnix), firstSeen: CH.min_($.TimeUnix), lastSeen: CH.max_($.TimeUnix), cpuPct: hostCpuPctExpr($), memoryPct: avgIfOrZero( $.Value, $.MetricName.eq("system.memory.utilization").and($.Attributes.get("state").eq("used")), ), load15: avgIfOrZero($.Value, $.MetricName.eq("system.cpu.load_average.15m")), })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get("host.name").eq(opts.hostName), $.MetricName.in_(...HOSTMETRIC_NAMES), ]) .groupBy("hostName") return fromQuery(host, "host") .leftJoinQuery(hostDiskPctQuery({ hostName: opts.hostName }), "disk", (h, disk) => h.hostName.eq(disk.hostName), ) .select(($) => ({ hostName: $.hostName, osType: $.osType, hostArch: $.hostArch, cloudProvider: $.cloudProvider, cloudRegion: $.cloudRegion, sourceId: $.sourceId, firstSeen: $.firstSeen, lastSeen: $.lastSeen, cpuPct: $.cpuPct, memoryPct: $.memoryPct, diskPct: finiteOrZero($.disk.diskPct), load15: $.load15, })) .format("JSON") } // Host infra time-series — gauge metric broken down by a single attribute key // (e.g. CPU by state). Always filtered to one host. export interface HostGaugeTimeseriesOpts { hostName: string metricName: string groupByAttributeKey?: string } export interface HostGaugeTimeseriesOutput { readonly bucket: DateTime.Utc readonly attributeValue: string readonly avgValue: number } export function hostGaugeTimeseriesQuery(opts: HostGaugeTimeseriesOpts) { const q = from(MetricsGauge) .select(($) => ({ bucket: CH.toStartOfInterval($.TimeUnix, param.int("bucketSeconds")), attributeValue: opts.groupByAttributeKey ? $.Attributes.get(opts.groupByAttributeKey) : CH.lit(""), avgValue: CH.avg($.Value), })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get("host.name").eq(opts.hostName), $.MetricName.eq(opts.metricName), ]) return (opts.groupByAttributeKey ? q.groupBy("bucket", "attributeValue") : q.groupBy("bucket")) .orderBy(["bucket", "asc"]) .format("JSON") } // Host filesystem time-series — used fraction per mountpoint, same row shape as the gauge series. export interface HostFilesystemTimeseriesOpts { hostName: string } export function hostFilesystemTimeseriesQuery(opts: HostFilesystemTimeseriesOpts) { return filesystemUsedFractionPoints({ hostName: opts.hostName }) .select(($) => ({ bucket: CH.toStartOfInterval($.sampleTime, param.int("bucketSeconds")), attributeValue: $.mountpoint, avgValue: CH.avg($.usedFraction), })) .groupBy("bucket", "attributeValue") .orderBy(["bucket", "asc"]) .format("JSON") } // Host network time-series — bytes/sec per direction. `system.network.io` is a cumulative // counter per (device, direction), so each sample's increase comes from the previous sample of // the same series (`metricDeltaExpr`, which also handles resets and delta temporality), and a // bucket's rate is its summed increase over the seconds of the bucket inside the range. export interface HostNetworkTimeseriesOpts { hostName: string } export interface HostNetworkTimeseriesOutput { readonly bucket: DateTime.Utc readonly attributeValue: string readonly rateValue: number } const NetworkDeltas = table("network_deltas", { external: true, columns: { TimeUnix: T.dateTime64, direction: T.string, delta: T.float64 }, }) export function hostNetworkTimeseriesQuery(opts: HostNetworkTimeseriesOpts) { const deltas = from(MetricsSum) .select(($) => { const previousSample = CH.windowSpec({ partitionBy: [ CH.cityHash64(CH.mapKeys($.Attributes), CH.mapValues($.Attributes)), CH.cityHash64(CH.mapKeys($.ResourceAttributes), CH.mapValues($.ResourceAttributes)), ], orderBy: [[$.TimeUnix, "asc"]], frame: CH.rowsBetween(CH.preceding(1), CH.currentRow), }) return { TimeUnix: $.TimeUnix, direction: renamedAttr($.Attributes, "network.io.direction", "direction"), delta: metricDeltaExpr({ value: $.Value, previousValue: CH.over(CH.lagInFrame($.Value, 1, $.Value), previousSample), startTime: $.StartTimeUnix, previousTime: CH.over(CH.lagInFrame($.TimeUnix, 1, $.TimeUnix), previousSample), time: $.TimeUnix, isDeltaTemporality: CH.dynamicColumn("AggregationTemporality").eq(1), }), } }) .where(($) => [ $.OrgId.eq(orgIdParam), // One bucket of lookback gives the first bucket's series a previous sample. $.TimeUnix.gte(CH.intervalSub(param.dateTime("startTime"), param.int("bucketSeconds"))), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get("host.name").eq(opts.hostName), $.MetricName.eq("system.network.io"), ]) return from(NetworkDeltas) .withCTE("network_deltas", deltas) .select(($) => { const bucket = CH.toStartOfInterval($.TimeUnix, param.int("bucketSeconds")) const bucketStart = CH.toUnixTimestamp(bucket) const rangeStart = CH.toUnixTimestamp(CH.toDateTime(utcSecondsParam("startTime"))) const rangeEnd = CH.toUnixTimestamp(CH.toDateTime(utcSecondsParam("endTime"))) // Edge buckets are partial; dividing by the full width would understate their rate. const coveredSeconds = CH.least_(bucketStart.add(param.int("bucketSeconds")), rangeEnd).sub( CH.greatest_(bucketStart, rangeStart), ) return { bucket, attributeValue: $.direction, rateValue: finiteOrZero(CH.sum($.delta).div(CH.min_(coveredSeconds))), } }) .where(($) => [$.TimeUnix.gte(param.dateTime("startTime"))]) .groupBy("bucket", "attributeValue") .orderBy(["bucket", "asc"]) .format("JSON") } // Host filesystems: used fraction per mountpoint. export interface HostFilesystemsOpts { hostName: string limit?: number } export interface HostFilesystemsOutput { readonly mountpoint: string readonly device: string readonly usedAvg: number readonly usedMax: number } export function hostFilesystemsQuery(opts: HostFilesystemsOpts) { return filesystemUsedFractionPoints({ hostName: opts.hostName }) .select(($) => ({ mountpoint: $.mountpoint, device: CH.any_($.device), usedAvg: finiteOrZero(CH.avg($.usedFraction)), usedMax: CH.ifNotFinite(CH.max_($.usedFraction), 0), })) .groupBy("mountpoint") .orderBy(["usedMax", "desc"]) .limit(opts.limit ?? 20) .format("JSON") } // Kubernetes — pod aggregations over k8s.pod.* metrics emitted by the kubelet // stats receiver. Identity carried on ResourceAttributes: // k8s.pod.name, k8s.pod.uid, k8s.namespace.name, k8s.node.name, // k8s.deployment.name | k8s.statefulset.name | k8s.daemonset.name, // k8s.pod.qos_class, k8s.pod.start_time // Headline metrics: // k8s.pod.cpu.usage gauge, cores // k8s.pod.cpu_limit_utilization gauge, 0..1 // k8s.pod.cpu_request_utilization gauge, 0..1 // k8s.pod.memory_limit_utilization gauge, 0..1 // k8s.pod.memory_request_utilization gauge, 0..1 const POD_METRIC_NAMES = [ "k8s.pod.cpu.usage", "k8s.pod.cpu_limit_utilization", "k8s.pod.cpu_request_utilization", "k8s.pod.memory_limit_utilization", "k8s.pod.memory_request_utilization", ] as const // Facets only need distinct resource-attribute values + uniq(pod.uid); every pod // emits cpu.usage, so one metric enumerates the same set at ~1/5 the rows scanned. // (The *_utilization metrics require requests/limits to be set; cpu.usage does not.) const POD_FACET_PROBE_METRIC = "k8s.pod.cpu.usage" as const /** * Sort keys for the pod list. All of these are select-list aliases, so they sort * the aggregated rows rather than the raw scan. * * `saturation` is the default and means "peak of CPU-vs-limit or memory-vs-limit * over the window" — the thing that decides whether a pod is about to be * throttled or OOM-killed. Sorting on the *average* (which is all the list used * to compute) hides a pod that pinned at 100% for four minutes of a twelve-hour * window behind pods that idle slightly higher. */ export type PodSortKey = "saturation" | "cpuUsage" | "cpuLimitPct" | "memoryLimitPct" | "podName" | "lastSeen" export type SortDirection = "asc" | "desc" /** Pods whose saturation is 0 because no limits are set sort by raw usage instead. */ const POD_SORT_TIEBREAK: ReadonlyArray<[PodSortKey | "cpuUsagePeak", SortDirection]> = [ ["cpuUsagePeak", "desc"], ["podName", "asc"], ] export interface ListPodsOpts { search?: string podNames?: ReadonlyArray namespaces?: ReadonlyArray nodeNames?: ReadonlyArray clusters?: ReadonlyArray deployments?: ReadonlyArray statefulsets?: ReadonlyArray daemonsets?: ReadonlyArray jobs?: ReadonlyArray environments?: ReadonlyArray computeTypes?: ReadonlyArray excludedPodNames?: ReadonlyArray excludedNamespaces?: ReadonlyArray excludedNodeNames?: ReadonlyArray excludedClusters?: ReadonlyArray excludedDeployments?: ReadonlyArray excludedStatefulsets?: ReadonlyArray excludedDaemonsets?: ReadonlyArray excludedJobs?: ReadonlyArray excludedEnvironments?: ReadonlyArray excludedComputeTypes?: ReadonlyArray // Single-value filters retained for backward compat with the workload detail // page, which still narrows by a single workload owner. workloadKind?: WorkloadKind workloadName?: string /** Defaults to `saturation` — see PodSortKey. */ sortBy?: PodSortKey sortDir?: SortDirection /** One-click fleet scope from the summary band. */ scope?: PodScope /** Defaults to `live` — see PodLifecycle. */ lifecycle?: PodLifecycle limit?: number offset?: number } /** * Scopes filter on *aggregated* values, so they can't live in the WHERE clause * alongside the row filters. The builder has no HAVING, so a scoped list wraps * the grouped query and filters outside it — same plan ClickHouse would produce * for HAVING, and it keeps the unscoped query (the common case) single-level. */ export type PodScope = "saturated" | "elevated" | "unbounded" /** * Which slice of the window's pods the caller wants. * * A windowed pod list is the union of everything that reported at any point in * it, so on an autoscaled fleet most of those pods no longer exist — scaled in * by an HPA, rolled out by a deploy, replaced when a Fargate task or spot node * was cycled. Ending is the normal end of a pod's life, not a fault, so the * list defaults to `live` and offers the rest as a deliberate scope. Without * this the ranking, the denominator and the fleet band all mix the dead in with * the running. */ export type PodLifecycle = "live" | "ended" | "all" export interface ListPodsOutput { readonly podName: string readonly namespace: string readonly nodeName: string readonly clusterName: string readonly environment: string readonly deploymentName: string readonly statefulsetName: string readonly daemonsetName: string readonly jobName: string readonly qosClass: string readonly podUid: string // "fargate" for EKS Fargate pods, "ec2" otherwise (empty when the // collector hasn't been told to extract the eks.amazonaws.com/compute-type // label, in which case the UI should treat it as ec2). readonly computeType: string readonly lastSeen: DateTime.Utc // Window averages. readonly cpuUsage: number readonly cpuLimitPct: number readonly memoryLimitPct: number readonly cpuRequestPct: number readonly memoryRequestPct: number // Window peaks. The list sorts and tones on these; the averages are shown // beside them so a row reads "0.42 → 0.97 cores" rather than one number that // could mean either. readonly cpuUsagePeak: number readonly cpuLimitPctPeak: number readonly memoryLimitPctPeak: number /** greatest(cpuLimitPctPeak, memoryLimitPctPeak) — 0 when no limits are set. */ readonly saturation: number } const WORKLOAD_ATTR_KEY = { deployment: "k8s.deployment.name", statefulset: "k8s.statefulset.name", daemonset: "k8s.daemonset.name", job: "k8s.job.name", } as const satisfies Record const workloadAttrKey = (kind: WorkloadKind) => WORKLOAD_ATTR_KEY[kind] const podBaseConditions = ( $: ColumnAccessor, metricNames: ReadonlyArray = POD_METRIC_NAMES, ): Array => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get("k8s.pod.name").neq(""), $.MetricName.in_(...metricNames), ] /** * Every pod facet, paired with the resource-attribute key it filters on. * * Driven from one table rather than open-coded per dimension: ten facets written out twice — once * to include, once to exclude — is exactly where a missed polarity hides. `attr: null` means the * dimension needs a real expression (environment coalesces both semconv spellings) rather than a * plain map read. Order here is the emitted clause order, so it stays as it was. */ const POD_FACETS = [ { include: "podNames", exclude: "excludedPodNames", attr: "k8s.pod.name" }, { include: "namespaces", exclude: "excludedNamespaces", attr: "k8s.namespace.name" }, { include: "nodeNames", exclude: "excludedNodeNames", attr: "k8s.node.name" }, { include: "clusters", exclude: "excludedClusters", attr: "k8s.cluster.name" }, { include: "deployments", exclude: "excludedDeployments", attr: "k8s.deployment.name" }, { include: "statefulsets", exclude: "excludedStatefulsets", attr: "k8s.statefulset.name" }, { include: "daemonsets", exclude: "excludedDaemonsets", attr: "k8s.daemonset.name" }, { include: "jobs", exclude: "excludedJobs", attr: "k8s.job.name" }, { include: "environments", exclude: "excludedEnvironments", attr: null }, { include: "computeTypes", exclude: "excludedComputeTypes", attr: "eks.amazonaws.com/compute-type", }, ] as const satisfies ReadonlyArray<{ include: keyof ListPodsOpts exclude: keyof ListPodsOpts attr: string | null }> const podFilterConditions = ( $: ColumnAccessor, opts: ListPodsOpts, ): Array => [ CH.when(opts.search, (v: string) => CH.positionCaseInsensitive($.ResourceAttributes.get("k8s.pod.name"), CH.lit(v)).gt(0), ), ...POD_FACETS.flatMap(({ include, exclude, attr }) => { const expr = attr === null ? deploymentEnvExpr($.ResourceAttributes) : $.ResourceAttributes.get(attr) const included = opts[include] const excluded = opts[exclude] return [ included?.length ? CH.inList(expr, included) : undefined, excluded?.length ? CH.notInList(expr, excluded) : undefined, ] }), CH.when( opts.workloadKind !== undefined && opts.workloadName !== undefined ? { kind: opts.workloadKind, name: opts.workloadName } : undefined, (workload) => $.ResourceAttributes.get(workloadAttrKey(workload.kind)).eq(workload.name), ), ] /** * Ten collection intervals at the chart's 30s default. A pod whose newest * datapoint predates this is one whose series ended, which for a pod means it * stopped existing — the same cutoff `deriveHostStatus` uses in the web app, so * the badge on a row and the predicate that selected it never disagree. */ const ENDED_POD_SECONDS = 300 /** * `lastSeen` is an aggregate, so these belong outside the grouping. The cutoff * rides on `endTime` rather than wall-clock now, so a window that ended an hour * ago still reports who was live *then*. */ type PodLifecycleColumns = { lastSeen: CH.Expr } const endedCutoff = () => CH.intervalSub(param.dateTime("endTime"), ENDED_POD_SECONDS) const podLiveCondition = ($: PodLifecycleColumns) => $.lastSeen.gte(endedCutoff()) const podEndedCondition = ($: PodLifecycleColumns) => $.lastSeen.lt(endedCutoff()) const podLifecycleCondition = ($: PodLifecycleColumns, lifecycle: PodLifecycle): CH.Condition | undefined => { switch (lifecycle) { case "live": return podLiveCondition($) case "ended": return podEndedCondition($) case "all": return undefined } } export function listPodsQuery(opts: ListPodsOpts = {}) { const sortBy = opts.sortBy ?? "saturation" const sortDir = opts.sortDir ?? (sortBy === "podName" ? "asc" : "desc") const orderBy: Array<[string, SortDirection]> = [ [sortBy, sortDir], ...POD_SORT_TIEBREAK.filter(([key]) => key !== sortBy), ] const grouped = from(MetricsGauge) .select(($) => ({ podName: $.ResourceAttributes.get("k8s.pod.name"), namespace: CH.any_($.ResourceAttributes.get("k8s.namespace.name")), nodeName: CH.any_($.ResourceAttributes.get("k8s.node.name")), clusterName: CH.any_($.ResourceAttributes.get("k8s.cluster.name")), environment: CH.any_(deploymentEnvExpr($.ResourceAttributes)), deploymentName: CH.any_($.ResourceAttributes.get("k8s.deployment.name")), statefulsetName: CH.any_($.ResourceAttributes.get("k8s.statefulset.name")), daemonsetName: CH.any_($.ResourceAttributes.get("k8s.daemonset.name")), jobName: CH.any_($.ResourceAttributes.get("k8s.job.name")), qosClass: CH.any_($.ResourceAttributes.get("k8s.pod.qos_class")), podUid: CH.any_($.ResourceAttributes.get("k8s.pod.uid")), computeType: CH.any_($.ResourceAttributes.get("eks.amazonaws.com/compute-type")), lastSeen: CH.max_($.TimeUnix), cpuUsage: avgIfOrZero($.Value, $.MetricName.eq("k8s.pod.cpu.usage")), cpuLimitPct: avgIfOrZero($.Value, $.MetricName.eq("k8s.pod.cpu_limit_utilization")), memoryLimitPct: avgIfOrZero($.Value, $.MetricName.eq("k8s.pod.memory_limit_utilization")), cpuRequestPct: avgIfOrZero($.Value, $.MetricName.eq("k8s.pod.cpu_request_utilization")), memoryRequestPct: avgIfOrZero($.Value, $.MetricName.eq("k8s.pod.memory_request_utilization")), // Peaks ride along on the same scan the averages already pay for. cpuUsagePeak: maxIfOrZero($.Value, $.MetricName.eq("k8s.pod.cpu.usage")), cpuLimitPctPeak: maxIfOrZero($.Value, $.MetricName.eq("k8s.pod.cpu_limit_utilization")), memoryLimitPctPeak: maxIfOrZero($.Value, $.MetricName.eq("k8s.pod.memory_limit_utilization")), saturation: CH.greatest_( maxIfOrZero($.Value, $.MetricName.eq("k8s.pod.cpu_limit_utilization")), maxIfOrZero($.Value, $.MetricName.eq("k8s.pod.memory_limit_utilization")), ), })) .where(($) => [...podBaseConditions($), ...podFilterConditions($, opts)]) .groupBy("podName") // Always wrapped, scope or not: sorting and scoping both operate on aggregates, // and one code path is worth more than saving a subquery ClickHouse flattens // anyway. return fromQuery(grouped, "pods") .select(($) => ({ podName: $.podName, namespace: $.namespace, nodeName: $.nodeName, clusterName: $.clusterName, environment: $.environment, deploymentName: $.deploymentName, statefulsetName: $.statefulsetName, daemonsetName: $.daemonsetName, jobName: $.jobName, qosClass: $.qosClass, podUid: $.podUid, computeType: $.computeType, lastSeen: $.lastSeen, cpuUsage: $.cpuUsage, cpuLimitPct: $.cpuLimitPct, memoryLimitPct: $.memoryLimitPct, cpuRequestPct: $.cpuRequestPct, memoryRequestPct: $.memoryRequestPct, cpuUsagePeak: $.cpuUsagePeak, cpuLimitPctPeak: $.cpuLimitPctPeak, memoryLimitPctPeak: $.memoryLimitPctPeak, saturation: $.saturation, })) .where(($) => [ podLifecycleCondition($, opts.lifecycle ?? "live"), opts.scope ? podScopeCondition($, opts.scope) : undefined, ]) .orderBy(...(orderBy as Array<[never, SortDirection]>)) .limit(opts.limit ?? 50) .offset(opts.offset ?? 0) .format("JSON") } /** * A pod with no limits set reports 0 for both limit utilizations — the metrics * simply aren't emitted — so `saturation = 0 AND cpuUsagePeak > 0` is exactly * "burning CPU with nothing capping it", with no extra column to carry. */ function podScopeCondition( $: { saturation: CH.Expr cpuUsagePeak: CH.Expr }, scope: PodScope, ): CH.Condition { switch (scope) { case "saturated": return $.saturation.gte(0.9) case "elevated": return $.saturation.gte(0.6).and($.saturation.lt(0.9)) case "unbounded": return $.saturation.eq(0).and($.cpuUsagePeak.gt(0)) } } // Pod count — the denominator behind "Top 50 of 1,284". // // The list is limited, so `rows.length` only ever tells you how many rows came // back, never how many matched. Without this the UI silently claims the fleet is // the size of the page. export interface ListPodsSummaryOutput { /** Still reporting at the window's end — the fleet as it stands. */ readonly livePods: number /** * Reported earlier in the window and stopped. Scale-in, a rollout, a cycled * Fargate task: expected churn, counted separately so it can be offered as a * scope instead of inflating the denominator. */ readonly endedPods: number /** Peak of either limit ≥ 0.9 — matches severityLevel("crit") in the web app. */ readonly saturatedPods: number /** Peak of either limit in [0.6, 0.9). */ readonly elevatedPods: number /** Burning CPU with no limit set at all — invisible to a saturation ranking. */ readonly unboundedPods: number } /** * One row of fleet-shape counts for the browse summary band. * * Deliberately runs over the *same* WHERE as the list so the band and the table * agree, and aggregates per pod first so the counts are exact rather than HLL * estimates — `uniq` set-differences would drift on exactly the small numbers * ("7 saturated") the band leads with. */ export function listPodsSummaryQuery(opts: ListPodsOpts = {}) { const perPod = from(MetricsGauge) .select(($) => ({ podName: $.ResourceAttributes.get("k8s.pod.name"), lastSeen: CH.max_($.TimeUnix), cpuUsagePeak: maxIfOrZero($.Value, $.MetricName.eq("k8s.pod.cpu.usage")), saturation: CH.greatest_( maxIfOrZero($.Value, $.MetricName.eq("k8s.pod.cpu_limit_utilization")), maxIfOrZero($.Value, $.MetricName.eq("k8s.pod.memory_limit_utilization")), ), limitSamples: CH.countIf( $.MetricName.in_("k8s.pod.cpu_limit_utilization", "k8s.pod.memory_limit_utilization"), ), })) .where(($) => [...podBaseConditions($), ...podFilterConditions($, opts)]) .groupBy("podName") // Live/ended are absolute so the band can always offer "and N more that // ended"; the saturation buckets are counted WITHIN the requested lifecycle // so they stay a valid denominator for the list that ran beside them. const lifecycle = opts.lifecycle ?? "live" return fromQuery(perPod, "pods") .select(($) => { const inScope = podLifecycleCondition($, lifecycle) const within = (condition: CH.Condition) => CH.countIf(inScope ? inScope.and(condition) : condition) return { livePods: CH.countIf(podLiveCondition($)), endedPods: CH.countIf(podEndedCondition($)), saturatedPods: within($.saturation.gte(0.9)), elevatedPods: within($.saturation.gte(0.6).and($.saturation.lt(0.9))), unboundedPods: within($.limitSamples.eq(0).and($.cpuUsagePeak.gt(0))), } }) .format("JSON") } export interface PodDetailSummaryOpts { podName: string namespace?: string } export interface PodDetailSummaryOutput { readonly podName: string readonly namespace: string readonly nodeName: string readonly deploymentName: string readonly statefulsetName: string readonly daemonsetName: string readonly qosClass: string readonly podUid: string readonly computeType: string readonly podStartTime: string readonly sourceId: string readonly firstSeen: DateTime.Utc readonly lastSeen: DateTime.Utc readonly cpuUsage: number readonly cpuLimitPct: number readonly memoryLimitPct: number readonly cpuRequestPct: number readonly memoryRequestPct: number } export function podDetailSummaryQuery(opts: PodDetailSummaryOpts) { return from(MetricsGauge) .select(($) => ({ podName: $.ResourceAttributes.get("k8s.pod.name"), namespace: CH.any_($.ResourceAttributes.get("k8s.namespace.name")), nodeName: CH.any_($.ResourceAttributes.get("k8s.node.name")), deploymentName: CH.any_($.ResourceAttributes.get("k8s.deployment.name")), statefulsetName: CH.any_($.ResourceAttributes.get("k8s.statefulset.name")), daemonsetName: CH.any_($.ResourceAttributes.get("k8s.daemonset.name")), qosClass: CH.any_($.ResourceAttributes.get("k8s.pod.qos_class")), podUid: CH.any_($.ResourceAttributes.get("k8s.pod.uid")), computeType: CH.any_($.ResourceAttributes.get("eks.amazonaws.com/compute-type")), podStartTime: CH.any_($.ResourceAttributes.get("k8s.pod.start_time")), sourceId: CH.argMax($.ResourceAttributes.get("maple_source_id"), $.TimeUnix), firstSeen: CH.min_($.TimeUnix), lastSeen: CH.max_($.TimeUnix), cpuUsage: avgIfOrZero($.Value, $.MetricName.eq("k8s.pod.cpu.usage")), cpuLimitPct: avgIfOrZero($.Value, $.MetricName.eq("k8s.pod.cpu_limit_utilization")), memoryLimitPct: avgIfOrZero($.Value, $.MetricName.eq("k8s.pod.memory_limit_utilization")), cpuRequestPct: avgIfOrZero($.Value, $.MetricName.eq("k8s.pod.cpu_request_utilization")), memoryRequestPct: avgIfOrZero($.Value, $.MetricName.eq("k8s.pod.memory_request_utilization")), })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get("k8s.pod.name").eq(opts.podName), CH.when(opts.namespace, (v: string) => $.ResourceAttributes.get("k8s.namespace.name").eq(v)), $.MetricName.in_(...POD_METRIC_NAMES), ]) .groupBy("podName") .format("JSON") } // Pod container restarts, from the k8s_cluster receiver's `k8s.container.restarts` // (a running total per container). The window's restarts are last - first, floored at 0: // a kubelet that prunes dead containers can reset the total, so this undercounts, never over. export interface PodRestartsOpts { podNames?: ReadonlyArray namespace?: string workloadKind?: WorkloadKind workloadName?: string limit?: number } export interface PodRestartsOutput { readonly podName: string readonly namespace: string readonly containerName: string readonly restarts: number readonly totalRestarts: number /** `k8s.container.status.last_terminated_reason` (OOMKilled, Error, ...); empty when never terminated. */ readonly lastTerminatedReason: string } export function podRestartsQuery(opts: PodRestartsOpts) { return from(MetricsGauge) .select(($) => ({ podName: $.ResourceAttributes.get("k8s.pod.name"), namespace: $.ResourceAttributes.get("k8s.namespace.name"), containerName: $.ResourceAttributes.get("k8s.container.name"), restarts: CH.ifNotFinite( CH.greatest_(CH.argMax($.Value, $.TimeUnix).sub(CH.argMin($.Value, $.TimeUnix)), CH.lit(0)), 0, ), totalRestarts: CH.ifNotFinite(CH.argMax($.Value, $.TimeUnix), 0), // The attribute rides on the resource, so the newest sample carries the newest reason. lastTerminatedReason: CH.argMax( $.ResourceAttributes.get("k8s.container.status.last_terminated_reason"), $.TimeUnix, ), })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.MetricName.eq("k8s.container.restarts"), $.ResourceAttributes.get("k8s.pod.name").neq(""), opts.podNames?.length ? CH.inList($.ResourceAttributes.get("k8s.pod.name"), opts.podNames) : undefined, CH.when(opts.namespace, (v: string) => $.ResourceAttributes.get("k8s.namespace.name").eq(v)), CH.when(opts.workloadName, (v: string) => $.ResourceAttributes.get(workloadAttrKey(opts.workloadKind ?? "deployment")).eq(v), ), ]) .groupBy("podName", "namespace", "containerName") .orderBy(["restarts", "desc"], ["totalRestarts", "desc"]) .limit(opts.limit ?? 50) .format("JSON") } // Pod time-series — gauge metric for one pod, optionally broken down by an // attribute key (e.g. container name, when present). export interface PodGaugeTimeseriesOpts { podName: string namespace?: string metricName: string groupByAttributeKey?: string } export function podGaugeTimeseriesQuery(opts: PodGaugeTimeseriesOpts) { const q = from(MetricsGauge) .select(($) => ({ bucket: CH.toStartOfInterval($.TimeUnix, param.int("bucketSeconds")), attributeValue: opts.groupByAttributeKey ? $.ResourceAttributes.get(opts.groupByAttributeKey) : CH.lit(""), avgValue: CH.avg($.Value), })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get("k8s.pod.name").eq(opts.podName), CH.when(opts.namespace, (v: string) => $.ResourceAttributes.get("k8s.namespace.name").eq(v)), $.MetricName.eq(opts.metricName), ]) return (opts.groupByAttributeKey ? q.groupBy("bucket", "attributeValue") : q.groupBy("bucket")) .orderBy(["bucket", "asc"]) .format("JSON") } // Kubernetes — node aggregations over k8s.node.* metrics from the kubelet // stats + k8s_cluster receivers. // k8s.node.cpu.usage gauge, cores (kubeletstats) // k8s.node.uptime gauge, seconds (kubeletstats) // k8s.node.memory.working_set gauge, bytes (kubeletstats) // k8s.node.allocatable_cpu gauge, cores (k8s_cluster, allocatable_types_to_report) // k8s.node.allocatable_memory gauge, bytes (k8s_cluster, allocatable_types_to_report) const NODE_ALLOCATABLE_CPU_METRIC = "k8s.node.allocatable_cpu" as const const NODE_ALLOCATABLE_MEMORY_METRIC = "k8s.node.allocatable_memory" as const const NODE_METRIC_NAMES = [ "k8s.node.cpu.usage", "k8s.node.uptime", "k8s.node.memory.working_set", NODE_ALLOCATABLE_CPU_METRIC, NODE_ALLOCATABLE_MEMORY_METRIC, ] as const // Single representative metric for node facets — see POD_FACET_PROBE_METRIC. const NODE_FACET_PROBE_METRIC = "k8s.node.cpu.usage" as const export interface ListNodesOpts { search?: string nodeNames?: ReadonlyArray clusters?: ReadonlyArray environments?: ReadonlyArray limit?: number offset?: number } /** Usage, allocatable capacity, usage/allocatable fractions and uptime; 0 when not collected. */ export interface NodeCapacityOutput { readonly cpuUsage: number readonly cpuAllocatable: number readonly cpuUtilization: number readonly memoryUsage: number readonly memoryAllocatable: number readonly memoryUtilization: number readonly uptime: number } export interface ListNodesOutput extends NodeCapacityOutput { readonly nodeName: string readonly nodeUid: string readonly clusterName: string readonly environment: string readonly kubeletVersion: string readonly lastSeen: DateTime.Utc } /** `usage / allocatable`; 0 when allocatable was not collected (x/0 is non-finite). */ const ratioOrZero = (usage: CH.Expr, allocatable: CH.Expr): CH.Expr => finiteOrZero(usage.div(allocatable)) // The node row merges two receivers: kubeletstats (usage) and k8s_cluster (allocatable, // kubelet version). String attributes skip the receiver that leaves them empty. const nodeCapacityColumns = ($: ColumnAccessor) => { const cpuUsage = avgIfOrZero($.Value, $.MetricName.eq("k8s.node.cpu.usage")) const cpuAllocatable = maxIfOrZero($.Value, $.MetricName.eq(NODE_ALLOCATABLE_CPU_METRIC)) const memoryUsage = avgIfOrZero($.Value, $.MetricName.eq("k8s.node.memory.working_set")) const memoryAllocatable = maxIfOrZero($.Value, $.MetricName.eq(NODE_ALLOCATABLE_MEMORY_METRIC)) return { cpuUsage, cpuAllocatable, cpuUtilization: ratioOrZero(cpuUsage, cpuAllocatable), memoryUsage, memoryAllocatable, memoryUtilization: ratioOrZero(memoryUsage, memoryAllocatable), uptime: maxIfOrZero($.Value, $.MetricName.eq("k8s.node.uptime")), } } const nonEmptyAttr = ($: ColumnAccessor, key: string) => CH.anyIf($.ResourceAttributes.get(key), $.ResourceAttributes.get(key).neq("")) // Nodes that only k8s_cluster reports (EKS Fargate virtual nodes, nodes the DaemonSet // does not run on) carry capacity but no usage; the list and facets both require kubelet data. const hasKubeletUsage = ($: ColumnAccessor) => CH.countIf($.MetricName.eq(NODE_FACET_PROBE_METRIC)).gt(0) const nodeBaseConditions = ( $: ColumnAccessor, metricNames: ReadonlyArray = NODE_METRIC_NAMES, ): Array => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get("k8s.node.name").neq(""), $.ResourceAttributes.get("k8s.pod.name").eq(""), $.MetricName.in_(...metricNames), ] const nodeFilterConditions = ( $: ColumnAccessor, opts: ListNodesOpts, ): Array => [ CH.when(opts.search, (v: string) => CH.positionCaseInsensitive($.ResourceAttributes.get("k8s.node.name"), CH.lit(v)).gt(0), ), opts.nodeNames?.length ? CH.inList($.ResourceAttributes.get("k8s.node.name"), opts.nodeNames) : undefined, opts.clusters?.length ? CH.inList($.ResourceAttributes.get("k8s.cluster.name"), opts.clusters) : undefined, opts.environments?.length ? CH.inList(deploymentEnvExpr($.ResourceAttributes), opts.environments) : undefined, ] export function listNodesQuery(opts: ListNodesOpts = {}) { return from(MetricsGauge) .select(($) => ({ nodeName: $.ResourceAttributes.get("k8s.node.name"), nodeUid: nonEmptyAttr($, "k8s.node.uid"), clusterName: nonEmptyAttr($, "k8s.cluster.name"), environment: CH.anyIf( deploymentEnvExpr($.ResourceAttributes), deploymentEnvExpr($.ResourceAttributes).neq(""), ), kubeletVersion: nonEmptyAttr($, "k8s.kubelet.version"), lastSeen: CH.max_($.TimeUnix), ...nodeCapacityColumns($), })) .where(($) => [...nodeBaseConditions($), ...nodeFilterConditions($, opts)]) .groupBy("nodeName") .having(($) => [hasKubeletUsage($)]) .orderBy(["lastSeen", "desc"]) .limit(opts.limit ?? 200) .offset(opts.offset ?? 0) .format("JSON") } export interface NodeDetailSummaryOpts { nodeName: string } export interface NodeDetailSummaryOutput extends NodeCapacityOutput { readonly nodeName: string readonly nodeUid: string readonly kubeletVersion: string readonly containerRuntime: string readonly sourceId: string readonly firstSeen: DateTime.Utc readonly lastSeen: DateTime.Utc } export function nodeDetailSummaryQuery(opts: NodeDetailSummaryOpts) { return from(MetricsGauge) .select(($) => ({ nodeName: $.ResourceAttributes.get("k8s.node.name"), nodeUid: nonEmptyAttr($, "k8s.node.uid"), kubeletVersion: nonEmptyAttr($, "k8s.kubelet.version"), containerRuntime: CH.anyIf( containerRuntimeExpr($.ResourceAttributes), containerRuntimeExpr($.ResourceAttributes).neq(""), ), sourceId: CH.argMax($.ResourceAttributes.get("maple_source_id"), $.TimeUnix), firstSeen: CH.min_($.TimeUnix), lastSeen: CH.max_($.TimeUnix), ...nodeCapacityColumns($), })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get("k8s.node.name").eq(opts.nodeName), $.ResourceAttributes.get("k8s.pod.name").eq(""), $.MetricName.in_(...NODE_METRIC_NAMES), ]) .groupBy("nodeName") .format("JSON") } export interface NodeGaugeTimeseriesOpts { nodeName: string metricName: string /** Plot `metricName / capacityMetricName` per bucket (a 0-1 fraction) instead of the raw gauge. */ capacityMetricName?: string } export function nodeGaugeTimeseriesQuery(opts: NodeGaugeTimeseriesOpts) { const capacityMetricName = opts.capacityMetricName return from(MetricsGauge) .select(($) => ({ bucket: CH.toStartOfInterval($.TimeUnix, param.int("bucketSeconds")), attributeValue: CH.lit(""), avgValue: capacityMetricName ? ratioOrZero( avgIfOrZero($.Value, $.MetricName.eq(opts.metricName)), maxIfOrZero($.Value, $.MetricName.eq(capacityMetricName)), ) : CH.avg($.Value), })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get("k8s.node.name").eq(opts.nodeName), $.ResourceAttributes.get("k8s.pod.name").eq(""), capacityMetricName ? $.MetricName.in_(opts.metricName, capacityMetricName) : $.MetricName.eq(opts.metricName), ]) .groupBy("bucket") .orderBy(["bucket", "asc"]) .format("JSON") } // Kubernetes — workload aggregations (Deployment / StatefulSet / DaemonSet / Job). // Walks over k8s.pod.* metrics and groups by workload-name + namespace. export type WorkloadKind = "deployment" | "statefulset" | "daemonset" | "job" export interface ListWorkloadsOpts { kind: WorkloadKind search?: string workloadNames?: ReadonlyArray namespaces?: ReadonlyArray clusters?: ReadonlyArray environments?: ReadonlyArray computeTypes?: ReadonlyArray limit?: number offset?: number } export interface ListWorkloadsOutput { readonly workloadName: string readonly namespace: string readonly clusterName: string readonly environment: string readonly podCount: number readonly lastSeen: DateTime.Utc /** * The latest desired / ready gauges from the k8s_cluster receiver. Jobs report * completions: desired successful pods and pods that succeeded. Both read 0 when * `replicaSamples` is 0, i.e. the cluster collector isn't running. */ readonly desiredReplicas: number readonly readyReplicas: number readonly replicaSamples: number /** Desired minus ready, never negative; always 0 for jobs, whose shortfall is just "still running". */ readonly shortfall: number /** Jobs only: pods that failed. */ readonly failedPods: number /** Container restarts in the window, summed over every pod. */ readonly restarts: number /** The reason a restarting container last terminated (OOMKilled, Error, ...); empty with no restarts. */ readonly lastTerminatedReason: string /** The worst pod's peak, not the average: the average hides the one pod at its limit. */ readonly peakCpuLimitPct: number readonly peakMemoryLimitPct: number readonly saturation: number /** Cores in use now, summed over the pods still reporting at the window's end. */ readonly cpuUsage: number } /** The k8s_cluster receiver's gauges for each kind; job readiness counts completions. */ const WORKLOAD_REPLICA_METRICS = { deployment: { desired: "k8s.deployment.desired", ready: "k8s.deployment.available" }, statefulset: { desired: "k8s.statefulset.desired_pods", ready: "k8s.statefulset.ready_pods" }, daemonset: { desired: "k8s.daemonset.desired_scheduled_nodes", ready: "k8s.daemonset.ready_nodes" }, job: { desired: "k8s.job.desired_successful_pods", ready: "k8s.job.successful_pods" }, } as const satisfies Record const JOB_FAILED_METRIC = "k8s.job.failed_pods" as const const CONTAINER_RESTARTS_METRIC = "k8s.container.restarts" as const const workloadFilterConditions = ( $: ColumnAccessor, opts: ListWorkloadsOpts, attrKey: string, ): Array => [ CH.when(opts.search, (v: string) => CH.positionCaseInsensitive($.ResourceAttributes.get(attrKey), CH.lit(v)).gt(0), ), opts.workloadNames?.length ? CH.inList($.ResourceAttributes.get(attrKey), opts.workloadNames) : undefined, opts.namespaces?.length ? CH.inList($.ResourceAttributes.get("k8s.namespace.name"), opts.namespaces) : undefined, opts.clusters?.length ? CH.inList($.ResourceAttributes.get("k8s.cluster.name"), opts.clusters) : undefined, opts.environments?.length ? CH.inList(deploymentEnvExpr($.ResourceAttributes), opts.environments) : undefined, // Pod and restart series carry the compute-type label (k8sattributes copies it from the node); // the replica gauges don't, so they stay in the scan and listWorkloadsQuery drops workloads // with no matching pod series. opts.computeTypes?.length ? CH.notInList($.MetricName, [...POD_METRIC_NAMES, CONTAINER_RESTARTS_METRIC]).or( CH.inList($.ResourceAttributes.get("eks.amazonaws.com/compute-type"), opts.computeTypes), ) : undefined, ] /** * One row per workload: replica health from the k8s_cluster gauges, restarts from * `k8s.container.restarts`, and the worst pod's saturation from kubeletstats. * * The inner pass reduces each series (one pod, one container, one metric) to its * first, last and peak value, because restarts are a running total per container * and only the series' delta is meaningful. The outer pass rolls the series up per * workload. Sorted worst first: missing replicas, failed job pods, restarts, saturation. */ export function listWorkloadsQuery(opts: ListWorkloadsOpts) { const attrKey = workloadAttrKey(opts.kind) const replica = WORKLOAD_REPLICA_METRICS[opts.kind] const metricNames = [ ...POD_METRIC_NAMES, CONTAINER_RESTARTS_METRIC, replica.desired, replica.ready, ...(opts.kind === "job" ? [JOB_FAILED_METRIC] : []), ] const perSeries = from(MetricsGauge) .select(($) => ({ workloadName: $.ResourceAttributes.get(attrKey), // Same-named workloads in different namespaces/clusters are distinct rows. namespace: $.ResourceAttributes.get("k8s.namespace.name"), clusterName: $.ResourceAttributes.get("k8s.cluster.name"), podUid: $.ResourceAttributes.get("k8s.pod.uid"), containerName: $.ResourceAttributes.get("k8s.container.name"), metric: $.MetricName, environment: CH.any_(deploymentEnvExpr($.ResourceAttributes)), earliest: CH.argMin($.Value, $.TimeUnix), latest: CH.argMax($.Value, $.TimeUnix), peak: CH.max_($.Value), lastSeen: CH.max_($.TimeUnix), lastReason: CH.argMax( $.ResourceAttributes.get("k8s.container.status.last_terminated_reason"), $.TimeUnix, ), // When a restart counter first reached its high-water mark, i.e. its last restart. // The key ranks by value, then by earliest time; both fit exactly in a Float64. restartedAt: CH.toUnixTimestamp( CH.argMax($.TimeUnix, $.Value.mul(4294967296).sub(CH.toUnixTimestamp($.TimeUnix))), ), })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get(attrKey).neq(""), $.MetricName.in_(...metricNames), ...workloadFilterConditions($, opts, attrKey), ]) .groupBy("workloadName", "namespace", "clusterName", "podUid", "containerName", "metric") const perWorkload = fromQuery(perSeries, "series") .select(($) => { const isRestarts = $.metric.eq(CONTAINER_RESTARTS_METRIC) const restartDelta = CH.greatest_($.latest.sub($.earliest), CH.lit(0)) const restartedWithReason = isRestarts.and($.latest.gt($.earliest)).and($.lastReason.neq("")) const desiredReplicas = maxIfOrZero($.latest, $.metric.eq(replica.desired)) const readyReplicas = maxIfOrZero($.latest, $.metric.eq(replica.ready)) const peakCpuLimitPct = maxIfOrZero($.peak, $.metric.eq("k8s.pod.cpu_limit_utilization")) const peakMemoryLimitPct = maxIfOrZero($.peak, $.metric.eq("k8s.pod.memory_limit_utilization")) return { workloadName: $.workloadName, namespace: $.namespace, clusterName: $.clusterName, environment: CH.any_($.environment), podCount: CH.uniqIf($.podUid, CH.inList($.metric, POD_METRIC_NAMES)), lastSeen: CH.max_($.lastSeen), desiredReplicas, readyReplicas, replicaSamples: CH.countIf($.metric.eq(replica.desired)), shortfall: opts.kind === "job" ? CH.lit(0) : CH.greatest_(desiredReplicas.sub(readyReplicas), CH.lit(0)), failedPods: maxIfOrZero($.latest, $.metric.eq(JOB_FAILED_METRIC)), restarts: finiteOrZero(CH.sumIf(restartDelta, isRestarts)), // The reason of whichever container restarted most recently. lastTerminatedReason: CH.argMax( CH.if_(restartedWithReason, $.lastReason, CH.lit("")), CH.if_(restartedWithReason, $.restartedAt, CH.lit(0)), ), peakCpuLimitPct, peakMemoryLimitPct, saturation: CH.greatest_(peakCpuLimitPct, peakMemoryLimitPct), cpuUsage: finiteOrZero( CH.sumIf($.latest, $.metric.eq("k8s.pod.cpu.usage").and($.lastSeen.gte(endedCutoff()))), ), } }) .groupBy("workloadName", "namespace", "clusterName") // The builder has no HAVING, so the compute-type gate filters outside the grouping: // a workload qualifies only if at least one of its pod series matched the filter. return fromQuery(perWorkload, "workloads") .select(($) => ({ workloadName: $.workloadName, namespace: $.namespace, clusterName: $.clusterName, environment: $.environment, podCount: $.podCount, lastSeen: $.lastSeen, desiredReplicas: $.desiredReplicas, readyReplicas: $.readyReplicas, replicaSamples: $.replicaSamples, shortfall: $.shortfall, failedPods: $.failedPods, restarts: $.restarts, lastTerminatedReason: $.lastTerminatedReason, peakCpuLimitPct: $.peakCpuLimitPct, peakMemoryLimitPct: $.peakMemoryLimitPct, saturation: $.saturation, cpuUsage: $.cpuUsage, })) .where(($) => [opts.computeTypes?.length ? $.podCount.gt(0) : undefined]) .orderBy( ["shortfall", "desc"], ["failedPods", "desc"], ["restarts", "desc"], ["saturation", "desc"], ["workloadName", "asc"], ) .limit(opts.limit ?? 200) .offset(opts.offset ?? 0) .format("JSON") } export interface WorkloadDetailSummaryOpts { kind: WorkloadKind workloadName: string namespace?: string } export interface WorkloadDetailSummaryOutput { readonly workloadName: string readonly kind: string readonly namespace: string readonly podCount: number readonly sourceId: string readonly firstSeen: DateTime.Utc readonly lastSeen: DateTime.Utc readonly avgCpuLimitPct: number readonly avgMemoryLimitPct: number readonly avgCpuUsage: number } export function workloadDetailSummaryQuery(opts: WorkloadDetailSummaryOpts) { const attrKey = workloadAttrKey(opts.kind) return from(MetricsGauge) .select(($) => ({ workloadName: $.ResourceAttributes.get(attrKey), namespace: CH.any_($.ResourceAttributes.get("k8s.namespace.name")), podCount: CH.uniq($.ResourceAttributes.get("k8s.pod.uid")), sourceId: CH.argMax($.ResourceAttributes.get("maple_source_id"), $.TimeUnix), firstSeen: CH.min_($.TimeUnix), lastSeen: CH.max_($.TimeUnix), avgCpuLimitPct: avgIfOrZero($.Value, $.MetricName.eq("k8s.pod.cpu_limit_utilization")), avgMemoryLimitPct: avgIfOrZero($.Value, $.MetricName.eq("k8s.pod.memory_limit_utilization")), avgCpuUsage: avgIfOrZero($.Value, $.MetricName.eq("k8s.pod.cpu.usage")), })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get(attrKey).eq(opts.workloadName), CH.when(opts.namespace, (v: string) => $.ResourceAttributes.get("k8s.namespace.name").eq(v)), $.MetricName.in_(...POD_METRIC_NAMES), ]) .groupBy("workloadName") .format("JSON") } export interface WorkloadGaugeTimeseriesOpts { kind: WorkloadKind workloadName: string namespace?: string metricName: string groupByPod?: boolean } export function workloadGaugeTimeseriesQuery(opts: WorkloadGaugeTimeseriesOpts) { const attrKey = workloadAttrKey(opts.kind) const q = from(MetricsGauge) .select(($) => ({ bucket: CH.toStartOfInterval($.TimeUnix, param.int("bucketSeconds")), attributeValue: opts.groupByPod ? $.ResourceAttributes.get("k8s.pod.name") : CH.lit(""), avgValue: CH.avg($.Value), })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get(attrKey).eq(opts.workloadName), CH.when(opts.namespace, (v: string) => $.ResourceAttributes.get("k8s.namespace.name").eq(v)), $.MetricName.eq(opts.metricName), ]) return (opts.groupByPod ? q.groupBy("bucket", "attributeValue") : q.groupBy("bucket")) .orderBy(["bucket", "asc"]) .format("JSON") } // K8s facets — distinct (name, count) pairs per ResourceAttribute key, used to // populate the SigNoz-style left filter sidebar. Each facet query is a UNION // of per-attribute SELECTs scoped to the rows that show up in the matching // list query (pods, nodes, or workloads), filtered by the same opts so the // facet counts reflect the *current* filtered set. export type PodFacetsOutput = FacetOutput const makePodFacet = (opts: ListPodsOpts, attrKey: string, facetType: string, perFacetLimit: number) => from(MetricsGauge) .select(($) => ({ name: facetAttrExpr($.ResourceAttributes, attrKey), count: CH.uniq($.ResourceAttributes.get("k8s.pod.uid")), facetType: CH.lit(facetType), })) .where(($) => [ ...podBaseConditions($, [POD_FACET_PROBE_METRIC]), ...podFilterConditions($, opts), facetAttrExpr($.ResourceAttributes, attrKey).neq(""), ]) .groupBy("name") .orderBy(["count", "desc"]) .limit(perFacetLimit) export function podFacetsQuery(opts: ListPodsOpts = {}): CHUnionQuery { return unionAll( makePodFacet(opts, "k8s.pod.name", "pod", 200), makePodFacet(opts, "k8s.namespace.name", "namespace", 100), makePodFacet(opts, "k8s.node.name", "node", 100), makePodFacet(opts, "k8s.cluster.name", "cluster", 50), makePodFacet(opts, "k8s.deployment.name", "deployment", 100), makePodFacet(opts, "k8s.statefulset.name", "statefulset", 100), makePodFacet(opts, "k8s.daemonset.name", "daemonset", 100), makePodFacet(opts, "k8s.job.name", "job", 100), makePodFacet(opts, "deployment.environment.name", "environment", 50), makePodFacet(opts, "eks.amazonaws.com/compute-type", "computeType", 10), ).format("JSON") } export type NodeFacetsOutput = FacetOutput const makeNodeFacet = (opts: ListNodesOpts, attrKey: string, facetType: string, perFacetLimit: number) => from(MetricsGauge) .select(($) => ({ name: facetAttrExpr($.ResourceAttributes, attrKey), count: CH.uniq($.ResourceAttributes.get("k8s.node.name")), facetType: CH.lit(facetType), })) .where(($) => [ ...nodeBaseConditions($, [NODE_FACET_PROBE_METRIC]), ...nodeFilterConditions($, opts), facetAttrExpr($.ResourceAttributes, attrKey).neq(""), ]) .groupBy("name") .orderBy(["count", "desc"]) .limit(perFacetLimit) export function nodeFacetsQuery(opts: ListNodesOpts = {}): CHUnionQuery { return unionAll( makeNodeFacet(opts, "k8s.node.name", "node", 200), makeNodeFacet(opts, "k8s.cluster.name", "cluster", 50), makeNodeFacet(opts, "deployment.environment.name", "environment", 50), ).format("JSON") } export type WorkloadFacetsOutput = FacetOutput const makeWorkloadFacet = ( opts: ListWorkloadsOpts, attrKey: string, facetType: string, perFacetLimit: number, ) => { const ownerKey = workloadAttrKey(opts.kind) return from(MetricsGauge) .select(($) => ({ name: facetAttrExpr($.ResourceAttributes, attrKey), count: CH.uniq($.ResourceAttributes.get(ownerKey)), facetType: CH.lit(facetType), })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.ResourceAttributes.get(ownerKey).neq(""), $.MetricName.in_(POD_FACET_PROBE_METRIC), ...workloadFilterConditions($, opts, ownerKey), facetAttrExpr($.ResourceAttributes, attrKey).neq(""), ]) .groupBy("name") .orderBy(["count", "desc"]) .limit(perFacetLimit) } export function workloadFacetsQuery(opts: ListWorkloadsOpts): CHUnionQuery { const ownerKey = workloadAttrKey(opts.kind) return unionAll( makeWorkloadFacet(opts, ownerKey, "workload", 200), makeWorkloadFacet(opts, "k8s.namespace.name", "namespace", 100), makeWorkloadFacet(opts, "k8s.cluster.name", "cluster", 50), makeWorkloadFacet(opts, "deployment.environment.name", "environment", 50), makeWorkloadFacet(opts, "eks.amazonaws.com/compute-type", "computeType", 10), ).format("JSON") } // Infrastructure presence — which surfaces this org actually reports // // The sidebar's Infrastructure section has seven children, and almost no org // runs all seven. To show only the ones an org has, something has to answer // "does this surface report anything?" on every page load — so the probe has // to be far cheaper than the list queries it gates. // // One branch per surface, each an existence check: a constant select list, a // single probe metric, a bounded window, `LIMIT 1`. Deliberately NOT an // aggregate — `count()` reads every matching row before the limit can trim its // one output row, while a non-aggregating branch stops at the first hit, which // is the whole point. One metric name rather than the surface's full set for // the same reason: every pod emits `k8s.pod.cpu.usage` and every container // `container.cpu.utilization`, so one name reaches the same population. // // A surface with nothing to report contributes NO row — presence is the row's // existence, not a count in it. The set of surfaces is known to the caller, so // there is nothing a zero row would say that an absent one does not. // // Callers pass a short window (an hour is plenty — this asks "is it reporting // now?", not "has it ever"). /** Sidebar surfaces gated by the probe. `hosts` is `/infra` itself. */ export type InfraSurface = "hosts" | "containers" | "k8sPods" | "k8sNodes" | "k8sWorkloads" export interface InfraPresenceOutput { readonly surface: string } /** * The three workload kinds share one branch: the sidebar has a single * "K8s Workloads" row, so which owner attribute is set doesn't change what it * shows — only whether *any* of them is. */ const WORKLOAD_OWNER_KEYS = ["k8s.deployment.name", "k8s.statefulset.name", "k8s.daemonset.name"] as const const presenceBranch = ( surface: InfraSurface, metricName: string, identity: ($: ColumnAccessor) => CH.Condition, ) => from(MetricsGauge) .select(() => ({ surface: CH.lit(surface) })) .where(($) => [ $.OrgId.eq(orgIdParam), $.TimeUnix.gte(param.dateTime("startTime")), $.TimeUnix.lte(param.dateTime("endTime")), $.MetricName.eq(metricName), identity($), ]) .limit(1) export function infraPresenceQuery(): CHUnionQuery { return unionAll( presenceBranch("hosts", "system.cpu.utilization", ($) => $.ResourceAttributes.get("host.name").neq(""), ), presenceBranch("containers", "container.cpu.utilization", ($) => $.ResourceAttributes.get("container.name").neq(""), ), presenceBranch("k8sPods", POD_FACET_PROBE_METRIC, ($) => $.ResourceAttributes.get("k8s.pod.name").neq(""), ), presenceBranch("k8sNodes", NODE_FACET_PROBE_METRIC, ($) => $.ResourceAttributes.get("k8s.node.name").neq(""), ), presenceBranch("k8sWorkloads", POD_FACET_PROBE_METRIC, ($) => WORKLOAD_OWNER_KEYS.map((key) => $.ResourceAttributes.get(key).neq("")).reduce((a, b) => a.or(b)), ), ).format("JSON") }