Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat(infrastructure-monitoring-k8s-and-hosts): add shared component for list/details (#10800)

Vinicius Lourençoc1a35808d973
diff --git a/frontend/src/api/infra/getHostAttributeKeys.ts b/frontend/src/api/infra/getHostAttributeKeys.ts
index ce39b79788..de66be23d1 100644
--- a/frontend/src/api/infra/getHostAttributeKeys.ts
+++ b/frontend/src/api/infra/getHostAttributeKeys.ts
@@ -2,7 +2,7 @@ import axios from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError, AxiosResponse } from 'axios';
import { baseAutoCompleteIdKeysOrder } from 'constants/queryBuilder';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
import { createIdFromObjectFields } from 'lib/createIdFromObjectFields';
import { ErrorResponse, SuccessResponse } from 'types/api';
import {
@@ -12,7 +12,7 @@ import {
export const getHostAttributeKeys = async (
searchText = '',
- entity: K8sCategory,
+ entity: InfraMonitoringEntity,
): Promise<SuccessResponse<IQueryAutocompleteResponse> | ErrorResponse> => {
try {
const response: AxiosResponse<{
diff --git a/frontend/src/api/infraMonitoring/getHostLists.ts b/frontend/src/api/infraMonitoring/getHostLists.ts
index 11fa8cb865..ab2d5a58f5 100644
--- a/frontend/src/api/infraMonitoring/getHostLists.ts
+++ b/frontend/src/api/infraMonitoring/getHostLists.ts
@@ -33,6 +33,8 @@ export interface HostData {
hostName: string;
active: boolean;
os: string;
+ /** Present when the list API returns grouped rows or extra resource attributes. */
+ meta?: Record<string, string>;
cpu: number;
cpuTimeSeries: TimeSeries;
memory: number;
diff --git a/frontend/src/api/infraMonitoring/getK8sNodesList.ts b/frontend/src/api/infraMonitoring/getK8sNodesList.ts
index 9d61ebb3cc..e69de29bb2 100644
--- a/frontend/src/api/infraMonitoring/getK8sNodesList.ts
+++ b/frontend/src/api/infraMonitoring/getK8sNodesList.ts
@@ -1,127 +0,0 @@
-import axios from 'api';
-import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
-import { AxiosError } from 'axios';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
-
-import { UnderscoreToDotMap } from '../utils';
-
-export interface K8sNodesListPayload {
- filters: TagFilter;
- groupBy?: BaseAutocompleteData[];
- offset?: number;
- limit?: number;
- orderBy?: {
- columnName: string;
- order: 'asc' | 'desc';
- };
-}
-
-export interface K8sNodesData {
- nodeUID: string;
- nodeCPUUsage: number;
- nodeCPUAllocatable: number;
- nodeMemoryUsage: number;
- nodeMemoryAllocatable: number;
- meta: {
- k8s_node_name: string;
- k8s_node_uid: string;
- k8s_cluster_name: string;
- };
-}
-
-export interface K8sNodesListResponse {
- status: string;
- data: {
- type: string;
- records: K8sNodesData[];
- groups: null;
- total: number;
- sentAnyHostMetricsData: boolean;
- isSendingK8SAgentMetrics: boolean;
- };
-}
-
-export const nodesMetaMap = [
- { dot: 'k8s.node.name', under: 'k8s_node_name' },
- { dot: 'k8s.node.uid', under: 'k8s_node_uid' },
- { dot: 'k8s.cluster.name', under: 'k8s_cluster_name' },
-] as const;
-
-export function mapNodesMeta(
- raw: Record<string, unknown>,
-): K8sNodesData['meta'] {
- const out: Record<string, unknown> = { ...raw };
- nodesMetaMap.forEach(({ dot, under }) => {
- if (dot in raw) {
- const v = raw[dot];
- out[under] = typeof v === 'string' ? v : raw[under];
- }
- });
- return out as K8sNodesData['meta'];
-}
-
-export const getK8sNodesList = async (
- props: K8sNodesListPayload,
- signal?: AbortSignal,
- headers?: Record<string, string>,
- dotMetricsEnabled = false,
-): Promise<SuccessResponse<K8sNodesListResponse> | ErrorResponse> => {
- try {
- const requestProps =
- dotMetricsEnabled && Array.isArray(props.filters?.items)
- ? {
- ...props,
- filters: {
- ...props.filters,
- items: props.filters.items.reduce<typeof props.filters.items>(
- (acc, item) => {
- if (item.value === undefined) {
- return acc;
- }
- if (
- item.key &&
- typeof item.key === 'object' &&
- 'key' in item.key &&
- typeof item.key.key === 'string'
- ) {
- const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
- acc.push({
- ...item,
- key: { ...item.key, key: mappedKey },
- });
- } else {
- acc.push(item);
- }
- return acc;
- },
- [] as typeof props.filters.items,
- ),
- },
- }
- : props;
-
- const response = await axios.post('/nodes/list', requestProps, {
- signal,
- headers,
- });
- const payload: K8sNodesListResponse = response.data;
-
- // one-liner to map dot→underscore
- payload.data.records = payload.data.records.map((record) => ({
- ...record,
- meta: mapNodesMeta(record.meta as Record<string, unknown>),
- }));
-
- return {
- statusCode: 200,
- error: null,
- message: 'Success',
- payload,
- params: requestProps,
- };
- } catch (error) {
- return ErrorResponseHandler(error as AxiosError);
- }
-};
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricDetail.interfaces.ts b/frontend/src/components/HostMetricsDetail/HostMetricDetail.interfaces.ts
deleted file mode 100644
index 65d3bf44d8..0000000000
--- a/frontend/src/components/HostMetricsDetail/HostMetricDetail.interfaces.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { HostData } from 'api/infraMonitoring/getHostLists';
-
-export type HostDetailProps = {
- host: HostData | null;
- isModalTimeSelection: boolean;
- onClose: () => void;
-};
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricTraces/HostMetricTraces.styles.scss b/frontend/src/components/HostMetricsDetail/HostMetricTraces/HostMetricTraces.styles.scss
deleted file mode 100644
index 1c11bf8daf..0000000000
--- a/frontend/src/components/HostMetricsDetail/HostMetricTraces/HostMetricTraces.styles.scss
+++ /dev/null
@@ -1,145 +0,0 @@
-.host-metric-traces {
- margin-top: 1rem;
-
- .host-metric-traces-header {
- display: flex;
- justify-content: space-between;
- margin-bottom: 1rem;
-
- gap: 8px;
- padding: 12px;
- border-radius: 3px;
- border: 1px solid var(--l1-border);
-
- .filter-section {
- flex: 1;
-
- .ant-select-selector {
- border-radius: 2px;
- border: 1px solid var(--l1-border) !important;
- background-color: var(--l3-background) !important;
-
- input {
- font-size: 12px;
- }
-
- .ant-tag .ant-typography {
- font-size: 12px;
- }
- }
- }
- }
-
- .host-metric-traces-table {
- .ant-table-content {
- overflow: hidden !important;
- }
-
- .ant-table {
- border-radius: 3px;
- border: 1px solid var(--l1-border);
-
- .ant-table-thead > tr > th {
- padding: 12px;
- font-weight: 500;
- font-size: 12px;
- line-height: 18px;
-
- background: color-mix(in srgb, var(--bg-robin-200) 1%, transparent);
- border-bottom: none;
-
- color: var(--l2-foreground);
- font-family: Inter;
- font-size: 11px;
- font-style: normal;
- font-weight: 600;
- line-height: 18px; /* 163.636% */
- letter-spacing: 0.44px;
- text-transform: uppercase;
-
- &::before {
- background-color: transparent;
- }
- }
-
- .ant-table-thead > tr > th:has(.hostname-column-header) {
- background: var(--l2-background);
- }
-
- .ant-table-cell {
- padding: 12px;
- font-size: 13px;
- line-height: 20px;
- color: var(--l1-foreground);
- background: color-mix(in srgb, var(--bg-robin-200) 1%, transparent);
- }
-
- .ant-table-cell:has(.hostname-column-value) {
- background: var(--l2-background);
- }
-
- .hostname-column-value {
- color: var(--l1-foreground);
- font-family: 'Geist Mono';
- font-style: normal;
- font-weight: 600;
- line-height: 20px; /* 142.857% */
- letter-spacing: -0.07px;
- }
-
- .status-cell {
- .active-tag {
- color: var(--bg-forest-500);
- padding: 4px 8px;
- border-radius: 4px;
- font-size: 12px;
- font-weight: 500;
- }
- }
-
- .progress-container {
- .ant-progress-bg {
- height: 8px !important;
- border-radius: 4px;
- }
- }
-
- .ant-table-tbody > tr:hover > td {
- background: color-mix(in srgb, var(--l1-foreground) 4%, transparent);
- }
-
- .ant-table-cell:first-child {
- text-align: justify;
- }
-
- .ant-table-cell:nth-child(2) {
- padding-left: 16px;
- padding-right: 16px;
- }
-
- .ant-table-cell:nth-child(n + 3) {
- padding-right: 24px;
- }
- .column-header-right {
- text-align: right;
- }
- .ant-table-tbody > tr > td {
- border-bottom: none;
- }
-
- .ant-table-thead
- > tr
- > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not([colspan])::before {
- background-color: transparent;
- }
-
- .ant-empty-normal {
- visibility: hidden;
- }
- }
-
- .ant-table-container::after {
- content: none;
- }
- }
-}
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricTraces/HostMetricTraces.tsx b/frontend/src/components/HostMetricsDetail/HostMetricTraces/HostMetricTraces.tsx
deleted file mode 100644
index e7a830f674..0000000000
--- a/frontend/src/components/HostMetricsDetail/HostMetricTraces/HostMetricTraces.tsx
+++ /dev/null
@@ -1,222 +0,0 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
-import { useQuery } from 'react-query';
-import logEvent from 'api/common/logEvent';
-import { ResizeTable } from 'components/ResizeTable';
-import { DEFAULT_ENTITY_VERSION } from 'constants/app';
-import { InfraMonitoringEvents } from 'constants/events';
-import { QueryParams } from 'constants/query';
-import EmptyLogsSearch from 'container/EmptyLogsSearch/EmptyLogsSearch';
-import NoLogs from 'container/NoLogs/NoLogs';
-import QueryBuilderSearch from 'container/QueryBuilder/filters/QueryBuilderSearch';
-import { ErrorText } from 'container/TimeSeriesView/styles';
-import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
-import {
- CustomTimeType,
- Time,
-} from 'container/TopNav/DateTimeSelectionV2/types';
-import TraceExplorerControls from 'container/TracesExplorer/Controls';
-import { PER_PAGE_OPTIONS } from 'container/TracesExplorer/ListView/configs';
-import { TracesLoading } from 'container/TracesExplorer/TraceLoading/TraceLoading';
-import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { Pagination } from 'hooks/queryPagination';
-import useUrlQueryData from 'hooks/useUrlQueryData';
-import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { DataSource } from 'types/common/queryBuilder';
-
-import { VIEWS } from '../constants';
-import { getHostTracesQueryPayload, selectedColumns } from './constants';
-import { getListColumns } from './utils';
-
-import './HostMetricTraces.styles.scss';
-
-interface Props {
- timeRange: {
- startTime: number;
- endTime: number;
- };
- isModalTimeSelection: boolean;
- handleTimeChange: (
- interval: Time | CustomTimeType,
- dateTimeRange?: [number, number],
- ) => void;
- handleChangeTracesFilters: (
- value: IBuilderQuery['filters'],
- view: VIEWS,
- ) => void;
- tracesFilters: IBuilderQuery['filters'];
- selectedInterval: Time;
-}
-
-function HostMetricTraces({
- timeRange,
- isModalTimeSelection,
- handleTimeChange,
- handleChangeTracesFilters,
- tracesFilters,
- selectedInterval,
-}: Props): JSX.Element {
- const [traces, setTraces] = useState<any[]>([]);
- const [offset] = useState<number>(0);
-
- const { currentQuery } = useQueryBuilder();
- const updatedCurrentQuery = useMemo(
- () => ({
- ...currentQuery,
- builder: {
- ...currentQuery.builder,
- queryData: [
- {
- ...currentQuery.builder.queryData[0],
- dataSource: DataSource.TRACES,
- aggregateOperator: 'noop',
- aggregateAttribute: {
- ...currentQuery.builder.queryData[0].aggregateAttribute,
- },
- filters: {
- items:
- tracesFilters?.items?.filter((item) => item.key?.key !== 'host.name') ||
- [],
- op: 'AND',
- },
- },
- ],
- },
- }),
- [currentQuery, tracesFilters?.items],
- );
-
- const query = updatedCurrentQuery?.builder?.queryData[0] || null;
-
- const { queryData: paginationQueryData } = useUrlQueryData<Pagination>(
- QueryParams.pagination,
- );
-
- const queryPayload = useMemo(
- () =>
- getHostTracesQueryPayload(
- timeRange.startTime,
- timeRange.endTime,
- paginationQueryData?.offset || offset,
- tracesFilters,
- ),
- [
- timeRange.startTime,
- timeRange.endTime,
- offset,
- tracesFilters,
- paginationQueryData,
- ],
- );
-
- const { data, isLoading, isFetching, isError } = useQuery({
- queryKey: [
- 'hostMetricTraces',
- timeRange.startTime,
- timeRange.endTime,
- offset,
- tracesFilters,
- DEFAULT_ENTITY_VERSION,
- paginationQueryData,
- ],
- queryFn: () => GetMetricQueryRange(queryPayload, DEFAULT_ENTITY_VERSION),
- enabled: !!queryPayload,
- });
-
- const traceListColumns = getListColumns(selectedColumns);
-
- useEffect(() => {
- if (data?.payload?.data?.newResult?.data?.result) {
- const currentData = data.payload.data.newResult.data.result;
- if (currentData.length > 0 && currentData[0].list) {
- if (offset === 0) {
- setTraces(currentData[0].list ?? []);
- } else {
- setTraces((prev) => [...prev, ...(currentData[0].list ?? [])]);
- }
- }
- }
- }, [data, offset]);
-
- const isDataEmpty =
- !isLoading && !isFetching && !isError && traces.length === 0;
- const hasAdditionalFilters =
- tracesFilters?.items && tracesFilters?.items?.length > 1;
-
- const totalCount =
- data?.payload?.data?.newResult?.data?.result?.[0]?.list?.length || 0;
-
- const handleRowClick = useCallback(() => {
- logEvent(InfraMonitoringEvents.ItemClicked, {
- entity: InfraMonitoringEvents.HostEntity,
- view: InfraMonitoringEvents.TracesView,
- });
- }, []);
-
- return (
- <div className="host-metric-traces">
- <div className="host-metric-traces-header">
- <div className="filter-section">
- {query && (
- <QueryBuilderSearch
- query={query as IBuilderQuery}
- onChange={(value): void =>
- handleChangeTracesFilters(value, VIEWS.TRACES)
- }
- disableNavigationShortcuts
- />
- )}
- </div>
- <div className="datetime-section">
- <DateTimeSelectionV2
- showAutoRefresh
- showRefreshText={false}
- hideShareModal
- isModalTimeSelection={isModalTimeSelection}
- onTimeChange={handleTimeChange}
- defaultRelativeTime="5m"
- modalSelectedInterval={selectedInterval}
- modalInitialStartTime={timeRange.startTime * 1000}
- modalInitialEndTime={timeRange.endTime * 1000}
- />
- </div>
- </div>
-
- {isError && <ErrorText>{data?.error || 'Something went wrong'}</ErrorText>}
-
- {isLoading && traces.length === 0 && <TracesLoading />}
-
- {isDataEmpty && !hasAdditionalFilters && (
- <NoLogs dataSource={DataSource.TRACES} />
- )}
-
- {isDataEmpty && hasAdditionalFilters && (
- <EmptyLogsSearch dataSource={DataSource.TRACES} panelType="LIST" />
- )}
-
- {!isError && traces.length > 0 && (
- <div className="host-metric-traces-table">
- <TraceExplorerControls
- isLoading={isFetching && traces.length === 0}
- totalCount={totalCount}
- perPageOptions={PER_PAGE_OPTIONS}
- showSizeChanger={false}
- />
- <ResizeTable
- tableLayout="fixed"
- pagination={false}
- scroll={{ x: true }}
- loading={isFetching && traces.length === 0}
- dataSource={traces}
- columns={traceListColumns}
- onRow={(): Record<string, unknown> => ({
- onClick: (): void => handleRowClick(),
- })}
- />
- </div>
- )}
- </div>
- );
-}
-
-export default HostMetricTraces;
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricTraces/constants.ts b/frontend/src/components/HostMetricsDetail/HostMetricTraces/constants.ts
deleted file mode 100644
index 91df21d98a..0000000000
--- a/frontend/src/components/HostMetricsDetail/HostMetricTraces/constants.ts
+++ /dev/null
@@ -1,183 +0,0 @@
-import { PANEL_TYPES } from 'constants/queryBuilder';
-import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
-import {
- BaseAutocompleteData,
- DataTypes,
-} from 'types/api/queryBuilder/queryAutocompleteResponse';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { EQueryType } from 'types/common/dashboard';
-import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
-import { nanoToMilli } from 'utils/timeUtils';
-
-export const columns = [
- {
- dataIndex: 'timestamp',
- key: 'timestamp',
- title: 'Timestamp',
- width: 200,
- render: (timestamp: string): string => new Date(timestamp).toLocaleString(),
- },
- {
- title: 'Service Name',
- dataIndex: ['data', 'serviceName'],
- key: 'serviceName-string-tag',
- width: 150,
- },
- {
- title: 'Name',
- dataIndex: ['data', 'name'],
- key: 'name-string-tag',
- width: 145,
- },
- {
- title: 'Duration',
- dataIndex: ['data', 'durationNano'],
- key: 'durationNano-float64-tag',
- width: 145,
- render: (duration: number): string => `${nanoToMilli(duration)}ms`,
- },
- {
- title: 'HTTP Method',
- dataIndex: ['data', 'httpMethod'],
- key: 'httpMethod-string-tag',
- width: 145,
- },
- {
- title: 'Status Code',
- dataIndex: ['data', 'responseStatusCode'],
- key: 'responseStatusCode-string-tag',
- width: 145,
- },
-];
-
-export const selectedColumns: BaseAutocompleteData[] = [
- {
- key: 'timestamp',
- dataType: DataTypes.String,
- type: 'tag',
- },
- {
- key: 'serviceName',
- dataType: DataTypes.String,
- type: 'tag',
- },
- {
- key: 'name',
- dataType: DataTypes.String,
- type: 'tag',
- },
- {
- key: 'durationNano',
- dataType: DataTypes.Float64,
- type: 'tag',
- },
- {
- key: 'httpMethod',
- dataType: DataTypes.String,
- type: 'tag',
- },
- {
- key: 'responseStatusCode',
- dataType: DataTypes.String,
- type: 'tag',
- },
-];
-
-export const getHostTracesQueryPayload = (
- start: number,
- end: number,
- offset = 0,
- filters: IBuilderQuery['filters'],
-): GetQueryResultsProps => ({
- query: {
- promql: [],
- clickhouse_sql: [],
- builder: {
- queryData: [
- {
- dataSource: DataSource.TRACES,
- queryName: 'A',
- aggregateOperator: 'noop',
- aggregateAttribute: {
- id: '------false',
- dataType: DataTypes.EMPTY,
- key: '',
- type: '',
- },
- timeAggregation: 'rate',
- spaceAggregation: 'sum',
- functions: [],
- filters,
- expression: 'A',
- disabled: false,
- stepInterval: 60,
- having: [],
- limit: null,
- orderBy: [
- {
- columnName: 'timestamp',
- order: 'desc',
- },
- ],
- groupBy: [],
- legend: '',
- reduceTo: ReduceOperators.AVG,
- },
- ],
- queryFormulas: [],
- queryTraceOperator: [],
- },
- id: '572f1d91-6ac0-46c0-b726-c21488b34434',
- queryType: EQueryType.QUERY_BUILDER,
- },
- graphType: PANEL_TYPES.LIST,
- selectedTime: 'GLOBAL_TIME',
- start,
- end,
- params: {
- dataSource: DataSource.TRACES,
- },
- tableParams: {
- pagination: {
- limit: 10,
- offset,
- },
- selectColumns: [
- {
- key: 'serviceName',
- dataType: 'string',
- type: 'tag',
- id: 'serviceName--string--tag--true',
- isIndexed: false,
- },
- {
- key: 'name',
- dataType: 'string',
- type: 'tag',
- id: 'name--string--tag--true',
- isIndexed: false,
- },
- {
- key: 'durationNano',
- dataType: 'float64',
- type: 'tag',
- id: 'durationNano--float64--tag--true',
- isIndexed: false,
- },
- {
- key: 'httpMethod',
- dataType: 'string',
- type: 'tag',
- id: 'httpMethod--string--tag--true',
- isIndexed: false,
- },
- {
- key: 'responseStatusCode',
- dataType: 'string',
- type: 'tag',
- id: 'responseStatusCode--string--tag--true',
- isIndexed: false,
- },
- ],
- },
-});
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricsDetail.styles.scss b/frontend/src/components/HostMetricsDetail/HostMetricsDetail.styles.scss
deleted file mode 100644
index 6d073c2a2b..0000000000
--- a/frontend/src/components/HostMetricsDetail/HostMetricsDetail.styles.scss
+++ /dev/null
@@ -1,176 +0,0 @@
-.host-detail-drawer {
- border-left: 1px solid var(--l1-border);
- background: var(--l2-background);
- box-shadow: -4px 10px 16px 2px rgba(0, 0, 0, 0.2);
-
- .ant-drawer-header {
- padding: 8px 16px;
- border-bottom: none;
-
- align-items: stretch;
-
- border-bottom: 1px solid var(--l1-border);
- background: var(--l2-background);
- }
-
- .ant-drawer-close {
- margin-inline-end: 0px;
- }
-
- .ant-drawer-body {
- display: flex;
- flex-direction: column;
- padding: 16px;
- }
-
- .title {
- color: var(--l2-foreground);
- font-family: 'Geist Mono';
- font-size: 14px;
- font-style: normal;
- font-weight: 500;
- line-height: 20px; /* 142.857% */
- letter-spacing: -0.07px;
- }
-
- .radio-button {
- display: flex;
- align-items: center;
- justify-content: center;
- padding-top: var(--padding-1);
- border: 1px solid var(--l1-border);
- background: var(--l3-background);
- box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
- }
-
- .host-detail-drawer__host {
- .host-details-grid {
- .labels-row,
- .values-row {
- display: grid;
- grid-template-columns: 1fr 1.5fr 1.5fr 1.5fr;
- gap: 30px;
- align-items: center;
- }
-
- .labels-row {
- margin-bottom: 8px;
- }
-
- .host-details-metadata-label {
- color: var(--l2-foreground);
- font-family: Inter;
- font-size: 11px;
- font-style: normal;
- font-weight: 500;
- line-height: 18px; /* 163.636% */
- letter-spacing: 0.44px;
- text-transform: uppercase;
- }
-
- .status-tag {
- margin: 0;
-
- &.active {
- color: var(--success-500);
- background: var(--success-100);
- border-color: var(--success-500);
- }
-
- &.inactive {
- color: var(--error-500);
- background: var(--error-100);
- border-color: var(--error-500);
- }
- }
-
- .progress-container {
- width: 158px;
- .ant-progress {
- margin: 0;
-
- .ant-progress-text {
- font-weight: 600;
- }
- }
- }
-
- .ant-card {
- &.ant-card-bordered {
- border: 1px solid var(--l1-border) !important;
- }
- }
- }
- }
-
- .tabs-and-search {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin: 16px 0;
-
- .action-btn {
- border-radius: 2px;
- border: 1px solid var(--l1-border);
- background: var(--l3-background);
- box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
- display: flex;
- align-items: center;
- justify-content: center;
- }
- }
-
- .views-tabs-container {
- margin-top: 1.5rem;
- display: flex;
- justify-content: space-between;
- align-items: center;
-
- .views-tabs {
- color: var(--l2-foreground);
-
- .view-title {
- display: flex;
- gap: var(--margin-2);
- align-items: center;
- justify-content: center;
- font-size: var(--font-size-xs);
- font-style: normal;
- font-weight: var(--font-weight-normal);
- }
-
- .tab {
- border: 1px solid var(--l1-border);
- width: 114px;
- }
-
- .tab::before {
- background: var(--l1-border);
- }
-
- .selected_view {
- background: var(--l3-background);
- color: var(--l1-foreground);
- border: 1px solid var(--l1-border);
- }
-
- .selected_view::before {
- background: var(--l1-border);
- }
- }
-
- .compass-button {
- width: 30px;
- height: 30px;
-
- border-radius: 2px;
- border: 1px solid var(--l1-border);
- background: var(--l3-background);
- box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
- }
- }
-
- .ant-drawer-close {
- padding: 0px;
- }
-}
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricsDetails.tsx b/frontend/src/components/HostMetricsDetail/HostMetricsDetails.tsx
deleted file mode 100644
index d929a1022c..0000000000
--- a/frontend/src/components/HostMetricsDetail/HostMetricsDetails.tsx
+++ /dev/null
@@ -1,595 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { useSearchParams } from 'react-router-dom-v5-compat';
-import { Color, Spacing } from '@signozhq/design-tokens';
-import {
- Button,
- Divider,
- Drawer,
- Progress,
- Radio,
- Tag,
- Typography,
-} from 'antd';
-import type { RadioChangeEvent } from 'antd/lib';
-import logEvent from 'api/common/logEvent';
-import { InfraMonitoringEvents } from 'constants/events';
-import { QueryParams } from 'constants/query';
-import {
- initialQueryBuilderFormValuesMap,
- initialQueryState,
-} from 'constants/queryBuilder';
-import ROUTES from 'constants/routes';
-import { getFiltersFromParams } from 'container/InfraMonitoringK8s/commonUtils';
-import { INFRA_MONITORING_K8S_PARAMS_KEYS } from 'container/InfraMonitoringK8s/constants';
-import {
- CustomTimeType,
- Time,
-} from 'container/TopNav/DateTimeSelectionV2/types';
-import { useIsDarkMode } from 'hooks/useDarkMode';
-import useUrlQuery from 'hooks/useUrlQuery';
-import GetMinMax from 'lib/getMinMax';
-import {
- BarChart2,
- ChevronsLeftRight,
- Compass,
- DraftingCompass,
- Package2,
- ScrollText,
- X,
-} from 'lucide-react';
-import { AppState } from 'store/reducers';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import {
- IBuilderQuery,
- TagFilterItem,
-} from 'types/api/queryBuilder/queryBuilderData';
-import {
- LogsAggregatorOperator,
- TracesAggregatorOperator,
-} from 'types/common/queryBuilder';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { v4 as uuidv4 } from 'uuid';
-
-import { VIEW_TYPES, VIEWS } from './constants';
-import Containers from './Containers/Containers';
-import { HostDetailProps } from './HostMetricDetail.interfaces';
-import HostMetricLogsDetailedView from './HostMetricsLogs/HostMetricLogsDetailedView';
-import HostMetricTraces from './HostMetricTraces/HostMetricTraces';
-import Metrics from './Metrics/Metrics';
-import Processes from './Processes/Processes';
-
-import './HostMetricsDetail.styles.scss';
-// eslint-disable-next-line sonarjs/cognitive-complexity
-function HostMetricsDetails({
- host,
- onClose,
- isModalTimeSelection,
-}: HostDetailProps): JSX.Element {
- const { maxTime, minTime, selectedTime } = useSelector<
- AppState,
- GlobalReducer
- >((state) => state.globalTime);
- const [searchParams, setSearchParams] = useSearchParams();
-
- const startMs = useMemo(() => Math.floor(Number(minTime) / 1000000000), [
- minTime,
- ]);
- const endMs = useMemo(() => Math.floor(Number(maxTime) / 1000000000), [
- maxTime,
- ]);
-
- const urlQuery = useUrlQuery();
-
- const [modalTimeRange, setModalTimeRange] = useState(() => ({
- startTime: startMs,
- endTime: endMs,
- }));
-
- const lastSelectedInterval = useRef<Time | null>(null);
-
- const [selectedInterval, setSelectedInterval] = useState<Time>(
- lastSelectedInterval.current
- ? lastSelectedInterval.current
- : (selectedTime as Time),
- );
-
- const [selectedView, setSelectedView] = useState<VIEWS>(
- (searchParams.get('view') as VIEWS) || VIEWS.METRICS,
- );
- const isDarkMode = useIsDarkMode();
-
- const initialFilters = useMemo(() => {
- const urlView = searchParams.get(INFRA_MONITORING_K8S_PARAMS_KEYS.VIEW);
- const queryKey =
- urlView === VIEW_TYPES.LOGS
- ? INFRA_MONITORING_K8S_PARAMS_KEYS.LOG_FILTERS
- : INFRA_MONITORING_K8S_PARAMS_KEYS.TRACES_FILTERS;
- const filters = getFiltersFromParams(searchParams, queryKey);
- if (filters) {
- return filters;
- }
-
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: 'host.name',
- dataType: DataTypes.String,
- type: 'resource',
- id: 'host.name--string--resource--false',
- },
- op: '=',
- value: host?.hostName || '',
- },
- ],
- };
- }, [host?.hostName, searchParams]);
-
- const [logFilters, setLogFilters] = useState<IBuilderQuery['filters']>(
- initialFilters,
- );
-
- const [tracesFilters, setTracesFilters] = useState<IBuilderQuery['filters']>(
- initialFilters,
- );
-
- useEffect(() => {
- if (host) {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.HostEntity,
- page: InfraMonitoringEvents.DetailedPage,
- });
- }
- }, [host]);
-
- useEffect(() => {
- setLogFilters(initialFilters);
- setTracesFilters(initialFilters);
- }, [initialFilters]);
-
- useEffect(() => {
- const currentSelectedInterval = lastSelectedInterval.current || selectedTime;
- setSelectedInterval(currentSelectedInterval as Time);
-
- if (currentSelectedInterval !== 'custom') {
- const { maxTime, minTime } = GetMinMax(currentSelectedInterval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- }, [selectedTime, minTime, maxTime]);
-
- const handleTabChange = (e: RadioChangeEvent): void => {
- setSelectedView(e.target.value);
- if (host?.hostName) {
- setSelectedView(e.target.value);
- setSearchParams({
- ...Object.fromEntries(searchParams.entries()),
- [INFRA_MONITORING_K8S_PARAMS_KEYS.VIEW]: e.target.value,
- [INFRA_MONITORING_K8S_PARAMS_KEYS.LOG_FILTERS]: JSON.stringify(null),
- [INFRA_MONITORING_K8S_PARAMS_KEYS.TRACES_FILTERS]: JSON.stringify(null),
- });
- }
- logEvent(InfraMonitoringEvents.TabChanged, {
- entity: InfraMonitoringEvents.HostEntity,
- view: e.target.value,
- });
- };
-
- const handleTimeChange = useCallback(
- (interval: Time | CustomTimeType, dateTimeRange?: [number, number]): void => {
- lastSelectedInterval.current = interval as Time;
- setSelectedInterval(interval as Time);
-
- if (interval === 'custom' && dateTimeRange) {
- setModalTimeRange({
- startTime: Math.floor(dateTimeRange[0] / 1000),
- endTime: Math.floor(dateTimeRange[1] / 1000),
- });
- } else {
- const { maxTime, minTime } = GetMinMax(interval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
-
- logEvent(InfraMonitoringEvents.TimeUpdated, {
- entity: InfraMonitoringEvents.HostEntity,
- interval,
- page: InfraMonitoringEvents.DetailedPage,
- });
- },
- [],
- );
-
- const handleChangeLogFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogFilters((prevFilters) => {
- const hostNameFilter = prevFilters?.items?.find(
- (item) => item.key?.key === 'host.name',
- );
- const paginationFilter = value?.items?.find(
- (item) => item.key?.key === 'id',
- );
- const newFilters = value?.items?.filter(
- (item) => item.key?.key !== 'id' && item.key?.key !== 'host.name',
- );
-
- if (newFilters && newFilters?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.HostEntity,
- view: InfraMonitoringEvents.LogsView,
- page: InfraMonitoringEvents.DetailedPage,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: [
- hostNameFilter,
- ...(newFilters || []),
- ...(paginationFilter ? [paginationFilter] : []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- };
-
- setSearchParams({
- ...Object.fromEntries(searchParams.entries()),
- [INFRA_MONITORING_K8S_PARAMS_KEYS.LOG_FILTERS]: JSON.stringify(
- updatedFilters,
- ),
- [INFRA_MONITORING_K8S_PARAMS_KEYS.VIEW]: view,
- });
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeTracesFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setTracesFilters((prevFilters) => {
- const hostNameFilter = prevFilters?.items?.find(
- (item) => item.key?.key === 'host.name',
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.HostEntity,
- view: InfraMonitoringEvents.TracesView,
- page: InfraMonitoringEvents.DetailedPage,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: [
- hostNameFilter,
- ...(value?.items?.filter((item) => item.key?.key !== 'host.name') || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- };
-
- setSearchParams({
- ...Object.fromEntries(searchParams.entries()),
- [INFRA_MONITORING_K8S_PARAMS_KEYS.TRACES_FILTERS]: JSON.stringify(
- updatedFilters,
- ),
- [INFRA_MONITORING_K8S_PARAMS_KEYS.VIEW]: view,
- });
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleExplorePagesRedirect = (): void => {
- if (selectedInterval !== 'custom') {
- urlQuery.set(QueryParams.relativeTime, selectedInterval);
- } else {
- urlQuery.delete(QueryParams.relativeTime);
- urlQuery.set(QueryParams.startTime, modalTimeRange.startTime.toString());
- urlQuery.set(QueryParams.endTime, modalTimeRange.endTime.toString());
- }
-
- logEvent(InfraMonitoringEvents.ExploreClicked, {
- view: selectedView,
- entity: InfraMonitoringEvents.HostEntity,
- page: InfraMonitoringEvents.DetailedPage,
- });
-
- if (selectedView === VIEW_TYPES.LOGS) {
- const filtersWithoutPagination = {
- ...logFilters,
- items: logFilters?.items?.filter((item) => item.key?.key !== 'id') || [],
- };
-
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.logs,
- aggregateOperator: LogsAggregatorOperator.NOOP,
- filters: filtersWithoutPagination,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.LOGS_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- } else if (selectedView === VIEW_TYPES.TRACES) {
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.traces,
- aggregateOperator: TracesAggregatorOperator.NOOP,
- filters: tracesFilters,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.TRACES_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- }
- };
-
- const handleClose = (): void => {
- setSelectedInterval(selectedTime as Time);
- lastSelectedInterval.current = null;
- setSearchParams({});
-
- if (selectedTime !== 'custom') {
- const { maxTime, minTime } = GetMinMax(selectedTime);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- setSelectedView(VIEW_TYPES.METRICS);
- onClose();
- };
-
- return (
- <Drawer
- width="70%"
- title={
- <>
- <Divider type="vertical" />
- <Typography.Text className="title">{host?.hostName}</Typography.Text>
- </>
- }
- placement="right"
- onClose={handleClose}
- open={!!host}
- style={{
- overscrollBehavior: 'contain',
- background: isDarkMode ? Color.BG_INK_400 : Color.BG_VANILLA_100,
- }}
- className="host-detail-drawer"
- destroyOnClose
- closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
- >
- {host && (
- <>
- <div className="host-detail-drawer__host">
- <div className="host-details-grid">
- <div className="labels-row">
- <Typography.Text
- type="secondary"
- className="host-details-metadata-label"
- >
- STATUS
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="host-details-metadata-label"
- >
- OPERATING SYSTEM
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="host-details-metadata-label"
- >
- CPU USAGE
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="host-details-metadata-label"
- >
- MEMORY USAGE
- </Typography.Text>
- </div>
-
- <div className="values-row">
- <Tag
- bordered
- className={`infra-monitoring-tags ${
- host.active ? 'active' : 'inactive'
- }`}
- >
- {host.active ? 'ACTIVE' : 'INACTIVE'}
- </Tag>
- {host.os ? (
- <Tag className="infra-monitoring-tags" bordered>
- {host.os}
- </Tag>
- ) : (
- <Typography.Text>-</Typography.Text>
- )}
- <div className="progress-container">
- <Progress
- percent={Number((host.cpu * 100).toFixed(1))}
- size="small"
- strokeColor={((): string => {
- const cpuPercent = Number((host.cpu * 100).toFixed(1));
- if (cpuPercent >= 90) {
- return Color.BG_SAKURA_500;
- }
- if (cpuPercent >= 60) {
- return Color.BG_AMBER_500;
- }
- return Color.BG_FOREST_500;
- })()}
- className="progress-bar"
- />
- </div>
- <div className="progress-container">
- <Progress
- percent={Number((host.memory * 100).toFixed(1))}
- size="small"
- strokeColor={((): string => {
- const memoryPercent = Number((host.memory * 100).toFixed(1));
- if (memoryPercent >= 90) {
- return Color.BG_CHERRY_500;
- }
- if (memoryPercent >= 60) {
- return Color.BG_AMBER_500;
- }
- return Color.BG_FOREST_500;
- })()}
- className="progress-bar"
- />
- </div>
- </div>
- </div>
- </div>
-
- <div className="views-tabs-container">
- <Radio.Group
- className="views-tabs"
- onChange={handleTabChange}
- value={selectedView}
- >
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.METRICS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.METRICS}
- >
- <div className="view-title">
- <BarChart2 size={14} />
- Metrics
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.LOGS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.LOGS}
- >
- <div className="view-title">
- <ScrollText size={14} />
- Logs
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.TRACES ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.TRACES}
- >
- <div className="view-title">
- <DraftingCompass size={14} />
- Traces
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.CONTAINERS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.CONTAINERS}
- >
- <div className="view-title">
- <Package2 size={14} />
- Containers
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.PROCESSES ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.PROCESSES}
- >
- <div className="view-title">
- <ChevronsLeftRight size={14} />
- Processes
- </div>
- </Radio.Button>
- </Radio.Group>
-
- {(selectedView === VIEW_TYPES.LOGS ||
- selectedView === VIEW_TYPES.TRACES) && (
- <Button
- icon={<Compass size={18} />}
- className="compass-button"
- onClick={handleExplorePagesRedirect}
- />
- )}
- </div>
-
- {selectedView === VIEW_TYPES.METRICS && (
- <Metrics
- selectedInterval={selectedInterval}
- hostName={host.hostName}
- timeRange={modalTimeRange}
- handleTimeChange={handleTimeChange}
- isModalTimeSelection={isModalTimeSelection}
- />
- )}
- {selectedView === VIEW_TYPES.LOGS && (
- <HostMetricLogsDetailedView
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeLogFilters={handleChangeLogFilters}
- logFilters={logFilters}
- selectedInterval={selectedInterval}
- />
- )}
- {selectedView === VIEW_TYPES.TRACES && (
- <HostMetricTraces
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeTracesFilters={handleChangeTracesFilters}
- tracesFilters={tracesFilters}
- selectedInterval={selectedInterval}
- />
- )}
-
- {selectedView === VIEW_TYPES.CONTAINERS && <Containers />}
- {selectedView === VIEW_TYPES.PROCESSES && <Processes />}
- </>
- )}
- </Drawer>
- );
-}
-
-export default HostMetricsDetails;
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricLogs.styles.scss b/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricLogs.styles.scss
deleted file mode 100644
index 47101fce43..0000000000
--- a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricLogs.styles.scss
+++ /dev/null
@@ -1,119 +0,0 @@
-.host-metrics-logs-container {
- margin-top: 1rem;
-
- .filter-section {
- flex: 1;
-
- .ant-select-selector {
- border-radius: 2px;
- border: 1px solid var(--l1-border) !important;
-
- input {
- font-size: 12px;
- }
-
- .ant-tag .ant-typography {
- font-size: 12px;
- }
- }
- }
-
- .host-metrics-logs-header {
- display: flex;
- justify-content: space-between;
- gap: 8px;
-
- padding: 12px;
- border-radius: 3px;
- border: 1px solid var(--l1-border);
- }
-
- .host-metrics-logs {
- margin-top: 1rem;
-
- .virtuoso-list {
- overflow-y: hidden !important;
-
- &::-webkit-scrollbar {
- width: 0.3rem;
- height: 0.3rem;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background: var(--l1-border);
- }
-
- &::-webkit-scrollbar-thumb:hover {
- background: var(--l1-border);
- }
-
- .ant-row {
- width: fit-content;
- }
- }
-
- .skeleton-container {
- height: 100%;
- padding: 16px;
- }
- }
-}
-
-.host-metrics-logs-list-container {
- flex: 1;
- height: calc(100vh - 272px) !important;
- display: flex;
- height: 100%;
-
- .raw-log-content {
- width: 100%;
- text-wrap: inherit;
- word-wrap: break-word;
- }
-}
-
-.host-metrics-logs-list-card {
- width: 100%;
- margin-top: 12px;
-
- .ant-card-body {
- padding: 0;
-
- height: 100%;
- width: 100%;
- }
-}
-
-.logs-loading-skeleton {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: 8px;
- padding: 8px 0;
-
- .ant-skeleton-input-sm {
- height: 18px;
- }
-}
-
-.no-logs-found {
- height: 50vh;
- width: 100%;
- display: flex;
- justify-content: center;
- align-items: center;
-
- padding: 24px;
- box-sizing: border-box;
-
- .ant-typography {
- display: flex;
- align-items: center;
- gap: 16px;
- }
-}
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricLogsDetailedView.tsx b/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricLogsDetailedView.tsx
deleted file mode 100644
index da165dd0c8..0000000000
--- a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricLogsDetailedView.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-import { useMemo } from 'react';
-import QueryBuilderSearch from 'container/QueryBuilder/filters/QueryBuilderSearch';
-import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
-import {
- CustomTimeType,
- Time,
-} from 'container/TopNav/DateTimeSelectionV2/types';
-import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { DataSource } from 'types/common/queryBuilder';
-
-import { VIEWS } from '../constants';
-import HostMetricsLogs from './HostMetricsLogs';
-
-import './HostMetricLogs.styles.scss';
-
-interface Props {
- timeRange: {
- startTime: number;
- endTime: number;
- };
- isModalTimeSelection: boolean;
- handleTimeChange: (
- interval: Time | CustomTimeType,
- dateTimeRange?: [number, number],
- ) => void;
- handleChangeLogFilters: (value: IBuilderQuery['filters'], view: VIEWS) => void;
- logFilters: IBuilderQuery['filters'];
- selectedInterval: Time;
-}
-
-function HostMetricLogsDetailedView({
- timeRange,
- isModalTimeSelection,
- handleTimeChange,
- handleChangeLogFilters,
- logFilters,
- selectedInterval,
-}: Props): JSX.Element {
- const { currentQuery } = useQueryBuilder();
- const updatedCurrentQuery = useMemo(
- () => ({
- ...currentQuery,
- builder: {
- ...currentQuery.builder,
- queryData: [
- {
- ...currentQuery.builder.queryData[0],
- dataSource: DataSource.LOGS,
- aggregateOperator: 'noop',
- aggregateAttribute: {
- ...currentQuery.builder.queryData[0].aggregateAttribute,
- },
- filters: {
- items:
- logFilters?.items?.filter((item) => item.key?.key !== 'host.name') ||
- [],
- op: 'AND',
- },
- },
- ],
- },
- }),
- [currentQuery, logFilters?.items],
- );
-
- const query = updatedCurrentQuery?.builder?.queryData[0] || null;
-
- return (
- <div className="host-metrics-logs-container">
- <div className="host-metrics-logs-header">
- <div className="filter-section">
- {query && (
- <QueryBuilderSearch
- query={query as IBuilderQuery}
- onChange={(value): void => handleChangeLogFilters(value, VIEWS.LOGS)}
- disableNavigationShortcuts
- />
- )}
- </div>
- <div className="datetime-section">
- <DateTimeSelectionV2
- showAutoRefresh
- showRefreshText={false}
- hideShareModal
- isModalTimeSelection={isModalTimeSelection}
- onTimeChange={handleTimeChange}
- defaultRelativeTime="5m"
- modalSelectedInterval={selectedInterval}
- modalInitialStartTime={timeRange.startTime * 1000}
- modalInitialEndTime={timeRange.endTime * 1000}
- />
- </div>
- </div>
- <HostMetricsLogs timeRange={timeRange} filters={logFilters} />
- </div>
- );
-}
-
-export default HostMetricLogsDetailedView;
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricsLogs.tsx b/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricsLogs.tsx
deleted file mode 100644
index 3dafe97656..0000000000
--- a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricsLogs.tsx
+++ /dev/null
@@ -1,187 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef } from 'react';
-import { useQuery } from 'react-query';
-import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
-import { Card } from 'antd';
-import LogDetail from 'components/LogDetail';
-import RawLogView from 'components/Logs/RawLogView';
-import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
-import { DEFAULT_ENTITY_VERSION } from 'constants/app';
-import LogsError from 'container/LogsError/LogsError';
-import { LogsLoading } from 'container/LogsLoading/LogsLoading';
-import { FontSize } from 'container/OptionsMenu/types';
-import { useHandleLogsPagination } from 'hooks/infraMonitoring/useHandleLogsPagination';
-import useLogDetailHandlers from 'hooks/logs/useLogDetailHandlers';
-import useScrollToLog from 'hooks/logs/useScrollToLog';
-import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
-import { ILog } from 'types/api/logs/log';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-
-import { getHostLogsQueryPayload } from './constants';
-import NoLogsContainer from './NoLogsContainer';
-
-import './HostMetricLogs.styles.scss';
-
-interface Props {
- timeRange: {
- startTime: number;
- endTime: number;
- };
- filters: IBuilderQuery['filters'];
-}
-
-function HostMetricsLogs({ timeRange, filters }: Props): JSX.Element {
- const virtuosoRef = useRef<VirtuosoHandle>(null);
- const {
- activeLog,
- onAddToQuery,
- selectedTab,
- handleSetActiveLog,
- handleCloseLogDetail,
- } = useLogDetailHandlers();
-
- const basePayload = getHostLogsQueryPayload(
- timeRange.startTime,
- timeRange.endTime,
- filters,
- );
- const {
- logs,
- hasReachedEndOfLogs,
- isPaginating,
- currentPage,
- setIsPaginating,
- handleNewData,
- loadMoreLogs,
- queryPayload,
- } = useHandleLogsPagination({
- timeRange,
- filters,
- excludeFilterKeys: ['host.name'],
- basePayload,
- });
-
- const { data, isLoading, isFetching, isError } = useQuery({
- queryKey: [
- 'hostMetricsLogs',
- timeRange.startTime,
- timeRange.endTime,
- filters,
- currentPage,
- ],
- queryFn: () => GetMetricQueryRange(queryPayload, DEFAULT_ENTITY_VERSION),
- enabled: !!queryPayload,
- keepPreviousData: isPaginating,
- });
-
- useEffect(() => {
- if (data?.payload?.data?.newResult?.data?.result) {
- handleNewData(data.payload.data.newResult.data.result);
- }
- }, [data, handleNewData]);
-
- useEffect(() => {
- setIsPaginating(false);
- }, [data, setIsPaginating]);
-
- const handleScrollToLog = useScrollToLog({
- logs,
- virtuosoRef,
- });
-
- const getItemContent = useCallback(
- (_: number, logToRender: ILog): JSX.Element => {
- return (
- <div key={logToRender.id}>
- <RawLogView
- isTextOverflowEllipsisDisabled
- data={logToRender}
- linesPerRow={5}
- fontSize={FontSize.MEDIUM}
- selectedFields={[
- {
- dataType: 'string',
- type: '',
- name: 'body',
- },
- {
- dataType: 'string',
- type: '',
- name: 'timestamp',
- },
- ]}
- onSetActiveLog={handleSetActiveLog}
- onClearActiveLog={handleCloseLogDetail}
- isActiveLog={activeLog?.id === logToRender.id}
- />
- </div>
- );
- },
- [activeLog, handleSetActiveLog, handleCloseLogDetail],
- );
-
- const renderFooter = useCallback(
- (): JSX.Element | null => (
- <>
- {isFetching ? (
- <div className="logs-loading-skeleton"> Loading more logs ... </div>
- ) : hasReachedEndOfLogs ? (
- <div className="logs-loading-skeleton"> *** End *** </div>
- ) : null}
- </>
- ),
- [isFetching, hasReachedEndOfLogs],
- );
-
- const renderContent = useMemo(
- () => (
- <Card bordered={false} className="host-metrics-logs-list-card">
- <OverlayScrollbar isVirtuoso>
- <Virtuoso
- className="host-metrics-logs-virtuoso"
- key="host-metrics-logs-virtuoso"
- ref={virtuosoRef}
- data={logs}
- endReached={loadMoreLogs}
- totalCount={logs.length}
- itemContent={getItemContent}
- overscan={200}
- components={{
- Footer: renderFooter,
- }}
- />
- </OverlayScrollbar>
- </Card>
- ),
- [logs, loadMoreLogs, getItemContent, renderFooter],
- );
-
- return (
- <div className="host-metrics-logs">
- {isLoading && <LogsLoading />}
- {!isLoading && !isError && logs.length === 0 && <NoLogsContainer />}
- {isError && !isLoading && <LogsError />}
- {!isLoading && !isError && logs.length > 0 && (
- <div
- className="host-metrics-logs-list-container"
- data-log-detail-ignore="true"
- >
- {renderContent}
- </div>
- )}
- {selectedTab && activeLog && (
- <LogDetail
- log={activeLog}
- onClose={handleCloseLogDetail}
- logs={logs}
- onNavigateLog={handleSetActiveLog}
- selectedTab={selectedTab}
- onAddToQuery={onAddToQuery}
- onClickActionItem={onAddToQuery}
- onScrollToLog={handleScrollToLog}
- />
- )}
- </div>
- );
-}
-
-export default HostMetricsLogs;
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/NoLogsContainer.tsx b/frontend/src/components/HostMetricsDetail/HostMetricsLogs/NoLogsContainer.tsx
deleted file mode 100644
index 92e7ebaac8..0000000000
--- a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/NoLogsContainer.tsx
+++ /dev/null
@@ -1,16 +0,0 @@
-import { Color } from '@signozhq/design-tokens';
-import { Typography } from 'antd';
-import { Ghost } from 'lucide-react';
-
-const { Text } = Typography;
-
-export default function NoLogsContainer(): React.ReactElement {
- return (
- <div className="no-logs-found">
- <Text type="secondary">
- <Ghost size={24} color={Color.BG_AMBER_500} /> No logs found for this host
- in the selected time range.
- </Text>
- </div>
- );
-}
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/constants.ts b/frontend/src/components/HostMetricsDetail/HostMetricsLogs/constants.ts
deleted file mode 100644
index 0028dda53e..0000000000
--- a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/constants.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { PANEL_TYPES } from 'constants/queryBuilder';
-import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { EQueryType } from 'types/common/dashboard';
-import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
-import { v4 as uuidv4 } from 'uuid';
-
-export const getHostLogsQueryPayload = (
- start: number,
- end: number,
- filters: IBuilderQuery['filters'],
-): GetQueryResultsProps => ({
- graphType: PANEL_TYPES.LIST,
- selectedTime: 'GLOBAL_TIME',
- query: {
- clickhouse_sql: [],
- promql: [],
- builder: {
- queryData: [
- {
- dataSource: DataSource.LOGS,
- queryName: 'A',
- aggregateOperator: 'noop',
- aggregateAttribute: {
- id: '------false',
- dataType: DataTypes.String,
- key: '',
- type: '',
- },
- timeAggregation: 'rate',
- spaceAggregation: 'sum',
- functions: [],
- filters,
- expression: 'A',
- disabled: false,
- stepInterval: 60,
- having: [],
- limit: null,
- orderBy: [
- {
- columnName: 'timestamp',
- order: 'desc',
- },
- ],
- groupBy: [],
- legend: '',
- reduceTo: ReduceOperators.AVG,
- offset: 0,
- pageSize: 100,
- },
- ],
- queryFormulas: [],
- queryTraceOperator: [],
- },
- id: uuidv4(),
- queryType: EQueryType.QUERY_BUILDER,
- },
- start,
- end,
-});
diff --git a/frontend/src/components/HostMetricsDetail/Metrics/Metrics.styles.scss b/frontend/src/components/HostMetricsDetail/Metrics/Metrics.styles.scss
deleted file mode 100644
index 65dcd00fdb..0000000000
--- a/frontend/src/components/HostMetricsDetail/Metrics/Metrics.styles.scss
+++ /dev/null
@@ -1,45 +0,0 @@
-.empty-container {
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100%;
-}
-
-.host-metrics-container {
- margin-top: 1rem;
-}
-
-.metrics-header {
- display: flex;
- justify-content: flex-end;
- margin-top: 1rem;
-
- gap: 8px;
- padding: 12px;
- border-radius: 3px;
- border: 1px solid var(--l1-border);
-}
-
-.host-metrics-card {
- margin: 8px 0 1rem 0;
- height: 300px;
- padding: 10px;
-
- border: 1px solid var(--l1-border);
-
- .ant-card-body {
- padding: 0;
- }
-
- .chart-container {
- width: 100%;
- height: 100%;
- }
-
- .no-data-container {
- position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- }
-}
diff --git a/frontend/src/components/HostMetricsDetail/Metrics/Metrics.tsx b/frontend/src/components/HostMetricsDetail/Metrics/Metrics.tsx
deleted file mode 100644
index 2f980d73bc..0000000000
--- a/frontend/src/components/HostMetricsDetail/Metrics/Metrics.tsx
+++ /dev/null
@@ -1,233 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { QueryFunctionContext, useQueries, UseQueryResult } from 'react-query';
-import { Card, Col, Row, Skeleton, Typography } from 'antd';
-import cx from 'classnames';
-import Uplot from 'components/Uplot';
-import { ENTITY_VERSION_V4 } from 'constants/app';
-import {
- getHostQueryPayload,
- hostWidgetInfo,
-} from 'container/LogDetailedView/InfraMetrics/constants';
-import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
-import {
- CustomTimeType,
- Time,
-} from 'container/TopNav/DateTimeSelectionV2/types';
-import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { useIsDarkMode } from 'hooks/useDarkMode';
-import { useResizeObserver } from 'hooks/useDimensions';
-import { useMultiIntersectionObserver } from 'hooks/useMultiIntersectionObserver';
-import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
-import { getUPlotChartOptions } from 'lib/uPlotLib/getUplotChartOptions';
-import { getUPlotChartData } from 'lib/uPlotLib/utils/getUplotChartData';
-import { SuccessResponse } from 'types/api';
-import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
-
-import { FeatureKeys } from '../../../constants/features';
-import { useAppContext } from '../../../providers/App/App';
-
-import './Metrics.styles.scss';
-
-interface MetricsTabProps {
- timeRange: {
- startTime: number;
- endTime: number;
- };
- isModalTimeSelection: boolean;
- handleTimeChange: (
- interval: Time | CustomTimeType,
- dateTimeRange?: [number, number],
- ) => void;
- selectedInterval: Time;
-
- hostName: string;
-}
-
-function Metrics({
- selectedInterval,
- hostName,
- timeRange,
- handleTimeChange,
- isModalTimeSelection,
-}: MetricsTabProps): JSX.Element {
- const { featureFlags } = useAppContext();
- const dotMetricsEnabled =
- featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
- ?.active || false;
-
- const {
- visibilities,
- setElement,
- } = useMultiIntersectionObserver(hostWidgetInfo.length, { threshold: 0.1 });
-
- const legendScrollPositionRef = useRef<{
- scrollTop: number;
- scrollLeft: number;
- }>({
- scrollTop: 0,
- scrollLeft: 0,
- });
-
- const queryPayloads = useMemo(
- () =>
- getHostQueryPayload(
- hostName,
- timeRange.startTime,
- timeRange.endTime,
- dotMetricsEnabled,
- ),
- [hostName, timeRange.startTime, timeRange.endTime, dotMetricsEnabled],
- );
-
- const queries = useQueries(
- queryPayloads.map((payload, index) => ({
- queryKey: ['host-metrics', payload, ENTITY_VERSION_V4, 'HOST'],
- queryFn: ({
- signal,
- }: QueryFunctionContext): Promise<
- SuccessResponse<MetricRangePayloadProps>
- > => GetMetricQueryRange(payload, ENTITY_VERSION_V4, undefined, signal),
- enabled: !!payload && visibilities[index],
- keepPreviousData: true,
- })),
- );
-
- const isDarkMode = useIsDarkMode();
- const graphRef = useRef<HTMLDivElement>(null);
- const dimensions = useResizeObserver(graphRef);
- const { currentQuery } = useQueryBuilder();
-
- const chartData = useMemo(
- () => queries.map(({ data }) => getUPlotChartData(data?.payload)),
- [queries],
- );
-
- const [graphTimeIntervals, setGraphTimeIntervals] = useState<
- {
- start: number;
- end: number;
- }[]
- >(
- new Array(queries.length).fill({
- start: timeRange.startTime,
- end: timeRange.endTime,
- }),
- );
-
- useEffect(() => {
- setGraphTimeIntervals(
- new Array(queries.length).fill({
- start: timeRange.startTime,
- end: timeRange.endTime,
- }),
- );
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [timeRange]);
-
- const onDragSelect = useCallback(
- (start: number, end: number, graphIndex: number) => {
- const startTimestamp = Math.trunc(start);
- const endTimestamp = Math.trunc(end);
-
- setGraphTimeIntervals((prev) => {
- const newIntervals = [...prev];
- newIntervals[graphIndex] = {
- start: Math.floor(startTimestamp / 1000),
- end: Math.floor(endTimestamp / 1000),
- };
- return newIntervals;
- });
- },
- [],
- );
-
- const options = useMemo(
- () =>
- queries.map(({ data }, idx) =>
- getUPlotChartOptions({
- apiResponse: data?.payload,
- isDarkMode,
- dimensions,
- yAxisUnit: hostWidgetInfo[idx].yAxisUnit,
- softMax: null,
- softMin: null,
- minTimeScale: graphTimeIntervals[idx].start,
- maxTimeScale: graphTimeIntervals[idx].end,
- onDragSelect: (start, end) => onDragSelect(start, end, idx),
- query: currentQuery,
- legendScrollPosition: legendScrollPositionRef.current,
- setLegendScrollPosition: (position: {
- scrollTop: number;
- scrollLeft: number;
- }) => {
- legendScrollPositionRef.current = position;
- },
- }),
- ),
- [
- queries,
- isDarkMode,
- dimensions,
- graphTimeIntervals,
- onDragSelect,
- currentQuery,
- ],
- );
-
- const renderCardContent = (
- query: UseQueryResult<SuccessResponse<MetricRangePayloadProps>, unknown>,
- idx: number,
- ): JSX.Element => {
- if ((!query.data && query.isLoading) || !visibilities[idx]) {
- return <Skeleton />;
- }
-
- if (query.error) {
- const errorMessage =
- (query.error as Error)?.message || 'Something went wrong';
- return <div>{errorMessage}</div>;
- }
- return (
- <div
- className={cx('chart-container', {
- 'no-data-container':
- !query.isLoading && !query?.data?.payload?.data?.result?.length,
- })}
- >
- <Uplot options={options[idx]} data={chartData[idx]} />
- </div>
- );
- };
-
- return (
- <>
- <div className="metrics-header">
- <div className="metrics-datetime-section">
- <DateTimeSelectionV2
- showAutoRefresh
- showRefreshText={false}
- hideShareModal
- onTimeChange={handleTimeChange}
- defaultRelativeTime="5m"
- isModalTimeSelection={isModalTimeSelection}
- modalSelectedInterval={selectedInterval}
- modalInitialStartTime={timeRange.startTime * 1000}
- modalInitialEndTime={timeRange.endTime * 1000}
- />
- </div>
- </div>
- <Row gutter={24} className="host-metrics-container">
- {queries.map((query, idx) => (
- <Col ref={setElement(idx)} span={12} key={hostWidgetInfo[idx].title}>
- <Typography.Text>{hostWidgetInfo[idx].title}</Typography.Text>
- <Card bordered className="host-metrics-card" ref={graphRef}>
- {renderCardContent(query, idx)}
- </Card>
- </Col>
- ))}
- </Row>
- </>
- );
-}
-
-export default Metrics;
diff --git a/frontend/src/components/HostMetricsDetail/constants.ts b/frontend/src/components/HostMetricsDetail/constants.ts
deleted file mode 100644
index e024fe5b55..0000000000
--- a/frontend/src/components/HostMetricsDetail/constants.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-export enum VIEWS {
- METRICS = 'metrics',
- LOGS = 'logs',
- TRACES = 'traces',
- CONTAINERS = 'containers',
- PROCESSES = 'processes',
- EVENTS = 'events',
-}
-
-export const VIEW_TYPES = {
- METRICS: VIEWS.METRICS,
- LOGS: VIEWS.LOGS,
- TRACES: VIEWS.TRACES,
- CONTAINERS: VIEWS.CONTAINERS,
- PROCESSES: VIEWS.PROCESSES,
- EVENTS: VIEWS.EVENTS,
-};
diff --git a/frontend/src/components/HostMetricsDetail/index.tsx b/frontend/src/components/HostMetricsDetail/index.tsx
deleted file mode 100644
index 5af00e9c32..0000000000
--- a/frontend/src/components/HostMetricsDetail/index.tsx
+++ /dev/null
@@ -1,3 +0,0 @@
-import HostMetricsDetails from './HostMetricsDetails';
-
-export default HostMetricsDetails;
diff --git a/frontend/src/container/InfraMonitoringHosts/Hosts.tsx b/frontend/src/container/InfraMonitoringHosts/Hosts.tsx
new file mode 100644
index 0000000000..cf8de4e401
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringHosts/Hosts.tsx
@@ -0,0 +1,205 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { VerticalAlignTopOutlined } from '@ant-design/icons';
+import { Button, Tooltip, Typography } from 'antd';
+import logEvent from 'api/common/logEvent';
+import QuickFilters from 'components/QuickFilters/QuickFilters';
+import { QuickFiltersSource } from 'components/QuickFilters/types';
+import { InfraMonitoringEvents } from 'constants/events';
+import { FeatureKeys } from 'constants/features';
+import K8sBaseDetails from 'container/InfraMonitoringK8s/Base/K8sBaseDetails';
+import { K8sBaseList } from 'container/InfraMonitoringK8s/Base/K8sBaseList';
+import { K8sBaseFilters } from 'container/InfraMonitoringK8s/Base/types';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
+import {
+ useInfraMonitoringCurrentPage,
+ useInfraMonitoringFilters,
+} from 'container/InfraMonitoringK8s/hooks';
+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
+import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
+import { Filter } from 'lucide-react';
+import { useAppContext } from 'providers/App/App';
+import { Query } from 'types/api/queryBuilder/queryBuilderData';
+
+import {
+ fetchHostEntityData,
+ fetchHostListData,
+ getHostMetricsQueryPayload,
+ hostDetailsMetadataConfig,
+ hostGetEntityName,
+ hostGetSelectedItemFilters,
+ hostInitialEventsFilter,
+ hostInitialLogTracesFilter,
+ hostWidgetInfo,
+} from './constants';
+import {
+ hostColumns,
+ hostColumnsConfig,
+ hostRenderRowData,
+} from './table.config';
+import { getHostsQuickFiltersConfig } from './utils';
+
+import styles from './InfraMonitoringHosts.module.scss';
+
+function Hosts(): JSX.Element {
+ const [showFilters, setShowFilters] = useState(true);
+ const [, setCurrentPage] = useInfraMonitoringCurrentPage();
+ const [urlFilters, setUrlFilters] = useInfraMonitoringFilters();
+
+ const { featureFlags } = useAppContext();
+ const dotMetricsEnabled =
+ featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
+ ?.active || false;
+
+ const { currentQuery } = useQueryBuilder();
+ const { handleChangeQueryData } = useQueryOperations({
+ index: 0,
+ query: currentQuery.builder.queryData[0],
+ entityVersion: '',
+ });
+
+ // Track previous urlFilters to only sync when the value actually changes
+ // (not when handleChangeQueryData changes due to query updates)
+ const prevUrlFiltersRef = useRef<string | null>(null);
+
+ useEffect(() => {
+ const currentFiltersJson = urlFilters ? JSON.stringify(urlFilters) : null;
+
+ // Only sync if urlFilters value has actually changed
+ if (prevUrlFiltersRef.current !== currentFiltersJson) {
+ prevUrlFiltersRef.current = currentFiltersJson;
+ // Sync filters to query builder, using empty filter when urlFilters is null
+ handleChangeQueryData('filters', urlFilters || { items: [], op: 'and' });
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [urlFilters]); // handleChangeQueryData intentionally omitted - we call the current version but don't re-run when it changes
+
+ const handleFilterVisibilityChange = (): void => {
+ setShowFilters(!showFilters);
+ };
+
+ const handleQuickFiltersChange = (query: Query): void => {
+ const filters = query.builder.queryData[0].filters;
+ // Nuqs batches these calls into a single URL update
+ // The useEffect will sync filters to query builder
+ setUrlFilters(filters || null);
+ setCurrentPage(1);
+ logEvent(InfraMonitoringEvents.FilterApplied, {
+ entity: InfraMonitoringEvents.HostEntity,
+ page: InfraMonitoringEvents.ListPage,
+ });
+ };
+
+ const fetchListData = useCallback(
+ async (filters: K8sBaseFilters, signal?: AbortSignal) => {
+ filters.orderBy ||= {
+ columnName: 'cpu',
+ order: 'desc',
+ };
+
+ return fetchHostListData(filters, signal);
+ },
+ [],
+ );
+
+ const fetchEntityData = useCallback(
+ async (
+ filters: Parameters<typeof fetchHostEntityData>[0],
+ signal?: AbortSignal,
+ ) => fetchHostEntityData(filters, signal),
+ [],
+ );
+
+ const getSelectedItemFilters = useCallback(
+ (selectedItem: string) =>
+ hostGetSelectedItemFilters(selectedItem, dotMetricsEnabled),
+ [dotMetricsEnabled],
+ );
+
+ const getInitialLogTracesFilters = useCallback(
+ (host: import('api/infraMonitoring/getHostLists').HostData) =>
+ hostInitialLogTracesFilter(host, dotMetricsEnabled),
+ [dotMetricsEnabled],
+ );
+
+ const primaryFilterKeys = useMemo(
+ () => [dotMetricsEnabled ? 'host.name' : 'host_name'],
+ [dotMetricsEnabled],
+ );
+
+ const controlListPrefix = !showFilters ? (
+ <div className={styles.quickFiltersToggleContainer}>
+ <Button
+ className="periscope-btn ghost"
+ type="text"
+ size="small"
+ onClick={handleFilterVisibilityChange}
+ >
+ <Filter size={14} />
+ </Button>
+ </div>
+ ) : undefined;
+
+ return (
+ <>
+ <div className={styles.infraMonitoringContainer}>
+ <div className={styles.infraContentRow}>
+ {showFilters && (
+ <div className={styles.quickFiltersContainer}>
+ <div className={styles.quickFiltersContainerHeader}>
+ <Typography.Text>Filters</Typography.Text>
+ <Tooltip title="Collapse Filters">
+ <VerticalAlignTopOutlined
+ rotate={270}
+ onClick={handleFilterVisibilityChange}
+ />
+ </Tooltip>
+ </div>
+ <QuickFilters
+ source={QuickFiltersSource.INFRA_MONITORING}
+ config={getHostsQuickFiltersConfig(dotMetricsEnabled)}
+ handleFilterVisibilityChange={handleFilterVisibilityChange}
+ onFilterChange={handleQuickFiltersChange}
+ />
+ </div>
+ )}
+ <div
+ className={`${styles.listContainer}${
+ showFilters ? ` ${styles.listContainerFiltersVisible}` : ''
+ }`}
+ >
+ <K8sBaseList
+ controlListPrefix={controlListPrefix}
+ entity={InfraMonitoringEntity.HOSTS}
+ tableColumnsDefinitions={hostColumns}
+ tableColumns={hostColumnsConfig}
+ fetchListData={fetchListData}
+ renderRowData={hostRenderRowData}
+ eventCategory={InfraMonitoringEvents.HostEntity}
+ />
+ </div>
+ </div>
+ </div>
+ <K8sBaseDetails
+ category={InfraMonitoringEntity.HOSTS}
+ eventCategory={InfraMonitoringEvents.HostEntity}
+ getSelectedItemFilters={getSelectedItemFilters}
+ fetchEntityData={fetchEntityData}
+ getEntityName={hostGetEntityName}
+ getInitialLogTracesFilters={getInitialLogTracesFilters}
+ getInitialEventsFilters={hostInitialEventsFilter}
+ primaryFilterKeys={primaryFilterKeys}
+ metadataConfig={hostDetailsMetadataConfig}
+ entityWidgetInfo={hostWidgetInfo}
+ getEntityQueryPayload={getHostMetricsQueryPayload}
+ queryKeyPrefix="hosts"
+ tabsConfig={{
+ showEvents: false,
+ showContainers: true,
+ showProcesses: true,
+ }}
+ />
+ </>
+ );
+}
+
+export default Hosts;
diff --git a/frontend/src/container/InfraMonitoringHosts/HostsEmptyOrIncorrectMetrics.tsx b/frontend/src/container/InfraMonitoringHosts/HostsEmptyOrIncorrectMetrics.tsx
deleted file mode 100644
index d0be619239..0000000000
--- a/frontend/src/container/InfraMonitoringHosts/HostsEmptyOrIncorrectMetrics.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { Typography } from 'antd';
-
-import eyesEmojiUrl from '@/assets/Images/eyesEmoji.svg';
-
-export default function HostsEmptyOrIncorrectMetrics({
- noData,
- incorrectData,
-}: {
- noData: boolean;
- incorrectData: boolean;
-}): JSX.Element {
- return (
- <div className="hosts-empty-state-container">
- <div className="hosts-empty-state-container-content">
- <img className="eyes-emoji" src={eyesEmojiUrl} alt="eyes emoji" />
-
- {noData && (
- <div className="no-hosts-message">
- <Typography.Title level={5} className="no-hosts-message-title">
- No host metrics data received yet.
- </Typography.Title>
-
- <Typography.Text className="no-hosts-message-text">
- Infrastructure monitoring requires the{' '}
- <a
- href="https://github.com/open-telemetry/semantic-conventions/blob/main/docs/system/system-metrics.md"
- target="_blank"
- rel="noreferrer"
- >
- OpenTelemetry system metrics
- </a>
- . Please refer to{' '}
- <a
- href="https://signoz.io/docs/userguide/hostmetrics"
- target="_blank"
- rel="noreferrer"
- >
- this
- </a>{' '}
- to learn how to send host metrics to SigNoz.
- </Typography.Text>
- </div>
- )}
-
- {incorrectData && (
- <Typography.Text className="incorrect-metrics-message">
- To see host metrics, upgrade to the latest version of SigNoz k8s-infra
- chart. Please contact support if you need help.
- </Typography.Text>
- )}
- </div>
- </div>
- );
-}
diff --git a/frontend/src/container/InfraMonitoringHosts/HostsList.tsx b/frontend/src/container/InfraMonitoringHosts/HostsList.tsx
deleted file mode 100644
index 740c6c9b78..0000000000
--- a/frontend/src/container/InfraMonitoringHosts/HostsList.tsx
+++ /dev/null
@@ -1,253 +0,0 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
-import { useQuery } from 'react-query';
-import { VerticalAlignTopOutlined } from '@ant-design/icons';
-import { Button, Tooltip, Typography } from 'antd';
-import logEvent from 'api/common/logEvent';
-import {
- getHostLists,
- HostListPayload,
- HostListResponse,
-} from 'api/infraMonitoring/getHostLists';
-import HostMetricDetail from 'components/HostMetricsDetail';
-import QuickFilters from 'components/QuickFilters/QuickFilters';
-import { QuickFiltersSource } from 'components/QuickFilters/types';
-import { InfraMonitoringEvents } from 'constants/events';
-import { FeatureKeys } from 'constants/features';
-import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
-import {
- useInfraMonitoringCurrentPage,
- useInfraMonitoringFiltersHosts,
- useInfraMonitoringOrderByHosts,
-} from 'container/InfraMonitoringK8s/hooks';
-import { usePageSize } from 'container/InfraMonitoringK8s/utils';
-import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
-import { Filter } from 'lucide-react';
-import { parseAsString, useQueryState } from 'nuqs';
-import { useAppContext } from 'providers/App/App';
-import { useGlobalTimeStore } from 'store/globalTime';
-import {
- getAutoRefreshQueryKey,
- NANO_SECOND_MULTIPLIER,
-} from 'store/globalTime/utils';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-import {
- IBuilderQuery,
- Query,
- TagFilter,
-} from 'types/api/queryBuilder/queryBuilderData';
-
-import HostsListControls from './HostsListControls';
-import HostsListTable from './HostsListTable';
-import { getHostListsQuery, GetHostsQuickFiltersConfig } from './utils';
-
-import './InfraMonitoring.styles.scss';
-
-const defaultFilters: TagFilter = { items: [], op: 'and' };
-const baseQuery = getHostListsQuery();
-
-function HostsList(): JSX.Element {
- const [currentPage, setCurrentPage] = useInfraMonitoringCurrentPage();
- const [filters, setFilters] = useInfraMonitoringFiltersHosts();
- const [orderBy, setOrderBy] = useInfraMonitoringOrderByHosts();
-
- const [showFilters, setShowFilters] = useState<boolean>(true);
-
- const [selectedHostName, setSelectedHostName] = useQueryState(
- 'hostName',
- parseAsString.withDefault(''),
- );
-
- const handleOrderByChange = (
- orderByValue: {
- columnName: string;
- order: 'asc' | 'desc';
- } | null,
- ): void => {
- setOrderBy(orderByValue);
- };
-
- const handleHostClick = (hostName: string): void => {
- setSelectedHostName(hostName);
- };
-
- const { pageSize, setPageSize } = usePageSize('hosts');
-
- const selectedTime = useGlobalTimeStore((s) => s.selectedTime);
- const isRefreshEnabled = useGlobalTimeStore((s) => s.isRefreshEnabled);
- const refreshInterval = useGlobalTimeStore((s) => s.refreshInterval);
- const getMinMaxTime = useGlobalTimeStore((s) => s.getMinMaxTime);
-
- const queryKey = useMemo(
- () =>
- getAutoRefreshQueryKey(
- selectedTime,
- REACT_QUERY_KEY.GET_HOST_LIST,
- String(pageSize),
- String(currentPage),
- JSON.stringify(filters),
- JSON.stringify(orderBy),
- ),
- [pageSize, currentPage, filters, orderBy, selectedTime],
- );
-
- const { data, isFetching, isLoading, isError } = useQuery<
- SuccessResponse<HostListResponse> | ErrorResponse,
- Error
- >({
- queryKey,
- queryFn: ({ signal }) => {
- const { minTime, maxTime } = getMinMaxTime();
-
- const payload: HostListPayload = {
- ...baseQuery,
- limit: pageSize,
- offset: (currentPage - 1) * pageSize,
- filters: filters ?? defaultFilters,
- orderBy,
- start: Math.floor(minTime / NANO_SECOND_MULTIPLIER),
- end: Math.floor(maxTime / NANO_SECOND_MULTIPLIER),
- };
-
- return getHostLists(payload, signal);
- },
- enabled: true,
- keepPreviousData: true,
- refetchInterval: isRefreshEnabled ? refreshInterval : false,
- });
-
- const hostMetricsData = useMemo(() => data?.payload?.data?.records || [], [
- data,
- ]);
-
- const { currentQuery } = useQueryBuilder();
-
- const { handleChangeQueryData } = useQueryOperations({
- index: 0,
- query: currentQuery.builder.queryData[0],
- entityVersion: '',
- });
-
- const { featureFlags } = useAppContext();
- const dotMetricsEnabled =
- featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
- ?.active || false;
-
- const handleFiltersChange = useCallback(
- (value: IBuilderQuery['filters']): void => {
- const isNewFilterAdded = value?.items?.length !== filters?.items?.length;
- setFilters(value ?? null);
- handleChangeQueryData('filters', value);
- if (isNewFilterAdded) {
- setCurrentPage(1);
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.HostEntity,
- page: InfraMonitoringEvents.ListPage,
- });
- }
- }
- },
- [filters, setFilters, setCurrentPage, handleChangeQueryData],
- );
-
- useEffect(() => {
- logEvent(InfraMonitoringEvents.PageVisited, {
- total: data?.payload?.data?.total,
- entity: InfraMonitoringEvents.HostEntity,
- page: InfraMonitoringEvents.ListPage,
- });
- }, [data?.payload?.data?.total]);
-
- const selectedHostData = useMemo(() => {
- if (!selectedHostName?.trim()) {
- return null;
- }
- return (
- hostMetricsData.find((host) => host.hostName === selectedHostName) || null
- );
- }, [selectedHostName, hostMetricsData]);
-
- const handleCloseHostDetail = (): void => {
- setSelectedHostName(null);
- };
-
- const handleFilterVisibilityChange = (): void => {
- setShowFilters(!showFilters);
- };
-
- const handleQuickFiltersChange = (query: Query): void => {
- handleChangeQueryData('filters', query.builder.queryData[0].filters);
- handleFiltersChange(query.builder.queryData[0].filters);
- };
-
- return (
- <div className="hosts-list">
- <div className="hosts-list-content">
- {showFilters && (
- <div className="hosts-quick-filters-container">
- <div className="hosts-quick-filters-container-header">
- <Typography.Text>Filters</Typography.Text>
- <Tooltip title="Collapse Filters">
- <VerticalAlignTopOutlined
- rotate={270}
- onClick={handleFilterVisibilityChange}
- />
- </Tooltip>
- </div>
- <QuickFilters
- source={QuickFiltersSource.INFRA_MONITORING}
- config={GetHostsQuickFiltersConfig(dotMetricsEnabled)}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- onFilterChange={handleQuickFiltersChange}
- />
- </div>
- )}
- <div className="hosts-list-table-container">
- <div className="hosts-list-table-header">
- {!showFilters && (
- <div className="quick-filters-toggle-container">
- <Button
- className="periscope-btn ghost"
- type="text"
- size="small"
- onClick={handleFilterVisibilityChange}
- >
- <Filter size={14} />
- </Button>
- </div>
- )}
- <HostsListControls
- filters={filters}
- handleFiltersChange={handleFiltersChange}
- showAutoRefresh={!selectedHostData}
- />
- </div>
- <HostsListTable
- isLoading={isLoading}
- isFetching={isFetching}
- isError={isError}
- tableData={data}
- hostMetricsData={hostMetricsData}
- filters={filters ?? defaultFilters}
- currentPage={currentPage}
- setCurrentPage={setCurrentPage}
- onHostClick={handleHostClick}
- pageSize={pageSize}
- setPageSize={setPageSize}
- setOrderBy={handleOrderByChange}
- orderBy={orderBy}
- />
- </div>
- </div>
- <HostMetricDetail
- host={selectedHostData}
- isModalTimeSelection
- onClose={handleCloseHostDetail}
- />
- </div>
- );
-}
-
-export default HostsList;
diff --git a/frontend/src/container/InfraMonitoringHosts/HostsListControls.tsx b/frontend/src/container/InfraMonitoringHosts/HostsListControls.tsx
deleted file mode 100644
index 2904542536..0000000000
--- a/frontend/src/container/InfraMonitoringHosts/HostsListControls.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import { useCallback, useMemo } from 'react';
-import { initialQueriesMap } from 'constants/queryBuilder';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
-import QueryBuilderSearch from 'container/QueryBuilder/filters/QueryBuilderSearch';
-import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { DataSource } from 'types/common/queryBuilder';
-
-import './InfraMonitoring.styles.scss';
-
-function HostsListControls({
- handleFiltersChange,
- filters,
- showAutoRefresh,
-}: {
- handleFiltersChange: (value: IBuilderQuery['filters']) => void;
- filters: IBuilderQuery['filters'] | null;
- showAutoRefresh: boolean;
-}): JSX.Element {
- const currentQuery = initialQueriesMap[DataSource.METRICS];
- const updatedCurrentQuery = useMemo(
- () => ({
- ...currentQuery,
- builder: {
- ...currentQuery.builder,
- queryData: [
- {
- ...currentQuery.builder.queryData[0],
- aggregateOperator: 'noop',
- aggregateAttribute: {
- ...currentQuery.builder.queryData[0].aggregateAttribute,
- },
- filters,
- },
- ],
- },
- }),
- [currentQuery, filters],
- );
- const query = updatedCurrentQuery?.builder?.queryData[0] || null;
-
- const handleChangeTagFilters = useCallback(
- (value: IBuilderQuery['filters']) => {
- handleFiltersChange(value);
- },
- [handleFiltersChange],
- );
-
- return (
- <div className="hosts-list-controls">
- <div className="hosts-list-controls-left">
- <QueryBuilderSearch
- query={query as IBuilderQuery}
- onChange={handleChangeTagFilters}
- isInfraMonitoring
- disableNavigationShortcuts
- entity={K8sCategory.HOSTS}
- />
- </div>
-
- <div className="time-selector">
- <DateTimeSelectionV2
- showAutoRefresh={showAutoRefresh}
- showRefreshText={false}
- hideShareModal
- />
- </div>
- </div>
- );
-}
-
-export default HostsListControls;
diff --git a/frontend/src/container/InfraMonitoringHosts/HostsListTable.tsx b/frontend/src/container/InfraMonitoringHosts/HostsListTable.tsx
deleted file mode 100644
index 41a8ec3676..0000000000
--- a/frontend/src/container/InfraMonitoringHosts/HostsListTable.tsx
+++ /dev/null
@@ -1,271 +0,0 @@
-import React, { useCallback, useMemo, useState } from 'react';
-import { LoadingOutlined } from '@ant-design/icons';
-import {
- Skeleton,
- Spin,
- Table,
- TablePaginationConfig,
- TableProps,
- Typography,
-} from 'antd';
-import type { SorterResult } from 'antd/es/table/interface';
-import logEvent from 'api/common/logEvent';
-import ErrorContent from 'components/ErrorModal/components/ErrorContent';
-import { InfraMonitoringEvents } from 'constants/events';
-import { isModifierKeyPressed } from 'utils/app';
-import { openInNewTab } from 'utils/navigation';
-
-import emptyStateUrl from '@/assets/Icons/emptyState.svg';
-import eyesEmojiUrl from '@/assets/Images/eyesEmoji.svg';
-
-import HostsEmptyOrIncorrectMetrics from './HostsEmptyOrIncorrectMetrics';
-import {
- EmptyOrLoadingViewProps,
- formatDataForTable,
- getHostsListColumns,
- HostRowData,
- HostsListTableProps,
-} from './utils';
-
-function EmptyOrLoadingView(
- viewState: EmptyOrLoadingViewProps,
-): React.ReactNode {
- if (viewState.showTableLoadingState) {
- return (
- <div className="hosts-list-loading-state">
- <Skeleton.Input
- className="hosts-list-loading-state-item"
- size="large"
- block
- active
- />
- <Skeleton.Input
- className="hosts-list-loading-state-item"
- size="large"
- block
- active
- />
- <Skeleton.Input
- className="hosts-list-loading-state-item"
- size="large"
- block
- active
- />
- </div>
- );
- }
- const { isError, data } = viewState;
- if (isError || data?.error || (data?.statusCode || 0) >= 300) {
- return (
- <ErrorContent
- error={{
- code: data?.statusCode || 500,
- message: data?.error || 'Something went wrong',
- }}
- />
- );
- }
- if (viewState.showHostsEmptyState) {
- return (
- <HostsEmptyOrIncorrectMetrics
- noData={!viewState.sentAnyHostMetricsData}
- incorrectData={viewState.isSendingIncorrectK8SAgentMetrics}
- />
- );
- }
- if (viewState.showEndTimeBeforeRetentionMessage) {
- return (
- <div className="hosts-empty-state-container">
- <div className="hosts-empty-state-container-content">
- <img className="eyes-emoji" src={eyesEmojiUrl} alt="eyes emoji" />
- <div className="no-hosts-message">
- <Typography.Title level={5} className="no-hosts-message-title">
- Queried time range is before earliest host metrics
- </Typography.Title>
- <Typography.Text className="no-hosts-message-text">
- Your requested end time is earlier than the earliest detected time of
- host metrics data, please adjust your end time.
- </Typography.Text>
- </div>
- </div>
- </div>
- );
- }
- if (viewState.showNoRecordsInSelectedTimeRangeMessage) {
- return (
- <div className="no-filtered-hosts-message-container">
- <div className="no-filtered-hosts-message-content">
- <img
- src={emptyStateUrl}
- alt="thinking-emoji"
- className="empty-state-svg"
- />
- <Typography.Title level={5} className="no-filtered-hosts-title">
- No host metrics found
- </Typography.Title>
- <Typography.Text className="no-filtered-hosts-message">
- No host metrics in the selected time range and filters. Please adjust your
- time range or filters.
- </Typography.Text>
- </div>
- </div>
- );
- }
- return null;
-}
-
-export default function HostsListTable({
- isLoading,
- isFetching,
- isError,
- tableData: data,
- hostMetricsData,
- filters,
- onHostClick,
- currentPage,
- setCurrentPage,
- pageSize,
- setOrderBy,
- setPageSize,
- orderBy,
-}: HostsListTableProps): JSX.Element {
- const [defaultOrderBy] = useState(orderBy);
- const columns = useMemo(() => getHostsListColumns(defaultOrderBy), [
- defaultOrderBy,
- ]);
-
- const sentAnyHostMetricsData = useMemo(
- () => data?.payload?.data?.sentAnyHostMetricsData || false,
- [data],
- );
-
- const isSendingIncorrectK8SAgentMetrics = useMemo(
- () => data?.payload?.data?.isSendingK8SAgentMetrics || false,
- [data],
- );
-
- const endTimeBeforeRetention = useMemo(
- () => data?.payload?.data?.endTimeBeforeRetention || false,
- [data],
- );
-
- const formattedHostMetricsData = useMemo(
- () => formatDataForTable(hostMetricsData),
- [hostMetricsData],
- );
-
- const totalCount = data?.payload?.data?.total || 0;
-
- const handleTableChange: TableProps<HostRowData>['onChange'] = useCallback(
- (
- pagination: TablePaginationConfig,
- _filters: Record<string, (string | number | boolean)[] | null>,
- sorter: SorterResult<HostRowData> | SorterResult<HostRowData>[],
- ): void => {
- if (pagination.current) {
- setCurrentPage(pagination.current);
- }
-
- if ('field' in sorter && sorter.order) {
- setOrderBy({
- columnName: sorter.field as string,
- order: sorter.order === 'ascend' ? 'asc' : 'desc',
- });
- } else {
- setOrderBy(null);
- }
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleRowClick = (
- record: HostRowData,
- event: React.MouseEvent,
- ): void => {
- if (isModifierKeyPressed(event)) {
- const params = new URLSearchParams(window.location.search);
- params.set('hostName', record.hostName);
- openInNewTab(`${window.location.pathname}?${params.toString()}`);
- return;
- }
- onHostClick(record.hostName);
- logEvent(InfraMonitoringEvents.ItemClicked, {
- entity: InfraMonitoringEvents.HostEntity,
- page: InfraMonitoringEvents.ListPage,
- });
- };
-
- const showHostsEmptyState =
- !isFetching &&
- !isLoading &&
- formattedHostMetricsData.length === 0 &&
- (!sentAnyHostMetricsData || isSendingIncorrectK8SAgentMetrics) &&
- !filters.items.length &&
- !endTimeBeforeRetention;
-
- const showEndTimeBeforeRetentionMessage =
- !isFetching &&
- !isLoading &&
- formattedHostMetricsData.length === 0 &&
- endTimeBeforeRetention &&
- !filters.items.length;
-
- const showNoRecordsInSelectedTimeRangeMessage =
- !isFetching &&
- !isLoading &&
- formattedHostMetricsData.length === 0 &&
- !showEndTimeBeforeRetentionMessage &&
- !showHostsEmptyState;
-
- const showTableLoadingState =
- (isLoading || isFetching) && formattedHostMetricsData.length === 0;
-
- const emptyOrLoadingView = EmptyOrLoadingView({
- isError,
- data,
- showHostsEmptyState,
- sentAnyHostMetricsData,
- isSendingIncorrectK8SAgentMetrics,
- showEndTimeBeforeRetentionMessage,
- showNoRecordsInSelectedTimeRangeMessage,
- showTableLoadingState,
- });
-
- if (emptyOrLoadingView) {
- return <>{emptyOrLoadingView}</>;
- }
-
- return (
- <Table
- className="hosts-list-table"
- dataSource={showTableLoadingState ? [] : formattedHostMetricsData}
- columns={columns}
- pagination={{
- current: currentPage,
- pageSize,
- total: totalCount,
- showSizeChanger: true,
- hideOnSinglePage: false,
- onChange: (page, pageSize): void => {
- setCurrentPage(page);
- setPageSize(pageSize);
- },
- }}
- scroll={{ x: true }}
- loading={{
- spinning: showTableLoadingState,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- tableLayout="fixed"
- rowKey={(record): string =>
- (record as HostRowData & { key: string }).key ?? record.hostName
- }
- onChange={handleTableChange}
- onRow={(record: HostRowData): Record<string, unknown> => ({
- onClick: (event: React.MouseEvent): void => handleRowClick(record, event),
- className: 'clickable-row',
- })}
- />
- );
-}
diff --git a/frontend/src/container/InfraMonitoringHosts/InfraMonitoring.styles.scss b/frontend/src/container/InfraMonitoringHosts/InfraMonitoring.styles.scss
deleted file mode 100644
index 1ddffac699..0000000000
--- a/frontend/src/container/InfraMonitoringHosts/InfraMonitoring.styles.scss
+++ /dev/null
@@ -1,416 +0,0 @@
-.infra-monitoring-container {
- display: flex;
- height: 100%;
- flex-direction: column;
-
- .infra-monitoring-header {
- display: flex;
- justify-content: space-between;
- width: 100%;
- margin-bottom: 16px;
- }
-
- .hosts-list-controls {
- flex: 1;
- padding: 8px;
-
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: 16px;
-
- .ant-select-selector {
- border-radius: 2px;
- border: 1px solid var(--l1-border) !important;
- background-color: var(--l3-background) !important;
-
- input {
- font-size: 12px;
- }
-
- .ant-tag .ant-typography {
- font-size: 12px;
- }
- }
-
- .hosts-list-controls-left {
- flex: 1;
- }
- }
-
- .progress-container {
- display: flex;
- align-items: center;
- }
-
- .progress-bar {
- flex: 1;
- margin-right: 8px;
- }
-
- .clickable-row {
- cursor: pointer;
- }
-
- .hosts-list-content {
- display: flex;
- flex-direction: row;
- align-items: stretch;
- height: calc(100vh - 110px);
-
- .hosts-quick-filters-container {
- width: 280px;
- min-width: 280px;
- border-right: 1px solid var(--l1-border);
- height: 100%;
-
- .hosts-quick-filters-container-header {
- padding: 8px;
- border-bottom: 1px solid var(--l1-border);
-
- display: flex;
- align-items: center;
- justify-content: space-between;
- }
- }
- }
-
- .hosts-list-table-container {
- flex: 1;
-
- .hosts-list-table-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
-
- .quick-filters-toggle-container {
- padding: 0 8px;
- }
- }
- }
-
- .hosts-list-table {
- .ant-table {
- .ant-table-thead > tr > th {
- padding: 12px;
- font-weight: 500;
- font-size: 12px;
- line-height: 18px;
-
- background: var(--l1-background);
- border-bottom: none;
-
- color: var(--muted-foreground);
- font-family: Inter;
- font-size: 11px;
- font-style: normal;
- font-weight: 600;
- line-height: 18px; /* 163.636% */
- letter-spacing: 0.44px;
- text-transform: uppercase;
-
- &::before {
- background-color: transparent;
- }
- }
-
- .ant-table-thead > tr > th:has(.hostname-column-header) {
- background: var(--l2-background);
- }
-
- .ant-table-cell {
- padding: 12px;
- font-size: 13px;
- line-height: 20px;
- color: var(--l1-foreground);
- background: var(--l1-background);
- }
-
- .ant-table-cell:has(.hostname-column-value),
- .ant-table-cell:has(.hostname-cell-missing) {
- background: var(--l2-background);
- }
-
- .hostname-column-value {
- color: var(--l1-foreground);
- font-family: 'Geist Mono';
- font-style: normal;
- font-weight: 600;
- line-height: 20px; /* 142.857% */
- letter-spacing: -0.07px;
- }
-
- .hostname-cell-missing {
- display: flex;
- align-items: center;
- gap: 4px;
- }
-
- .hostname-cell-placeholder {
- color: var(--muted-foreground);
- }
-
- .hostname-cell-warning-icon {
- display: inline-flex;
- align-items: center;
- margin-left: 4px;
- cursor: help;
- }
-
- .status-cell {
- .active-tag {
- color: var(--bg-forest-500);
- padding: 4px 8px;
- border-radius: 4px;
- font-size: 12px;
- font-weight: 500;
- }
- }
-
- .progress-container {
- .ant-progress-bg {
- height: 8px !important;
- border-radius: 4px;
- }
- }
-
- .ant-table-tbody > tr:hover > td {
- background: color-mix(in srgb, var(--l1-foreground) 4%, transparent);
- }
-
- .ant-table-cell:first-child {
- text-align: justify;
- }
-
- .ant-table-cell:nth-child(2) {
- padding-left: 16px;
- padding-right: 16px;
- }
-
- .ant-table-cell:nth-child(n + 3) {
- padding-right: 24px;
- }
- .status-header {
- display: flex;
- align-items: center;
- gap: 4px;
- }
- .memory-usage-header {
- display: flex;
- align-items: center;
- justify-content: flex-end;
- gap: 4px;
- margin-right: 4px;
- }
- .column-header-right {
- text-align: right;
- }
- .column-header-left {
- text-align: left;
- }
- .ant-table-tbody > tr > td {
- border-bottom: none;
- }
-
- .ant-table-thead
- > tr
- > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not([colspan])::before {
- background-color: transparent;
- }
-
- .ant-empty-normal {
- visibility: hidden;
- }
- }
-
- .ant-pagination {
- position: fixed;
- bottom: 0;
- width: calc(100% - 364px);
- background: var(--l1-background);
- padding: 16px;
- margin: 0;
-
- // this is to offset chat support icon till we improve the design
- right: 20px;
-
- .ant-pagination-item {
- border-radius: 4px;
-
- &-active {
- background: var(--primary-background);
- border-color: var(--primary-background);
-
- a {
- color: var(--l1-foreground) !important;
- }
- }
- }
- }
- }
-}
-
-.infra-monitoring-tags {
- width: fit-content;
-
- font-family: Inter;
- font-size: 11px;
- font-style: normal;
- font-weight: 500;
- line-height: 18px; /* 163.636% */
- letter-spacing: 0.44px;
- text-transform: uppercase;
-
- border-radius: 50px;
- padding: 2px 8px;
-
- &.active {
- color: var(--bg-forest-500);
- border: 1px solid color-mix(in srgb, var(--bg-forest-500) 20%, transparent);
- background: color-mix(in srgb, var(--bg-forest-500) 10%, transparent);
- }
-
- &.inactive {
- color: var(--l3-foreground);
- border: 1px solid color-mix(in srgb, var(--bg-slate-50) 20%, transparent);
- background: color-mix(in srgb, var(--bg-slate-50) 10%, transparent);
- }
-}
-
-.hosts-list-loading-state {
- padding: 8px;
- display: flex;
- flex-direction: column;
- gap: 2px;
- flex: 1;
-
- .hosts-list-loading-state-item {
- height: 48px;
- width: 100%;
- }
-}
-
-.no-filtered-hosts-message-container {
- flex: 1;
- height: 30vh;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
-
- .no-filtered-hosts-message-content {
- display: flex;
- flex-direction: column;
- align-items: flex-start;
- justify-content: center;
-
- width: fit-content;
- padding: 24px;
- }
-
- .no-filtered-hosts-message {
- margin-top: 8px;
- }
-}
-
-.hosts-empty-state-container {
- padding: 16px;
- height: 40vh;
- flex: 1;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
-
- .hosts-empty-state-container-content {
- padding: 16px;
- display: flex;
- flex-direction: column;
- align-items: flex-start;
- justify-content: center;
-
- width: fit-content;
-
- .no-hosts-message {
- margin-bottom: 16px;
-
- .no-hosts-message-title {
- margin-top: 8px;
- margin-bottom: 4px;
- }
- }
- }
-}
-
-.lightMode {
- .infra-monitoring-container {
- .ant-table-thead > tr > th {
- background: var(--l1-background);
- color: var(--l1-foreground);
- }
-
- .ant-table-cell {
- color: var(--l1-foreground);
- }
- .hosts-list-controls {
- border-top: 1px solid var(--l1-border);
- border-bottom: 1px solid var(--l1-border);
-
- .ant-select-selector {
- border-color: var(--l1-border) !important;
- background-color: var(--l1-background) !important;
- color: var(--l2-foreground);
- }
- }
- }
-
- .hosts-list-table {
- .ant-table {
- .ant-table-thead > tr > th {
- background: var(--l1-background);
- color: var(--l2-foreground);
- }
-
- .ant-table-thead > tr > th:has(.hostname-column-header) {
- background: var(--l1-background);
- }
-
- .ant-table-cell {
- background: var(--l1-background);
- color: var(--l1-foreground);
- }
-
- .ant-table-cell:has(.hostname-column-value),
- .ant-table-cell:has(.hostname-cell-missing) {
- background: var(--l1-background);
- }
-
- .hostname-column-value {
- color: var(--l1-foreground);
- }
-
- .hostname-cell-placeholder {
- color: var(--l2-foreground);
- }
-
- .ant-table-tbody > tr:hover > td {
- background: rgba(0, 0, 0, 0.04);
- }
- }
-
- .ant-pagination {
- background: var(--l1-background);
-
- .ant-pagination-item {
- &-active {
- background: var(--primary-background);
- border-color: var(--primary-background);
-
- a {
- color: var(--l1-background) !important;
- }
- }
- }
- }
- }
-}
diff --git a/frontend/src/container/InfraMonitoringHosts/InfraMonitoringHosts.module.scss b/frontend/src/container/InfraMonitoringHosts/InfraMonitoringHosts.module.scss
new file mode 100644
index 0000000000..4a2f49d895
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringHosts/InfraMonitoringHosts.module.scss
@@ -0,0 +1,175 @@
+.infraMonitoringContainer {
+ display: flex;
+ height: 100%;
+ flex-direction: column;
+}
+
+.infraContentRow {
+ display: flex;
+ flex-direction: row;
+ height: calc(100vh - 45px);
+ width: 100%;
+ position: relative;
+ overflow-y: auto;
+
+ :global(.periscope-btn) {
+ &.ghost:not(:disabled) {
+ border: none;
+ background: transparent;
+
+ &:hover {
+ background: transparent;
+ color: var(--bg-robin-500) !important;
+ font-weight: 500;
+ }
+ }
+ }
+
+ &::-webkit-scrollbar {
+ width: 0.1rem;
+ height: 0.1rem;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: var(--accent-primary);
+ }
+
+ &::-webkit-scrollbar-thumb:hover {
+ background: colox-mix(var(--accent-primary), var(--bg-vanilla-100), 20%);
+ }
+}
+
+.quickFiltersContainer {
+ width: 280px;
+ min-width: 280px;
+ border-right: 1px solid var(--l1-border);
+ overflow-y: auto;
+
+ &::-webkit-scrollbar {
+ width: 0.1rem;
+ height: 0.1rem;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: var(--accent-primary);
+ }
+
+ &::-webkit-scrollbar-thumb:hover {
+ background: colox-mix(var(--accent-primary), var(--bg-vanilla-100), 20%);
+ }
+
+ :global(.ant-collapse-header) {
+ border-bottom: 1px solid var(--l1-border);
+ padding: 12px 8px;
+ }
+
+ :global(.ant-collapse-content-box) {
+ padding: 0 !important;
+ padding-block: 0 !important;
+
+ :global(.quick-filters .checkbox-filter) {
+ padding-left: 18px;
+ }
+ }
+
+ :global(.quick-filters) {
+ overflow-y: auto;
+ overflow-x: hidden;
+
+ &::-webkit-scrollbar {
+ width: 0.1rem;
+ height: 0.1rem;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: var(--accent-primary);
+ }
+
+ &::-webkit-scrollbar-thumb:hover {
+ background: colox-mix(var(--accent-primary), var(--bg-vanilla-100), 20%);
+ }
+ }
+}
+
+.quickFiltersContainerHeader {
+ padding: 8px;
+ border-bottom: 1px solid var(--l1-border);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+
+.listContainer {
+ flex: 1;
+ min-width: 0;
+ max-width: 100%;
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+
+ > * {
+ min-width: 0;
+ max-width: 100%;
+ box-sizing: border-box;
+ }
+
+ > :global(.ant-table-wrapper) {
+ width: 100%;
+ max-width: 100%;
+
+ :global(.ant-spin-container) {
+ display: flex !important;
+ flex-direction: column;
+ }
+
+ :global(.ant-table),
+ :global(.ant-table-container) {
+ max-width: 100%;
+ }
+ }
+}
+
+.listContainerFiltersVisible {
+ max-width: calc(100% - 280px);
+}
+
+.quickFiltersToggleContainer {
+ padding: 0 8px;
+}
+
+.infraMonitoringTags {
+ width: fit-content;
+ font-family: Inter;
+ font-size: 11px;
+ font-style: normal;
+ font-weight: 500;
+ line-height: 18px;
+ letter-spacing: 0.44px;
+ text-transform: uppercase;
+ border-radius: 50px;
+ padding: 2px 8px;
+}
+
+.tagsActive {
+ color: var(--bg-forest-500, #25e192);
+ border: 1px solid rgba(37, 225, 146, 0.2);
+ background: rgba(37, 225, 146, 0.1);
+}
+
+.tagsInactive {
+ color: var(--bg-slate-50, #62687c);
+ border: 1px solid rgba(98, 104, 124, 0.2);
+ background: rgba(98, 104, 124, 0.1);
+}
diff --git a/frontend/src/container/InfraMonitoringHosts/__tests__/HostsEmptyOrIncorrectMetrics.test.tsx b/frontend/src/container/InfraMonitoringHosts/__tests__/HostsEmptyOrIncorrectMetrics.test.tsx
deleted file mode 100644
index 0b2aa28531..0000000000
--- a/frontend/src/container/InfraMonitoringHosts/__tests__/HostsEmptyOrIncorrectMetrics.test.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { render, screen } from '@testing-library/react';
-
-import HostsEmptyOrIncorrectMetrics from '../HostsEmptyOrIncorrectMetrics';
-
-describe('HostsEmptyOrIncorrectMetrics', () => {
- it('shows no data message when noData is true', () => {
- render(<HostsEmptyOrIncorrectMetrics noData incorrectData={false} />);
- expect(
- screen.getByText('No host metrics data received yet.'),
- ).toBeInTheDocument();
- expect(
- screen.getByText(/Infrastructure monitoring requires the/),
- ).toBeInTheDocument();
- });
-
- it('shows incorrect data message when incorrectData is true', () => {
- render(<HostsEmptyOrIncorrectMetrics noData={false} incorrectData />);
- expect(
- screen.getByText(
- 'To see host metrics, upgrade to the latest version of SigNoz k8s-infra chart. Please contact support if you need help.',
- ),
- ).toBeInTheDocument();
- });
-
- it('does not show no data message when noData is false', () => {
- render(<HostsEmptyOrIncorrectMetrics noData={false} incorrectData={false} />);
- expect(
- screen.queryByText('No host metrics data received yet.'),
- ).not.toBeInTheDocument();
- expect(
- screen.queryByText(/Infrastructure monitoring requires the/),
- ).not.toBeInTheDocument();
- });
-
- it('does not show incorrect data message when incorrectData is false', () => {
- render(<HostsEmptyOrIncorrectMetrics noData={false} incorrectData={false} />);
- expect(
- screen.queryByText(
- 'To see host metrics, upgrade to the latest version of SigNoz k8s-infra chart. Please contact support if you need help.',
- ),
- ).not.toBeInTheDocument();
- });
-});
diff --git a/frontend/src/container/InfraMonitoringHosts/__tests__/HostsList.test.tsx b/frontend/src/container/InfraMonitoringHosts/__tests__/HostsList.test.tsx
index 2b375ba777..afb6bee35f 100644
--- a/frontend/src/container/InfraMonitoringHosts/__tests__/HostsList.test.tsx
+++ b/frontend/src/container/InfraMonitoringHosts/__tests__/HostsList.test.tsx
@@ -4,13 +4,16 @@ import { Provider } from 'react-redux';
import { MemoryRouter } from 'react-router-dom';
import { render, waitFor } from '@testing-library/react';
import * as getHostListsApi from 'api/infraMonitoring/getHostLists';
+import { initialQueriesMap } from 'constants/queryBuilder';
+import * as useQueryBuilderHooks from 'hooks/queryBuilder/useQueryBuilder';
+import * as useQueryBuilderOperations from 'hooks/queryBuilder/useQueryBuilderOperations';
import { withNuqsTestingAdapter } from 'nuqs/adapters/testing';
import * as appContextHooks from 'providers/App/App';
import * as timezoneHooks from 'providers/Timezone';
import store from 'store';
import { LicenseEvent } from 'types/api/licensesV3/getActive';
-import HostsList from '../HostsList';
+import Hosts from '../Hosts';
jest.mock('lib/getMinMax', () => ({
__esModule: true,
@@ -30,10 +33,6 @@ jest.mock('container/TopNav/DateTimeSelectionV2', () => ({
<div data-testid="date-time-selection">Date Time</div>
),
}));
-jest.mock('components/HostMetricsDetail', () => ({
- __esModule: true,
- default: (): null => null,
-}));
jest.mock('components/CustomTimePicker/CustomTimePicker', () => ({
__esModule: true,
default: ({ onSelect, selectedTime, selectedValue }: any): JSX.Element => (
@@ -53,20 +52,6 @@ const queryClient = new QueryClient({
},
});
-jest.mock('react-redux', () => ({
- ...jest.requireActual('react-redux'),
- useSelector: (): any => ({
- globalTime: {
- selectedTime: {
- startTime: 1713734400000,
- endTime: 1713738000000,
- },
- maxTime: 1713738000000,
- minTime: 1713734400000,
- },
- }),
-}));
-
jest.mock('react-router-dom', () => {
const ROUTES = jest.requireActual('constants/routes').default;
return {
@@ -128,6 +113,7 @@ jest.spyOn(appContextHooks, 'useAppContext').mockReturnValue({
user: {
role: 'admin',
},
+ featureFlags: [],
activeLicenseV3: {
event_queue: {
created_at: '0',
@@ -148,9 +134,22 @@ jest.spyOn(appContextHooks, 'useAppContext').mockReturnValue({
},
} as any);
+jest.spyOn(useQueryBuilderHooks, 'useQueryBuilder').mockReturnValue({
+ currentQuery: initialQueriesMap.metrics,
+ setSupersetQuery: jest.fn(),
+ setLastUsedQuery: jest.fn(),
+ handleSetConfig: jest.fn(),
+ resetQuery: jest.fn(),
+ updateAllQueriesOperators: jest.fn(),
+} as any);
+
+jest.spyOn(useQueryBuilderOperations, 'useQueryOperations').mockReturnValue({
+ handleChangeQueryData: jest.fn(),
+} as any);
+
const Wrapper = withNuqsTestingAdapter({ searchParams: {} });
-describe('HostsList', () => {
+describe('Hosts', () => {
beforeEach(() => {
queryClient.clear();
});
@@ -161,14 +160,14 @@ describe('HostsList', () => {
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<Provider store={store}>
- <HostsList />
+ <Hosts />
</Provider>
</MemoryRouter>
</QueryClientProvider>
</Wrapper>,
);
await waitFor(() => {
- expect(container.querySelector('.hosts-list-table')).toBeInTheDocument();
+ expect(container.querySelector('.ant-table')).toBeInTheDocument();
});
});
@@ -178,7 +177,7 @@ describe('HostsList', () => {
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<Provider store={store}>
- <HostsList />
+ <Hosts />
</Provider>
</MemoryRouter>
</QueryClientProvider>
diff --git a/frontend/src/container/InfraMonitoringHosts/__tests__/HostsListControl.test.tsx b/frontend/src/container/InfraMonitoringHosts/__tests__/HostsListControl.test.tsx
deleted file mode 100644
index be299a253c..0000000000
--- a/frontend/src/container/InfraMonitoringHosts/__tests__/HostsListControl.test.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-import { render, screen } from '@testing-library/react';
-
-import HostsListControls from '../HostsListControls';
-
-jest.mock('container/QueryBuilder/filters/QueryBuilderSearch', () => ({
- __esModule: true,
- default: (): JSX.Element => (
- <div data-testid="query-builder-search">Search</div>
- ),
-}));
-
-jest.mock('container/TopNav/DateTimeSelectionV2', () => ({
- __esModule: true,
- default: (): JSX.Element => (
- <div data-testid="date-time-selection">Date Time</div>
- ),
-}));
-
-describe('HostsListControls', () => {
- const mockHandleFiltersChange = jest.fn();
- const mockFilters = {
- items: [],
- op: 'AND',
- };
-
- it('renders search and date time filters', () => {
- render(
- <HostsListControls
- handleFiltersChange={mockHandleFiltersChange}
- filters={mockFilters}
- showAutoRefresh={false}
- />,
- );
-
- expect(screen.getByTestId('query-builder-search')).toBeInTheDocument();
- expect(screen.getByTestId('date-time-selection')).toBeInTheDocument();
- });
-});
diff --git a/frontend/src/container/InfraMonitoringHosts/__tests__/HostsListTable.test.tsx b/frontend/src/container/InfraMonitoringHosts/__tests__/HostsListTable.test.tsx
deleted file mode 100644
index 5b378b8b9e..0000000000
--- a/frontend/src/container/InfraMonitoringHosts/__tests__/HostsListTable.test.tsx
+++ /dev/null
@@ -1,276 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { HostData, HostListResponse } from 'api/infraMonitoring/getHostLists';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-
-import HostsListTable from '../HostsListTable';
-import { HostsListTableProps } from '../utils';
-
-const EMPTY_STATE_CONTAINER_CLASS = '.hosts-empty-state-container';
-
-const createMockHost = (): HostData =>
- ({
- hostName: 'test-host-1',
- active: true,
- cpu: 0.75,
- memory: 0.65,
- wait: 0.03,
- load15: 1.5,
- os: 'linux',
- cpuTimeSeries: { labels: {}, labelsArray: [], values: [] },
- memoryTimeSeries: { labels: {}, labelsArray: [], values: [] },
- waitTimeSeries: { labels: {}, labelsArray: [], values: [] },
- load15TimeSeries: { labels: {}, labelsArray: [], values: [] },
- } as HostData);
-
-const createMockTableData = (
- overrides: Partial<HostListResponse['data']> = {},
-): SuccessResponse<HostListResponse> => {
- const mockHost = createMockHost();
- return {
- statusCode: 200,
- message: 'Success',
- error: null,
- payload: {
- status: 'success',
- data: {
- type: 'list',
- records: [mockHost],
- groups: null,
- total: 1,
- sentAnyHostMetricsData: true,
- isSendingK8SAgentMetrics: false,
- endTimeBeforeRetention: false,
- ...overrides,
- },
- },
- };
-};
-
-describe('HostsListTable', () => {
- const mockHost = createMockHost();
- const mockTableData = createMockTableData();
-
- const mockOnHostClick = jest.fn();
- const mockSetCurrentPage = jest.fn();
- const mockSetOrderBy = jest.fn();
- const mockSetPageSize = jest.fn();
-
- const mockProps: HostsListTableProps = {
- isLoading: false,
- isError: false,
- isFetching: false,
- tableData: mockTableData,
- hostMetricsData: [mockHost],
- filters: {
- items: [],
- op: 'AND',
- },
- onHostClick: mockOnHostClick,
- currentPage: 1,
- setCurrentPage: mockSetCurrentPage,
- pageSize: 10,
- setOrderBy: mockSetOrderBy,
- setPageSize: mockSetPageSize,
- orderBy: null,
- };
-
- it('renders loading state if isLoading is true and tableData is empty', () => {
- const { container } = render(
- <HostsListTable
- {...mockProps}
- isLoading
- hostMetricsData={[]}
- tableData={createMockTableData({ records: [] })}
- />,
- );
- expect(container.querySelector('.hosts-list-loading-state')).toBeTruthy();
- });
-
- it('renders loading state if isFetching is true and tableData is empty', () => {
- const { container } = render(
- <HostsListTable
- {...mockProps}
- isFetching
- hostMetricsData={[]}
- tableData={createMockTableData({ records: [] })}
- />,
- );
- expect(container.querySelector('.hosts-list-loading-state')).toBeTruthy();
- });
-
- it('renders error state if isError is true', () => {
- render(<HostsListTable {...mockProps} isError />);
- expect(screen.getByText('Something went wrong')).toBeTruthy();
- });
-
- it('renders "Something went wrong" fallback when isError is true and error message is empty', () => {
- const tableDataWithEmptyError: ErrorResponse = {
- statusCode: 500,
- payload: null,
- error: '',
- message: null,
- };
- render(
- <HostsListTable
- {...mockProps}
- isError
- hostMetricsData={[]}
- tableData={tableDataWithEmptyError}
- />,
- );
- expect(screen.getByText('Something went wrong')).toBeInTheDocument();
- });
-
- it('renders custom error message when isError is true and error message is provided', () => {
- const customErrorMessage = 'Failed to fetch host metrics';
- const tableDataWithError: ErrorResponse = {
- statusCode: 500,
- payload: null,
- error: customErrorMessage,
- message: null,
- };
- render(
- <HostsListTable
- {...mockProps}
- isError
- hostMetricsData={[]}
- tableData={tableDataWithError}
- />,
- );
- expect(screen.getByText(customErrorMessage)).toBeInTheDocument();
- });
-
- it('renders empty state if no hosts are found', () => {
- const { container } = render(
- <HostsListTable
- {...mockProps}
- hostMetricsData={[]}
- tableData={createMockTableData({
- records: [],
- })}
- />,
- );
- expect(
- container.querySelector('.no-filtered-hosts-message-container'),
- ).toBeTruthy();
- });
-
- it('renders empty state if sentAnyHostMetricsData is false', () => {
- const { container } = render(
- <HostsListTable
- {...mockProps}
- hostMetricsData={[]}
- tableData={createMockTableData({
- sentAnyHostMetricsData: false,
- records: [],
- })}
- />,
- );
- expect(container.querySelector(EMPTY_STATE_CONTAINER_CLASS)).toBeTruthy();
- });
-
- it('renders empty state if isSendingK8SAgentMetrics is true', () => {
- const { container } = render(
- <HostsListTable
- {...mockProps}
- hostMetricsData={[]}
- tableData={createMockTableData({
- isSendingK8SAgentMetrics: true,
- records: [],
- })}
- />,
- );
- expect(container.querySelector(EMPTY_STATE_CONTAINER_CLASS)).toBeTruthy();
- });
-
- it('renders end time before retention message when endTimeBeforeRetention is true', () => {
- const { container } = render(
- <HostsListTable
- {...mockProps}
- hostMetricsData={[]}
- tableData={createMockTableData({
- sentAnyHostMetricsData: true,
- isSendingK8SAgentMetrics: false,
- endTimeBeforeRetention: true,
- records: [],
- })}
- />,
- );
- expect(container.querySelector(EMPTY_STATE_CONTAINER_CLASS)).toBeTruthy();
- expect(
- screen.getByText(
- /Your requested end time is earlier than the earliest detected time of host metrics data, please adjust your end time\./,
- ),
- ).toBeInTheDocument();
- });
-
- it('renders no records message when noRecordsInSelectedTimeRangeAndFilters is true', () => {
- const { container } = render(
- <HostsListTable
- {...mockProps}
- hostMetricsData={[]}
- tableData={createMockTableData({
- sentAnyHostMetricsData: true,
- isSendingK8SAgentMetrics: false,
- records: [],
- })}
- />,
- );
- expect(
- container.querySelector('.no-filtered-hosts-message-container'),
- ).toBeTruthy();
- expect(
- screen.getByText(/No host metrics in the selected time range and filters/),
- ).toBeInTheDocument();
- });
-
- it('renders no filtered hosts message when filters are present and no hosts are found', () => {
- const { container } = render(
- <HostsListTable
- {...mockProps}
- hostMetricsData={[]}
- filters={{
- items: [
- {
- id: 'host_name',
- key: {
- key: 'host_name',
- dataType: DataTypes.String,
- type: 'tag',
- isIndexed: true,
- },
- op: '=',
- value: 'unknown',
- },
- ],
- op: 'AND',
- }}
- tableData={createMockTableData({
- sentAnyHostMetricsData: true,
- isSendingK8SAgentMetrics: false,
- records: [],
- })}
- />,
- );
- expect(container.querySelector('.no-filtered-hosts-message')).toBeTruthy();
- expect(
- screen.getByText(
- /No host metrics in the selected time range and filters\. Please adjust your time range or filters\./,
- ),
- ).toBeInTheDocument();
- });
-
- it('renders table data', () => {
- const { container } = render(
- <HostsListTable
- {...mockProps}
- tableData={createMockTableData({
- isSendingK8SAgentMetrics: false,
- sentAnyHostMetricsData: true,
- })}
- />,
- );
- expect(container.querySelector('.hosts-list-table')).toBeTruthy();
- });
-});
diff --git a/frontend/src/container/InfraMonitoringHosts/__tests__/utilts.test.tsx b/frontend/src/container/InfraMonitoringHosts/__tests__/utils.test.tsx
similarity index 51%
rename from frontend/src/container/InfraMonitoringHosts/__tests__/utilts.test.tsx
rename to frontend/src/container/InfraMonitoringHosts/__tests__/utils.test.tsx
index 82e17c6474..b7a576fd8d 100644
--- a/frontend/src/container/InfraMonitoringHosts/__tests__/utilts.test.tsx
+++ b/frontend/src/container/InfraMonitoringHosts/__tests__/utils.test.tsx
@@ -1,13 +1,8 @@
import { render, screen } from '@testing-library/react';
import { HostData, TimeSeries } from 'api/infraMonitoring/getHostLists';
-import {
- formatDataForTable,
- GetHostsQuickFiltersConfig,
- HostnameCell,
-} from '../utils';
-
-const PROGRESS_BAR_CLASS = '.progress-bar';
+import { hostRenderRowData } from '../table.config';
+import { getHostsQuickFiltersConfig, HostnameCell } from '../utils';
const emptyTimeSeries: TimeSeries = {
labels: {},
@@ -16,94 +11,79 @@ const emptyTimeSeries: TimeSeries = {
};
describe('InfraMonitoringHosts utils', () => {
- describe('formatDataForTable', () => {
+ describe('hostRenderRowData', () => {
it('should format host data correctly', () => {
- const mockData: HostData[] = [
- {
- hostName: 'test-host',
- active: true,
- cpu: 0.95,
- memory: 0.85,
- wait: 0.05,
- load15: 2.5,
- os: 'linux',
- cpuTimeSeries: emptyTimeSeries,
- memoryTimeSeries: emptyTimeSeries,
- waitTimeSeries: emptyTimeSeries,
- load15TimeSeries: emptyTimeSeries,
- },
- ];
-
- const result = formatDataForTable(mockData);
-
- expect(result[0].hostName).toBe('test-host');
- expect(result[0].wait).toBe('5%');
- expect(result[0].load15).toBe(2.5);
-
- // Test active tag rendering
- const activeTag = render(result[0].active as JSX.Element);
+ const host: HostData = {
+ hostName: 'test-host',
+ active: true,
+ cpu: 0.95,
+ memory: 0.85,
+ wait: 0.05,
+ load15: 2.5,
+ os: 'linux',
+ cpuTimeSeries: emptyTimeSeries,
+ memoryTimeSeries: emptyTimeSeries,
+ waitTimeSeries: emptyTimeSeries,
+ load15TimeSeries: emptyTimeSeries,
+ };
+
+ const result = hostRenderRowData(host, []);
+
+ expect(result.wait).toBe('5%');
+ expect(result.load15).toBe(2.5);
+ expect(result.itemKey).toBe('test-host');
+ expect(result.hostName).toBe('test-host');
+
+ const activeTag = render(result.active as JSX.Element);
expect(activeTag.container.textContent).toBe('ACTIVE');
- expect(activeTag.container.querySelector('.active')).toBeTruthy();
+ expect(activeTag.getByText('ACTIVE')).toBeTruthy();
- // Test CPU progress bar
- const cpuProgress = render(result[0].cpu as JSX.Element);
- const cpuProgressBar = cpuProgress.container.querySelector(
- PROGRESS_BAR_CLASS,
- );
- expect(cpuProgressBar).toBeTruthy();
+ const cpuProgress = render(result.cpu as JSX.Element);
+ expect(cpuProgress.container.querySelector('.ant-progress')).toBeTruthy();
- // Test memory progress bar
- const memoryProgress = render(result[0].memory as JSX.Element);
- const memoryProgressBar = memoryProgress.container.querySelector(
- PROGRESS_BAR_CLASS,
- );
- expect(memoryProgressBar).toBeTruthy();
+ const memoryProgress = render(result.memory as JSX.Element);
+ expect(memoryProgress.container.querySelector('.ant-progress')).toBeTruthy();
});
it('should handle inactive hosts', () => {
- const mockData: HostData[] = [
- {
- hostName: 'test-host',
- active: false,
- cpu: 0.3,
- memory: 0.4,
- wait: 0.02,
- load15: 1.2,
- os: 'linux',
- cpuTimeSeries: emptyTimeSeries,
- memoryTimeSeries: emptyTimeSeries,
- waitTimeSeries: emptyTimeSeries,
- load15TimeSeries: emptyTimeSeries,
- },
- ];
-
- const result = formatDataForTable(mockData);
-
- const inactiveTag = render(result[0].active as JSX.Element);
+ const host: HostData = {
+ hostName: 'test-host',
+ active: false,
+ cpu: 0.3,
+ memory: 0.4,
+ wait: 0.02,
+ load15: 1.2,
+ os: 'linux',
+ cpuTimeSeries: emptyTimeSeries,
+ memoryTimeSeries: emptyTimeSeries,
+ waitTimeSeries: emptyTimeSeries,
+ load15TimeSeries: emptyTimeSeries,
+ };
+
+ const result = hostRenderRowData(host, []);
+
+ const inactiveTag = render(result.active as JSX.Element);
expect(inactiveTag.container.textContent).toBe('INACTIVE');
- expect(inactiveTag.container.querySelector('.inactive')).toBeTruthy();
+ expect(inactiveTag.getByText('INACTIVE')).toBeTruthy();
});
- it('should set hostName to empty string when host has no hostname', () => {
- const mockData: HostData[] = [
- {
- hostName: '',
- active: true,
- cpu: 0.5,
- memory: 0.4,
- wait: 0.01,
- load15: 1.0,
- os: 'linux',
- cpuTimeSeries: emptyTimeSeries,
- memoryTimeSeries: emptyTimeSeries,
- waitTimeSeries: emptyTimeSeries,
- load15TimeSeries: emptyTimeSeries,
- },
- ];
-
- const result = formatDataForTable(mockData);
- expect(result[0].hostName).toBe('');
- expect(result[0].key).toBe('-0');
+ it('should use empty itemKey when host has no hostname', () => {
+ const host: HostData = {
+ hostName: '',
+ active: true,
+ cpu: 0.5,
+ memory: 0.4,
+ wait: 0.01,
+ load15: 1.0,
+ os: 'linux',
+ cpuTimeSeries: emptyTimeSeries,
+ memoryTimeSeries: emptyTimeSeries,
+ waitTimeSeries: emptyTimeSeries,
+ load15TimeSeries: emptyTimeSeries,
+ };
+
+ const result = hostRenderRowData(host, []);
+ expect(result.itemKey).toBe('');
});
});
@@ -126,7 +106,6 @@ describe('InfraMonitoringHosts utils', () => {
'Missing host.name metadata',
);
expect(iconWrapper?.getAttribute('tabindex')).toBe('0');
- // Tooltip with "Learn how to configure →" link is shown on hover/focus
});
it('should render placeholder and icon when hostName is whitespace only (case C)', () => {
@@ -144,9 +123,9 @@ describe('InfraMonitoringHosts utils', () => {
});
});
- describe('GetHostsQuickFiltersConfig', () => {
+ describe('getHostsQuickFiltersConfig', () => {
it('should return correct config when dotMetricsEnabled is true', () => {
- const result = GetHostsQuickFiltersConfig(true);
+ const result = getHostsQuickFiltersConfig(true);
expect(result[0].attributeKey.key).toBe('host.name');
expect(result[1].attributeKey.key).toBe('os.type');
@@ -154,7 +133,7 @@ describe('InfraMonitoringHosts utils', () => {
});
it('should return correct config when dotMetricsEnabled is false', () => {
- const result = GetHostsQuickFiltersConfig(false);
+ const result = getHostsQuickFiltersConfig(false);
expect(result[0].attributeKey.key).toBe('host_name');
expect(result[1].attributeKey.key).toBe('os_type');
diff --git a/frontend/src/container/InfraMonitoringHosts/constants.tsx b/frontend/src/container/InfraMonitoringHosts/constants.tsx
new file mode 100644
index 0000000000..6dd72645a0
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringHosts/constants.tsx
@@ -0,0 +1,189 @@
+import React from 'react';
+import { Color } from '@signozhq/design-tokens';
+import { Progress, Tag, Typography } from 'antd';
+import {
+ getHostLists,
+ HostData,
+ HostListPayload,
+} from 'api/infraMonitoring/getHostLists';
+import {
+ createFilterItem,
+ K8sDetailsFilters,
+ K8sDetailsMetadataConfig,
+} from 'container/InfraMonitoringK8s/Base/K8sBaseDetails';
+import { K8sBaseFilters } from 'container/InfraMonitoringK8s/Base/types';
+import {
+ getHostQueryPayload,
+ hostWidgetInfo,
+} from 'container/LogDetailedView/InfraMetrics/constants';
+import {
+ TagFilter,
+ TagFilterItem,
+} from 'types/api/queryBuilder/queryBuilderData';
+
+import { getHostListsQuery } from './utils';
+
+import infraHostsStyles from './InfraMonitoringHosts.module.scss';
+
+export function getProgressColor(percent: number): string {
+ if (percent >= 90) {
+ return Color.BG_SAKURA_500;
+ }
+ if (percent >= 60) {
+ return Color.BG_AMBER_500;
+ }
+ return Color.BG_FOREST_500;
+}
+
+export function getMemoryProgressColor(percent: number): string {
+ if (percent >= 90) {
+ return Color.BG_CHERRY_500;
+ }
+ if (percent >= 60) {
+ return Color.BG_AMBER_500;
+ }
+ return Color.BG_FOREST_500;
+}
+
+export const hostDetailsMetadataConfig: K8sDetailsMetadataConfig<HostData>[] = [
+ {
+ label: 'STATUS',
+ getValue: (h): string => (h.active ? 'ACTIVE' : 'INACTIVE'),
+ render: (value, h): React.ReactNode => (
+ <Tag
+ className={`${infraHostsStyles.infraMonitoringTags} ${
+ h.active ? infraHostsStyles.tagsActive : infraHostsStyles.tagsInactive
+ }`}
+ bordered
+ >
+ {value}
+ </Tag>
+ ),
+ },
+ {
+ label: 'OPERATING SYSTEM',
+ getValue: (h): string => h.os || '-',
+ render: (value): React.ReactNode =>
+ value !== '-' ? (
+ <Tag className={infraHostsStyles.infraMonitoringTags} bordered>
+ {value}
+ </Tag>
+ ) : (
+ <Typography.Text>-</Typography.Text>
+ ),
+ },
+ {
+ label: 'CPU USAGE',
+ getValue: (h): number => h.cpu * 100,
+ render: (value): React.ReactNode => (
+ <Progress
+ percent={Number(Number(value).toFixed(1))}
+ size="small"
+ strokeColor={getProgressColor(Number(value))}
+ />
+ ),
+ },
+ {
+ label: 'MEMORY USAGE',
+ getValue: (h): number => h.memory * 100,
+ render: (value): React.ReactNode => (
+ <Progress
+ percent={Number(Number(value).toFixed(1))}
+ size="small"
+ strokeColor={getMemoryProgressColor(Number(value))}
+ />
+ ),
+ },
+];
+
+export function getHostMetricsQueryPayload(
+ host: HostData,
+ start: number,
+ end: number,
+ dotMetricsEnabled: boolean,
+): ReturnType<typeof getHostQueryPayload> {
+ return getHostQueryPayload(host.hostName, start, end, dotMetricsEnabled);
+}
+
+export { hostWidgetInfo };
+
+export function hostGetSelectedItemFilters(
+ selectedItem: string,
+ dotMetricsEnabled: boolean,
+): TagFilter {
+ const hostKey = dotMetricsEnabled ? 'host.name' : 'host_name';
+ return {
+ op: 'AND',
+ items: [createFilterItem(hostKey, selectedItem)],
+ };
+}
+
+export function hostInitialLogTracesFilter(
+ host: HostData,
+ dotMetricsEnabled: boolean,
+): TagFilterItem[] {
+ const hostKey = dotMetricsEnabled ? 'host.name' : 'host_name';
+ return [createFilterItem(hostKey, host.hostName || '')];
+}
+
+export function hostInitialEventsFilter(_host: HostData): TagFilterItem[] {
+ return [];
+}
+
+export const hostGetEntityName = (host: HostData): string => host.hostName;
+
+export async function fetchHostListData(
+ filters: K8sBaseFilters,
+ signal?: AbortSignal,
+): Promise<{
+ data: HostData[];
+ total: number;
+ error?: string | null;
+ rawData?: unknown;
+}> {
+ const baseQuery = getHostListsQuery();
+ const payload: HostListPayload = {
+ ...baseQuery,
+ limit: filters.limit,
+ offset: filters.offset,
+ filters: filters.filters ?? { items: [], op: 'and' },
+ orderBy: filters.orderBy,
+ start: filters.start,
+ end: filters.end,
+ groupBy: filters.groupBy ?? [],
+ };
+
+ const response = await getHostLists(payload, signal);
+
+ return {
+ data: response.payload?.data?.records || [],
+ total: response.payload?.data?.total || 0,
+ error: response.error,
+ rawData: response.payload?.data,
+ };
+}
+
+export async function fetchHostEntityData(
+ filters: K8sDetailsFilters,
+ signal?: AbortSignal,
+): Promise<{ data: HostData | null; error?: string | null }> {
+ const response = await getHostLists(
+ {
+ ...getHostListsQuery(),
+ filters: filters.filters,
+ start: filters.start,
+ end: filters.end,
+ limit: 1,
+ offset: 0,
+ groupBy: [],
+ },
+ signal,
+ );
+
+ const records = response.payload?.data?.records || [];
+
+ return {
+ data: records.length > 0 ? records[0] : null,
+ error: response.error,
+ };
+}
diff --git a/frontend/src/container/InfraMonitoringHosts/index.tsx b/frontend/src/container/InfraMonitoringHosts/index.tsx
index 2f7b93651f..126a9bc678 100644
--- a/frontend/src/container/InfraMonitoringHosts/index.tsx
+++ b/frontend/src/container/InfraMonitoringHosts/index.tsx
@@ -5,9 +5,7 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
import { DataSource } from 'types/common/queryBuilder';
-import HostsList from './HostsList';
-
-import './InfraMonitoring.styles.scss';
+import Hosts from './Hosts';
function InfraMonitoringHosts(): JSX.Element {
const {
@@ -63,11 +61,7 @@ function InfraMonitoringHosts(): JSX.Element {
return (
<Sentry.ErrorBoundary fallback={<ErrorBoundaryFallback />}>
- <div className="infra-monitoring-container">
- <div className="hosts-list-container">
- <HostsList />
- </div>
- </div>
+ <Hosts />
</Sentry.ErrorBoundary>
);
}
diff --git a/frontend/src/container/InfraMonitoringHosts/table.config.tsx b/frontend/src/container/InfraMonitoringHosts/table.config.tsx
new file mode 100644
index 0000000000..1dda32fe5e
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringHosts/table.config.tsx
@@ -0,0 +1,234 @@
+import React from 'react';
+import { InfoCircleOutlined } from '@ant-design/icons';
+import { Progress, TableColumnType as ColumnType, Tag, Tooltip } from 'antd';
+import { HostData } from 'api/infraMonitoring/getHostLists';
+import { K8sRenderedRowData } from 'container/InfraMonitoringK8s/Base/types';
+import { IEntityColumn } from 'container/InfraMonitoringK8s/Base/useInfraMonitoringTableColumnsStore';
+import {
+ getGroupByEl,
+ getGroupedByMeta,
+ getRowKey,
+} from 'container/InfraMonitoringK8s/Base/utils';
+import { ValidateColumnValueWrapper } from 'container/InfraMonitoringK8s/commonUtils';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
+import { Group } from 'lucide-react';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+
+import { getMemoryProgressColor, getProgressColor } from './constants';
+import { HostnameCell } from './utils';
+
+import styles from './table.module.scss';
+
+export const hostColumns: IEntityColumn[] = [
+ {
+ label: 'Host group',
+ value: 'hostGroup',
+ id: 'hostGroup',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-collapse',
+ },
+ {
+ label: 'Hostname',
+ value: 'hostName',
+ id: 'hostName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-expand',
+ },
+ {
+ label: 'Status',
+ value: 'active',
+ id: 'active',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Usage',
+ value: 'cpu',
+ id: 'cpu',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Memory Usage',
+ value: 'memory',
+ id: 'memory',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'IOWait',
+ value: 'wait',
+ id: 'wait',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Load Avg',
+ value: 'load15',
+ id: 'load15',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+];
+
+export const hostColumnsConfig: ColumnType<K8sRenderedRowData>[] = [
+ {
+ title: (
+ <div className={styles.entityGroupHeader}>
+ <Group size={14} /> HOST GROUP
+ </div>
+ ),
+ dataIndex: 'hostGroup',
+ key: 'hostGroup',
+ ellipsis: true,
+ width: 180,
+ sorter: false,
+ },
+ {
+ title: <div className={styles.hostnameColumnHeader}>Hostname</div>,
+ dataIndex: 'hostName',
+ key: 'hostName',
+ width: 250,
+ render: (_value, record): React.ReactNode => (
+ <HostnameCell
+ hostName={typeof record.hostName === 'string' ? record.hostName : ''}
+ />
+ ),
+ },
+ {
+ title: (
+ <div className={styles.statusHeader}>
+ Status
+ <Tooltip title="Sent system metrics in last 10 mins">
+ <InfoCircleOutlined />
+ </Tooltip>
+ </div>
+ ),
+ dataIndex: 'active',
+ key: 'active',
+ width: 100,
+ },
+ {
+ title: <div className={styles.columnHeaderRight}>CPU Usage</div>,
+ dataIndex: 'cpu',
+ key: 'cpu',
+ width: 100,
+ sorter: true,
+ align: 'right',
+ },
+ {
+ title: (
+ <div className={`${styles.columnHeaderRight} ${styles.memoryUsageHeader}`}>
+ Memory Usage
+ <Tooltip title="Excluding cache memory">
+ <InfoCircleOutlined />
+ </Tooltip>
+ </div>
+ ),
+ dataIndex: 'memory',
+ key: 'memory',
+ width: 100,
+ sorter: true,
+ align: 'right',
+ },
+ {
+ title: <div className={styles.columnHeaderRight}>IOWait</div>,
+ dataIndex: 'wait',
+ key: 'wait',
+ width: 100,
+ sorter: true,
+ align: 'right',
+ },
+ {
+ title: <div className={styles.columnHeaderRight}>Load Avg</div>,
+ dataIndex: 'load15',
+ key: 'load15',
+ width: 100,
+ sorter: true,
+ align: 'right',
+ },
+];
+
+function hostRowSource(host: HostData): { meta: Record<string, string> } {
+ return {
+ meta: {
+ ...(host.meta ?? {}),
+ host_name: host.hostName ?? '',
+ 'host.name': host.hostName ?? '',
+ os_type: host.os ?? '',
+ 'os.type': host.os ?? '',
+ },
+ };
+}
+
+export const hostRenderRowData = (
+ host: HostData,
+ groupBy: BaseAutocompleteData[],
+): K8sRenderedRowData => {
+ const synthetic = hostRowSource(host);
+ const rowKey = getRowKey(synthetic, () => host.hostName || 'unknown', groupBy);
+ const groupedByMeta = getGroupedByMeta(synthetic, groupBy);
+ const cpuPercent = Number((host.cpu * 100).toFixed(1));
+ const memoryPercent = Number((host.memory * 100).toFixed(1));
+
+ return {
+ key: rowKey,
+ itemKey: host.hostName ?? '',
+ groupedByMeta,
+ meta: synthetic.meta,
+ hostGroup: getGroupByEl(synthetic, groupBy),
+ ...synthetic.meta,
+ hostName: host.hostName ?? '',
+ active: (
+ <Tag
+ bordered
+ className={`${styles.statusTag} ${
+ host.active ? styles.statusTagActive : styles.statusTagInactive
+ }`}
+ >
+ {host.active ? 'ACTIVE' : 'INACTIVE'}
+ </Tag>
+ ),
+ cpu: (
+ <div className={styles.progressContainer}>
+ <ValidateColumnValueWrapper
+ value={host.cpu}
+ entity={InfraMonitoringEntity.HOSTS}
+ >
+ <Progress
+ percent={cpuPercent}
+ strokeLinecap="butt"
+ size="small"
+ strokeColor={getProgressColor(cpuPercent)}
+ className={styles.progressBar}
+ />
+ </ValidateColumnValueWrapper>
+ </div>
+ ),
+ memory: (
+ <div className={styles.progressContainer}>
+ <ValidateColumnValueWrapper
+ value={host.memory}
+ entity={InfraMonitoringEntity.HOSTS}
+ >
+ <Progress
+ percent={memoryPercent}
+ strokeLinecap="butt"
+ size="small"
+ strokeColor={getMemoryProgressColor(memoryPercent)}
+ className={styles.progressBar}
+ />
+ </ValidateColumnValueWrapper>
+ </div>
+ ),
+ wait: `${Number((host.wait * 100).toFixed(1))}%`,
+ load15: host.load15,
+ };
+};
diff --git a/frontend/src/container/InfraMonitoringHosts/table.module.scss b/frontend/src/container/InfraMonitoringHosts/table.module.scss
new file mode 100644
index 0000000000..369aa52b71
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringHosts/table.module.scss
@@ -0,0 +1,73 @@
+.entityGroupHeader {
+ padding-left: var(--spacing-5);
+ gap: var(--spacing-5);
+ display: flex;
+ align-items: center;
+}
+
+.hostnameColumnHeader {
+ display: block;
+}
+
+.statusHeader {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--spacing-2);
+ width: 100%;
+}
+
+.columnHeaderRight {
+ text-align: right;
+}
+
+.memoryUsageHeader {
+ display: inline-flex;
+ align-items: center;
+ justify-content: flex-end;
+ gap: var(--spacing-2);
+ width: 100%;
+}
+
+.statusTag {
+ width: fit-content;
+ font-family: Inter, sans-serif;
+ font-size: 11px;
+ font-style: normal;
+ font-weight: 500;
+ line-height: 18px;
+ letter-spacing: 0.44px;
+ text-transform: uppercase;
+ border-radius: 50px;
+ padding: 2px 8px;
+}
+
+.statusTagActive {
+ color: var(--Forest-500, #25e192);
+ border: 1px solid rgba(37, 225, 146, 0.2);
+ background: rgba(37, 225, 146, 0.1);
+}
+
+.statusTagInactive {
+ color: var(--Slate-50, #62687c);
+ border: 1px solid rgba(98, 104, 124, 0.2);
+ background: rgba(98, 104, 124, 0.1);
+}
+
+.progressContainer {
+ display: flex;
+ align-items: center;
+
+ & > div {
+ width: 100%;
+ }
+
+ :global(.ant-progress-bg) {
+ height: 8px !important;
+ border-radius: 4px;
+ }
+}
+
+.progressBar {
+ flex: 1;
+ margin-right: 8px;
+}
diff --git a/frontend/src/container/InfraMonitoringHosts/utils.tsx b/frontend/src/container/InfraMonitoringHosts/utils.tsx
index f514f465ba..ecb05b007d 100644
--- a/frontend/src/container/InfraMonitoringHosts/utils.tsx
+++ b/frontend/src/container/InfraMonitoringHosts/utils.tsx
@@ -1,41 +1,15 @@
-import { Dispatch, SetStateAction } from 'react';
-import { InfoCircleOutlined } from '@ant-design/icons';
+import React from 'react';
import { Color } from '@signozhq/design-tokens';
-import {
- Progress,
- TableColumnType as ColumnType,
- Tag,
- Tooltip,
- Typography,
-} from 'antd';
-import { SortOrder } from 'antd/lib/table/interface';
-import {
- HostData,
- HostListPayload,
- HostListResponse,
-} from 'api/infraMonitoring/getHostLists';
+import { Tooltip, Typography } from 'antd';
+import { HostListPayload } from 'api/infraMonitoring/getHostLists';
import {
FiltersType,
IQuickFiltersConfig,
} from 'components/QuickFilters/types';
import { TriangleAlert } from 'lucide-react';
-import { ErrorResponse, SuccessResponse } from 'types/api';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
-import { OrderBySchemaType } from '../InfraMonitoringK8s/schemas';
-
-export interface HostRowData {
- key?: string;
- hostName: string;
- cpu: React.ReactNode;
- memory: React.ReactNode;
- wait: string;
- load15: number;
- active: React.ReactNode;
-}
-
const HOSTNAME_DOCS_URL =
'https://signoz.io/docs/infrastructure-monitoring/hostmetrics/#host-name-is-blankempty';
@@ -89,41 +63,6 @@ export function HostnameCell({
);
}
-export interface HostsListTableProps {
- isLoading: boolean;
- isError: boolean;
- isFetching: boolean;
- tableData:
- | SuccessResponse<HostListResponse, unknown>
- | ErrorResponse
- | undefined;
- hostMetricsData: HostData[];
- filters: TagFilter;
- onHostClick: (hostName: string) => void;
- currentPage: number;
- setCurrentPage: Dispatch<SetStateAction<number>>;
- pageSize: number;
- setOrderBy: (
- orderBy: { columnName: string; order: 'asc' | 'desc' } | null,
- ) => void;
- setPageSize: (pageSize: number) => void;
- orderBy: OrderBySchemaType;
-}
-
-export interface EmptyOrLoadingViewProps {
- isError: boolean;
- data:
- | ErrorResponse<string>
- | SuccessResponse<HostListResponse, unknown>
- | undefined;
- showHostsEmptyState: boolean;
- sentAnyHostMetricsData: boolean;
- isSendingIncorrectK8SAgentMetrics: boolean;
- showEndTimeBeforeRetentionMessage: boolean;
- showNoRecordsInSelectedTimeRangeMessage: boolean;
- showTableLoadingState: boolean;
-}
-
export const getHostListsQuery = (): HostListPayload => ({
filters: {
items: [],
@@ -133,143 +72,6 @@ export const getHostListsQuery = (): HostListPayload => ({
orderBy: { columnName: 'cpu', order: 'desc' },
});
-function mapOrderByToSortOrder(
- column: string,
- orderBy: OrderBySchemaType,
-): SortOrder | undefined {
- return orderBy?.columnName === column
- ? orderBy?.order === 'asc'
- ? 'ascend'
- : 'descend'
- : undefined;
-}
-
-export const getHostsListColumns = (
- orderBy: OrderBySchemaType,
-): ColumnType<HostRowData>[] => [
- {
- title: <div className="hostname-column-header">Hostname</div>,
- dataIndex: 'hostName',
- key: 'hostName',
- width: 250,
- render: (value: string | undefined): React.ReactNode => (
- <HostnameCell hostName={value ?? ''} />
- ),
- },
- {
- title: (
- <div className="status-header">
- Status
- <Tooltip title="Sent system metrics in last 10 mins">
- <InfoCircleOutlined />
- </Tooltip>
- </div>
- ),
- dataIndex: 'active',
- key: 'active',
- width: 100,
- },
- {
- title: <div className="column-header-right">CPU Usage</div>,
- dataIndex: 'cpu',
- key: 'cpu',
- width: 100,
- sorter: true,
- defaultSortOrder: mapOrderByToSortOrder('cpu', orderBy),
- align: 'right',
- },
- {
- title: (
- <div className="column-header-right memory-usage-header">
- Memory Usage
- <Tooltip title="Excluding cache memory">
- <InfoCircleOutlined />
- </Tooltip>
- </div>
- ),
- dataIndex: 'memory',
- key: 'memory',
- width: 100,
- sorter: true,
- defaultSortOrder: mapOrderByToSortOrder('memory', orderBy),
- align: 'right',
- },
- {
- title: <div className="column-header-right">IOWait</div>,
- dataIndex: 'wait',
- key: 'wait',
- width: 100,
- sorter: true,
- defaultSortOrder: mapOrderByToSortOrder('wait', orderBy),
- align: 'right',
- },
- {
- title: <div className="column-header-right">Load Avg</div>,
- dataIndex: 'load15',
- key: 'load15',
- width: 100,
- sorter: true,
- defaultSortOrder: mapOrderByToSortOrder('load15', orderBy),
- align: 'right',
- },
-];
-
-export const formatDataForTable = (data: HostData[]): HostRowData[] =>
- data.map((host, index) => ({
- key: `${host.hostName}-${index}`,
- hostName: host.hostName || '',
- active: (
- <Tag
- bordered
- className={`infra-monitoring-tags ${host.active ? 'active' : 'inactive'}`}
- >
- {host.active ? 'ACTIVE' : 'INACTIVE'}
- </Tag>
- ),
- cpu: (
- <div className="progress-container">
- <Progress
- percent={Number((host.cpu * 100).toFixed(1))}
- strokeLinecap="butt"
- size="small"
- strokeColor={((): string => {
- const cpuPercent = Number((host.cpu * 100).toFixed(1));
- if (cpuPercent >= 90) {
- return Color.BG_SAKURA_500;
- }
- if (cpuPercent >= 60) {
- return Color.BG_AMBER_500;
- }
- return Color.BG_FOREST_500;
- })()}
- className="progress-bar"
- />
- </div>
- ),
- memory: (
- <div className="progress-container">
- <Progress
- percent={Number((host.memory * 100).toFixed(1))}
- strokeLinecap="butt"
- size="small"
- strokeColor={((): string => {
- const memoryPercent = Number((host.memory * 100).toFixed(1));
- if (memoryPercent >= 90) {
- return Color.BG_CHERRY_500;
- }
- if (memoryPercent >= 60) {
- return Color.BG_AMBER_500;
- }
- return Color.BG_FOREST_500;
- })()}
- className="progress-bar"
- />
- </div>
- ),
- wait: `${Number((host.wait * 100).toFixed(1))}%`,
- load15: host.load15,
- }));
-
export const HostsQuickFiltersConfig: IQuickFiltersConfig[] = [
{
type: FiltersType.CHECKBOX,
@@ -299,13 +101,11 @@ export const HostsQuickFiltersConfig: IQuickFiltersConfig[] = [
},
];
-export function GetHostsQuickFiltersConfig(
+export function getHostsQuickFiltersConfig(
dotMetricsEnabled: boolean,
): IQuickFiltersConfig[] {
- // These keys don’t change with dotMetricsEnabled
const hostNameKey = dotMetricsEnabled ? 'host.name' : 'host_name';
const osTypeKey = dotMetricsEnabled ? 'os.type' : 'os_type';
- // This metric stays the same regardless of notation
const metricName = dotMetricsEnabled
? 'system.cpu.load_average.15m'
: 'system_cpu_load_average_15m';
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/K8sBaseDetails.tsx b/frontend/src/container/InfraMonitoringK8s/Base/K8sBaseDetails.tsx
new file mode 100644
index 0000000000..4d37a6fcc0
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/K8sBaseDetails.tsx
@@ -0,0 +1,860 @@
+import React, {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import { useQuery } from 'react-query';
+// eslint-disable-next-line no-restricted-imports
+import { Color, Spacing } from '@signozhq/design-tokens';
+import { Button, Divider, Drawer, Radio, Tooltip, Typography } from 'antd';
+import type { RadioChangeEvent } from 'antd/lib';
+import logEvent from 'api/common/logEvent';
+import { InfraMonitoringEvents } from 'constants/events';
+import { QueryParams } from 'constants/query';
+import {
+ initialQueryBuilderFormValuesMap,
+ initialQueryState,
+} from 'constants/queryBuilder';
+import ROUTES from 'constants/routes';
+import { DEFAULT_TIME_RANGE } from 'container/TopNav/DateTimeSelectionV2/constants';
+import {
+ CustomTimeType,
+ Time,
+} from 'container/TopNav/DateTimeSelectionV2/types';
+import { useIsDarkMode } from 'hooks/useDarkMode';
+import useUrlQuery from 'hooks/useUrlQuery';
+import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
+import GetMinMax from 'lib/getMinMax';
+import {
+ BarChart2,
+ ChevronsLeftRight,
+ Compass,
+ DraftingCompass,
+ Package2,
+ ScrollText,
+ X,
+} from 'lucide-react';
+import { isCustomTimeRange, useGlobalTimeStore } from 'store/globalTime';
+import {
+ getAutoRefreshQueryKey,
+ NANO_SECOND_MULTIPLIER,
+} from 'store/globalTime/utils';
+import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import {
+ IBuilderQuery,
+ TagFilter,
+ TagFilterItem,
+} from 'types/api/queryBuilder/queryBuilderData';
+import {
+ LogsAggregatorOperator,
+ TracesAggregatorOperator,
+} from 'types/common/queryBuilder';
+import { v4 as uuidv4 } from 'uuid';
+
+import { filterDuplicateFilters } from '../commonUtils';
+import { InfraMonitoringEntity, VIEW_TYPES, VIEWS } from '../constants';
+import EntityContainers from '../EntityDetailsUtils/EntityContainers';
+import EntityEvents from '../EntityDetailsUtils/EntityEvents';
+import EntityLogs from '../EntityDetailsUtils/EntityLogs';
+import EntityMetrics from '../EntityDetailsUtils/EntityMetrics';
+import EntityProcesses from '../EntityDetailsUtils/EntityProcesses';
+import EntityTraces from '../EntityDetailsUtils/EntityTraces';
+import { QUERY_KEYS } from '../EntityDetailsUtils/utils';
+import {
+ useInfraMonitoringEventsFilters,
+ useInfraMonitoringLogFilters,
+ useInfraMonitoringSelectedItem,
+ useInfraMonitoringTracesFilters,
+ useInfraMonitoringView,
+} from '../hooks';
+import LoadingContainer from '../LoadingContainer';
+
+import '../EntityDetailsUtils/entityDetails.styles.scss';
+
+const TimeRangeOffset = 1000000000;
+
+export interface K8sDetailsMetadataConfig<T> {
+ label: string;
+ getValue: (entity: T) => string | number;
+ render?: (value: string | number, entity: T) => React.ReactNode;
+}
+
+export interface K8sDetailsFilters {
+ filters: TagFilter;
+ start: number;
+ end: number;
+}
+
+export interface K8sBaseDetailsProps<T> {
+ category: InfraMonitoringEntity;
+ eventCategory: string;
+ // Data fetching configuration
+ getSelectedItemFilters: (selectedItem: string) => TagFilter;
+ fetchEntityData: (
+ filters: K8sDetailsFilters,
+ signal?: AbortSignal,
+ ) => Promise<{ data: T | null; error?: string | null }>;
+ // Entity configuration
+ getEntityName: (entity: T) => string;
+ getInitialLogTracesFilters: (entity: T) => TagFilterItem[];
+ getInitialEventsFilters: (entity: T) => TagFilterItem[];
+ primaryFilterKeys: string[];
+ metadataConfig: K8sDetailsMetadataConfig<T>[];
+ entityWidgetInfo: {
+ title: string;
+ yAxisUnit: string;
+ }[];
+ getEntityQueryPayload: (
+ entity: T,
+ start: number,
+ end: number,
+ dotMetricsEnabled: boolean,
+ ) => GetQueryResultsProps[];
+ queryKeyPrefix: string;
+ /** When true, only metrics are shown and the Metrics/Logs/Traces/Events tab bar is hidden. */
+ hideDetailViewTabs?: boolean;
+ tabsConfig?: {
+ showMetrics?: boolean;
+ showLogs?: boolean;
+ showTraces?: boolean;
+ showEvents?: boolean;
+ showContainers?: boolean;
+ showProcesses?: boolean;
+ };
+ customTabs?: Array<{
+ key: string;
+ label: string;
+ icon: React.ReactNode;
+ render: (props: {
+ entity: T;
+ timeRange: { startTime: number; endTime: number };
+ selectedInterval: Time;
+ handleTimeChange: (
+ interval: Time | CustomTimeType,
+ dateTimeRange?: [number, number],
+ ) => void;
+ }) => React.ReactNode;
+ }>;
+}
+
+export function createFilterItem(
+ key: string,
+ value: string,
+ dataType: DataTypes = DataTypes.String,
+): TagFilterItem {
+ return {
+ id: uuidv4(),
+ key: {
+ key,
+ dataType,
+ type: 'resource',
+ id: `${key}--string--resource--false`,
+ },
+ op: '=',
+ value,
+ };
+}
+
+// eslint-disable-next-line sonarjs/cognitive-complexity
+function K8sBaseDetails<T>({
+ category,
+ eventCategory,
+ getSelectedItemFilters,
+ fetchEntityData,
+ getEntityName,
+ getInitialLogTracesFilters,
+ getInitialEventsFilters,
+ primaryFilterKeys,
+ metadataConfig,
+ entityWidgetInfo,
+ getEntityQueryPayload,
+ queryKeyPrefix,
+ hideDetailViewTabs = false,
+ tabsConfig,
+ customTabs,
+}: K8sBaseDetailsProps<T>): JSX.Element {
+ const tabVisibility = useMemo(
+ () => ({
+ showMetrics: true,
+ showLogs: true,
+ showTraces: true,
+ showEvents: true,
+ showContainers: false,
+ showProcesses: false,
+ ...tabsConfig,
+ }),
+ [tabsConfig],
+ );
+
+ const selectedTime = useGlobalTimeStore((s) => s.selectedTime);
+ const getMinMaxTime = useGlobalTimeStore((s) => s.getMinMaxTime);
+
+ const { startMs, endMs } = useMemo(() => {
+ const { minTime: startNs, maxTime: endNs } = getMinMaxTime(selectedTime);
+
+ return {
+ startMs: Math.floor(startNs / NANO_SECOND_MULTIPLIER),
+ endMs: Math.floor(endNs / NANO_SECOND_MULTIPLIER),
+ };
+ }, [getMinMaxTime, selectedTime]);
+
+ const [modalTimeRange, setModalTimeRange] = useState(() => ({
+ startTime: startMs,
+ endTime: endMs,
+ }));
+
+ // TODO(h4ad): Remove this and use context/zustand
+ const lastSelectedInterval = useRef<Time | null>(null);
+ const [selectedInterval, setSelectedInterval] = useState<Time>(
+ lastSelectedInterval.current
+ ? lastSelectedInterval.current
+ : isCustomTimeRange(selectedTime)
+ ? DEFAULT_TIME_RANGE
+ : selectedTime,
+ );
+
+ const [selectedView, setSelectedView] = useInfraMonitoringView();
+ const effectiveView = hideDetailViewTabs ? VIEW_TYPES.METRICS : selectedView;
+
+ const [logFiltersParam, setLogFiltersParam] = useInfraMonitoringLogFilters();
+ const [
+ tracesFiltersParam,
+ setTracesFiltersParam,
+ ] = useInfraMonitoringTracesFilters();
+ const [
+ eventsFiltersParam,
+ setEventsFiltersParam,
+ ] = useInfraMonitoringEventsFilters();
+ const isDarkMode = useIsDarkMode();
+
+ const [selectedItem, setSelectedItem] = useInfraMonitoringSelectedItem();
+ const urlQuery = useUrlQuery();
+
+ useEffect(() => {
+ if (
+ hideDetailViewTabs &&
+ selectedItem &&
+ selectedView !== VIEW_TYPES.METRICS
+ ) {
+ setSelectedView(VIEW_TYPES.METRICS);
+ }
+ }, [hideDetailViewTabs, selectedItem, selectedView, setSelectedView]);
+
+ const entityQueryKey = useMemo(
+ () =>
+ getAutoRefreshQueryKey(
+ selectedTime,
+ `${queryKeyPrefix}EntityDetails`,
+ selectedItem,
+ ),
+ [queryKeyPrefix, selectedItem, selectedTime],
+ );
+
+ const {
+ data: entityResponse,
+ isLoading: isEntityLoading,
+ isError: isEntityError,
+ } = useQuery({
+ queryKey: entityQueryKey,
+ queryFn: ({ signal }) => {
+ if (!selectedItem) {
+ return { data: null };
+ }
+ const filters = getSelectedItemFilters(selectedItem);
+ const { minTime, maxTime } = getMinMaxTime();
+
+ return fetchEntityData(
+ {
+ filters,
+ start: Math.floor(minTime / NANO_SECOND_MULTIPLIER),
+ end: Math.floor(maxTime / NANO_SECOND_MULTIPLIER),
+ },
+ signal,
+ );
+ },
+ enabled: !!selectedItem,
+ });
+
+ const entity = entityResponse?.data ?? null;
+
+ const initialFilters = useMemo(() => {
+ const filters =
+ effectiveView === VIEW_TYPES.LOGS ? logFiltersParam : tracesFiltersParam;
+ if (filters) {
+ return filters;
+ }
+ if (!entity) {
+ return { op: 'AND', items: [] };
+ }
+ return {
+ op: 'AND',
+ items: getInitialLogTracesFilters(entity),
+ };
+ }, [
+ entity,
+ effectiveView,
+ logFiltersParam,
+ tracesFiltersParam,
+ getInitialLogTracesFilters,
+ ]);
+
+ const initialEventsFilters = useMemo(() => {
+ if (eventsFiltersParam) {
+ return eventsFiltersParam;
+ }
+ if (!entity) {
+ return { op: 'AND', items: [] };
+ }
+ return {
+ op: 'AND',
+ items: getInitialEventsFilters(entity),
+ };
+ }, [entity, eventsFiltersParam, getInitialEventsFilters]);
+
+ const [logsAndTracesFilters, setLogsAndTracesFilters] = useState<
+ IBuilderQuery['filters']
+ >(initialFilters);
+
+ const [eventsFilters, setEventsFilters] = useState<IBuilderQuery['filters']>(
+ initialEventsFilters,
+ );
+
+ useEffect(() => {
+ if (entity) {
+ logEvent(InfraMonitoringEvents.PageVisited, {
+ entity: InfraMonitoringEvents.K8sEntity,
+ page: InfraMonitoringEvents.DetailedPage,
+ category: eventCategory,
+ });
+ }
+ }, [entity, eventCategory]);
+
+ useEffect(() => {
+ setLogsAndTracesFilters(initialFilters);
+ setEventsFilters(initialEventsFilters);
+ }, [initialFilters, initialEventsFilters]);
+
+ useEffect(() => {
+ const currentSelectedInterval = lastSelectedInterval.current || selectedTime;
+ if (!isCustomTimeRange(currentSelectedInterval)) {
+ setSelectedInterval(currentSelectedInterval);
+ const { minTime, maxTime } = getMinMaxTime();
+
+ setModalTimeRange({
+ startTime: Math.floor(minTime / TimeRangeOffset),
+ endTime: Math.floor(maxTime / TimeRangeOffset),
+ });
+ }
+ }, [getMinMaxTime, selectedTime]);
+
+ const handleTabChange = (e: RadioChangeEvent): void => {
+ setSelectedView(e.target.value);
+ setLogFiltersParam(null);
+ setTracesFiltersParam(null);
+ setEventsFiltersParam(null);
+ logEvent(InfraMonitoringEvents.TabChanged, {
+ entity: InfraMonitoringEvents.K8sEntity,
+ page: InfraMonitoringEvents.DetailedPage,
+ category: eventCategory,
+ view: e.target.value,
+ });
+ };
+
+ const handleTimeChange = useCallback(
+ (interval: Time | CustomTimeType, dateTimeRange?: [number, number]): void => {
+ lastSelectedInterval.current = interval as Time;
+ setSelectedInterval(interval as Time);
+
+ if (interval === 'custom' && dateTimeRange) {
+ setModalTimeRange({
+ startTime: Math.floor(dateTimeRange[0] / 1000),
+ endTime: Math.floor(dateTimeRange[1] / 1000),
+ });
+ } else {
+ const { maxTime, minTime } = GetMinMax(interval);
+
+ setModalTimeRange({
+ startTime: Math.floor(minTime / TimeRangeOffset),
+ endTime: Math.floor(maxTime / TimeRangeOffset),
+ });
+ }
+
+ logEvent(InfraMonitoringEvents.TimeUpdated, {
+ entity: InfraMonitoringEvents.K8sEntity,
+ page: InfraMonitoringEvents.DetailedPage,
+ category: eventCategory,
+ interval,
+ view: effectiveView,
+ });
+ },
+ [eventCategory, effectiveView],
+ );
+
+ const handleChangeLogFilters = useCallback(
+ (value: IBuilderQuery['filters'], view: VIEWS) => {
+ setLogsAndTracesFilters((prevFilters) => {
+ const primaryFilters = prevFilters?.items?.filter((item) =>
+ primaryFilterKeys.includes(item.key?.key ?? ''),
+ );
+ const paginationFilter = value?.items?.find(
+ (item) => item.key?.key === 'id',
+ );
+ const newFilters = value?.items?.filter(
+ (item) =>
+ item.key?.key !== 'id' &&
+ !primaryFilterKeys.includes(item.key?.key ?? ''),
+ );
+
+ if (newFilters && newFilters?.length > 0) {
+ logEvent(InfraMonitoringEvents.FilterApplied, {
+ entity: InfraMonitoringEvents.K8sEntity,
+ page: InfraMonitoringEvents.DetailedPage,
+ category: eventCategory,
+ view: selectedView,
+ });
+ }
+
+ const updatedFilters = {
+ op: 'AND',
+ items: filterDuplicateFilters(
+ [
+ ...(primaryFilters || []),
+ ...(newFilters || []),
+ ...(paginationFilter ? [paginationFilter] : []),
+ ].filter((item): item is TagFilterItem => item !== undefined),
+ ),
+ };
+
+ setLogFiltersParam(updatedFilters);
+ setSelectedView(view);
+
+ return updatedFilters;
+ });
+ },
+ [
+ setLogFiltersParam,
+ setSelectedView,
+ primaryFilterKeys,
+ eventCategory,
+ selectedView,
+ ],
+ );
+
+ const handleChangeTracesFilters = useCallback(
+ (value: IBuilderQuery['filters'], view: VIEWS) => {
+ setLogsAndTracesFilters((prevFilters) => {
+ const primaryFilters = prevFilters?.items?.filter((item) =>
+ primaryFilterKeys.includes(item.key?.key ?? ''),
+ );
+
+ if (value?.items && value?.items?.length > 0) {
+ logEvent(InfraMonitoringEvents.FilterApplied, {
+ entity: InfraMonitoringEvents.K8sEntity,
+ page: InfraMonitoringEvents.DetailedPage,
+ category: eventCategory,
+ view: selectedView,
+ });
+ }
+
+ const updatedFilters = {
+ op: 'AND',
+ items: filterDuplicateFilters(
+ [
+ ...(primaryFilters || []),
+ ...(value?.items?.filter(
+ (item) => !primaryFilterKeys.includes(item.key?.key ?? ''),
+ ) || []),
+ ].filter((item): item is TagFilterItem => item !== undefined),
+ ),
+ };
+
+ setTracesFiltersParam(updatedFilters);
+ setSelectedView(view);
+
+ return updatedFilters;
+ });
+ },
+ [
+ setTracesFiltersParam,
+ setSelectedView,
+ primaryFilterKeys,
+ eventCategory,
+ selectedView,
+ ],
+ );
+
+ const handleChangeEventsFilters = useCallback(
+ (value: IBuilderQuery['filters'], view: VIEWS) => {
+ setEventsFilters((prevFilters) => {
+ const kindFilter = prevFilters?.items?.find(
+ (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_KIND,
+ );
+ const nameFilter = prevFilters?.items?.find(
+ (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_NAME,
+ );
+
+ if (value?.items && value?.items?.length > 0) {
+ logEvent(InfraMonitoringEvents.FilterApplied, {
+ entity: InfraMonitoringEvents.K8sEntity,
+ page: InfraMonitoringEvents.DetailedPage,
+ category: eventCategory,
+ view: selectedView,
+ });
+ }
+
+ const updatedFilters = {
+ op: 'AND',
+ items: filterDuplicateFilters(
+ [
+ kindFilter,
+ nameFilter,
+ ...(value?.items?.filter(
+ (item) =>
+ item.key?.key !== QUERY_KEYS.K8S_OBJECT_KIND &&
+ item.key?.key !== QUERY_KEYS.K8S_OBJECT_NAME,
+ ) || []),
+ ].filter((item): item is TagFilterItem => item !== undefined),
+ ),
+ };
+
+ setEventsFiltersParam(updatedFilters);
+ setSelectedView(view);
+
+ return updatedFilters;
+ });
+ },
+ [eventCategory, selectedView, setEventsFiltersParam, setSelectedView],
+ );
+
+ const handleExplorePagesRedirect = (): void => {
+ if (selectedInterval !== 'custom') {
+ urlQuery.set(QueryParams.relativeTime, selectedInterval);
+ } else {
+ urlQuery.delete(QueryParams.relativeTime);
+ urlQuery.set(QueryParams.startTime, modalTimeRange.startTime.toString());
+ urlQuery.set(QueryParams.endTime, modalTimeRange.endTime.toString());
+ }
+
+ logEvent(InfraMonitoringEvents.ExploreClicked, {
+ entity: InfraMonitoringEvents.K8sEntity,
+ page: InfraMonitoringEvents.DetailedPage,
+ category: eventCategory,
+ view: selectedView,
+ });
+
+ if (selectedView === VIEW_TYPES.LOGS) {
+ const filtersWithoutPagination = {
+ ...logsAndTracesFilters,
+ items:
+ logsAndTracesFilters?.items?.filter((item) => item.key?.key !== 'id') ||
+ [],
+ };
+
+ const compositeQuery = {
+ ...initialQueryState,
+ queryType: 'builder',
+ builder: {
+ ...initialQueryState.builder,
+ queryData: [
+ {
+ ...initialQueryBuilderFormValuesMap.logs,
+ aggregateOperator: LogsAggregatorOperator.NOOP,
+ filters: filtersWithoutPagination,
+ },
+ ],
+ },
+ };
+
+ urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
+
+ window.open(
+ `${window.location.origin}${ROUTES.LOGS_EXPLORER}?${urlQuery.toString()}`,
+ '_blank',
+ );
+ } else if (selectedView === VIEW_TYPES.TRACES) {
+ const compositeQuery = {
+ ...initialQueryState,
+ queryType: 'builder',
+ builder: {
+ ...initialQueryState.builder,
+ queryData: [
+ {
+ ...initialQueryBuilderFormValuesMap.traces,
+ aggregateOperator: TracesAggregatorOperator.NOOP,
+ filters: logsAndTracesFilters,
+ },
+ ],
+ },
+ };
+
+ urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
+
+ window.open(
+ `${window.location.origin}${ROUTES.TRACES_EXPLORER}?${urlQuery.toString()}`,
+ '_blank',
+ );
+ }
+ };
+
+ const handleClose = (): void => {
+ lastSelectedInterval.current = null;
+
+ setSelectedItem(null);
+ setSelectedView(null);
+ setTracesFiltersParam(null);
+ setEventsFiltersParam(null);
+ setLogFiltersParam(null);
+ };
+
+ const entityName = entity ? getEntityName(entity) : '';
+
+ return (
+ <Drawer
+ width="70%"
+ title={
+ <>
+ <Divider type="vertical" />
+ <Typography.Text className="title">{entityName}</Typography.Text>
+ </>
+ }
+ placement="right"
+ onClose={handleClose}
+ open={!!selectedItem}
+ style={{
+ overscrollBehavior: 'contain',
+ background: isDarkMode ? Color.BG_INK_400 : Color.BG_VANILLA_100,
+ }}
+ className="entity-detail-drawer"
+ destroyOnClose
+ closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
+ >
+ {isEntityLoading && <LoadingContainer />}
+ {isEntityError && (
+ <Typography.Text type="danger">
+ {entityResponse?.error || 'Failed to load entity details'}
+ </Typography.Text>
+ )}
+ {entity && !isEntityLoading && (
+ <>
+ <div className="entity-detail-drawer__entity">
+ <div className="entity-details-grid">
+ <div className="labels-row">
+ {metadataConfig.map((config) => (
+ <Typography.Text
+ key={config.label}
+ type="secondary"
+ className="entity-details-metadata-label"
+ >
+ {config.label}
+ </Typography.Text>
+ ))}
+ </div>
+
+ <div className="values-row">
+ {metadataConfig.map((config) => {
+ const value = config.getValue(entity);
+ const displayValue = String(value);
+ return (
+ <Typography.Text
+ key={config.label}
+ className="entity-details-metadata-value"
+ >
+ {config.render ? (
+ config.render(value, entity)
+ ) : (
+ <Tooltip title={displayValue}>{displayValue}</Tooltip>
+ )}
+ </Typography.Text>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+
+ {!hideDetailViewTabs && (
+ <div className="views-tabs-container">
+ <Radio.Group
+ className="views-tabs"
+ onChange={handleTabChange}
+ value={selectedView}
+ >
+ {tabVisibility.showMetrics && (
+ <Radio.Button
+ className={
+ selectedView === VIEW_TYPES.METRICS ? 'selected_view tab' : 'tab'
+ }
+ value={VIEW_TYPES.METRICS}
+ >
+ <div className="view-title">
+ <BarChart2 size={14} />
+ Metrics
+ </div>
+ </Radio.Button>
+ )}
+ {tabVisibility.showLogs && (
+ <Radio.Button
+ className={
+ selectedView === VIEW_TYPES.LOGS ? 'selected_view tab' : 'tab'
+ }
+ value={VIEW_TYPES.LOGS}
+ >
+ <div className="view-title">
+ <ScrollText size={14} />
+ Logs
+ </div>
+ </Radio.Button>
+ )}
+ {tabVisibility.showTraces && (
+ <Radio.Button
+ className={
+ selectedView === VIEW_TYPES.TRACES ? 'selected_view tab' : 'tab'
+ }
+ value={VIEW_TYPES.TRACES}
+ >
+ <div className="view-title">
+ <DraftingCompass size={14} />
+ Traces
+ </div>
+ </Radio.Button>
+ )}
+ {tabVisibility.showEvents && (
+ <Radio.Button
+ className={
+ selectedView === VIEW_TYPES.EVENTS ? 'selected_view tab' : 'tab'
+ }
+ value={VIEW_TYPES.EVENTS}
+ >
+ <div className="view-title">
+ <ChevronsLeftRight size={14} />
+ Events
+ </div>
+ </Radio.Button>
+ )}
+ {tabVisibility.showContainers && (
+ <Radio.Button
+ className={
+ selectedView === VIEW_TYPES.CONTAINERS ? 'selected_view tab' : 'tab'
+ }
+ value={VIEW_TYPES.CONTAINERS}
+ >
+ <div className="view-title">
+ <Package2 size={14} />
+ Containers
+ </div>
+ </Radio.Button>
+ )}
+ {tabVisibility.showProcesses && (
+ <Radio.Button
+ className={
+ selectedView === VIEW_TYPES.PROCESSES ? 'selected_view tab' : 'tab'
+ }
+ value={VIEW_TYPES.PROCESSES}
+ >
+ <div className="view-title">
+ <ChevronsLeftRight size={14} />
+ Processes
+ </div>
+ </Radio.Button>
+ )}
+ {customTabs?.map((tab) => (
+ <Radio.Button
+ key={tab.key}
+ className={selectedView === tab.key ? 'selected_view tab' : 'tab'}
+ value={tab.key}
+ >
+ <div className="view-title">
+ {tab.icon}
+ {tab.label}
+ </div>
+ </Radio.Button>
+ ))}
+ </Radio.Group>
+
+ {(selectedView === VIEW_TYPES.LOGS ||
+ selectedView === VIEW_TYPES.TRACES) && (
+ <Button
+ icon={<Compass size={18} />}
+ className="compass-button"
+ onClick={handleExplorePagesRedirect}
+ />
+ )}
+ </div>
+ )}
+
+ {effectiveView === VIEW_TYPES.METRICS && (
+ <EntityMetrics<T>
+ entity={entity}
+ selectedInterval={selectedInterval}
+ timeRange={modalTimeRange}
+ handleTimeChange={handleTimeChange}
+ isModalTimeSelection
+ entityWidgetInfo={entityWidgetInfo}
+ getEntityQueryPayload={getEntityQueryPayload}
+ category={category}
+ queryKey={`${queryKeyPrefix}Metrics`}
+ />
+ )}
+ {effectiveView === VIEW_TYPES.LOGS && (
+ <EntityLogs
+ timeRange={modalTimeRange}
+ isModalTimeSelection
+ handleTimeChange={handleTimeChange}
+ handleChangeLogFilters={handleChangeLogFilters}
+ logFilters={logsAndTracesFilters}
+ selectedInterval={selectedInterval}
+ queryKeyFilters={primaryFilterKeys}
+ queryKey={`${queryKeyPrefix}Logs`}
+ category={category}
+ />
+ )}
+ {effectiveView === VIEW_TYPES.TRACES && (
+ <EntityTraces
+ timeRange={modalTimeRange}
+ isModalTimeSelection
+ handleTimeChange={handleTimeChange}
+ handleChangeTracesFilters={handleChangeTracesFilters}
+ tracesFilters={logsAndTracesFilters}
+ selectedInterval={selectedInterval}
+ queryKey={`${queryKeyPrefix}Traces`}
+ category={eventCategory}
+ queryKeyFilters={primaryFilterKeys}
+ />
+ )}
+ {effectiveView === VIEW_TYPES.EVENTS && tabVisibility.showEvents && (
+ <EntityEvents
+ timeRange={modalTimeRange}
+ isModalTimeSelection
+ handleTimeChange={handleTimeChange}
+ handleChangeEventFilters={handleChangeEventsFilters}
+ filters={eventsFilters}
+ selectedInterval={selectedInterval}
+ category={category}
+ queryKey={`${queryKeyPrefix}Events`}
+ />
+ )}
+ {effectiveView === VIEW_TYPES.CONTAINERS &&
+ tabVisibility.showContainers && <EntityContainers />}
+ {effectiveView === VIEW_TYPES.PROCESSES && tabVisibility.showProcesses && (
+ <EntityProcesses />
+ )}
+ {customTabs?.map((tab) =>
+ selectedView === tab.key ? (
+ <React.Fragment key={tab.key}>
+ {tab.render({
+ entity,
+ timeRange: modalTimeRange,
+ selectedInterval,
+ handleTimeChange,
+ })}
+ </React.Fragment>
+ ) : null,
+ )}
+ </>
+ )}
+ </Drawer>
+ );
+}
+
+export default K8sBaseDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/K8sBaseList.module.scss b/frontend/src/container/InfraMonitoringK8s/Base/K8sBaseList.module.scss
new file mode 100644
index 0000000000..bbb1babd8a
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/K8sBaseList.module.scss
@@ -0,0 +1,173 @@
+.clickableRow {
+ cursor: pointer;
+}
+
+.k8SListTable {
+ --k8s-base-list-pagination-offset: 64px;
+
+ display: flex;
+ flex-direction: column;
+
+ :global(.ant-spin-nested-loading) {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ }
+
+ :global(.ant-spin-container) {
+ position: relative;
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ padding-bottom: var(--k8s-base-list-pagination-offset);
+ }
+
+ :global(.ant-table-container) {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ }
+
+ :global(.ant-table-header) {
+ flex-shrink: 0;
+ }
+
+ :global(.ant-table-body) {
+ flex: 1;
+ min-height: 0;
+ overflow: auto !important;
+ }
+
+ :global(.ant-table) {
+ flex: 1;
+ background: var(--l1-background) !important;
+
+ :global(.ant-table-thead > tr > th) {
+ padding: 12px;
+ font-weight: 500;
+ font-size: 12px;
+ line-height: 18px;
+
+ border-bottom: none;
+
+ color: var(--l2-foreground);
+ font-family: Inter;
+ font-size: 11px;
+ font-style: normal;
+ font-weight: 600;
+ line-height: 18px;
+ letter-spacing: 0.44px;
+ text-transform: uppercase;
+ background: var(--l1-background) !important;
+
+ &::before {
+ background: transparent !important;
+ }
+ }
+
+ :global(.ant-table-cell) {
+ padding: 12px;
+ font-size: 13px;
+ line-height: 20px;
+ color: var(--l1-foreground);
+ background: var(--l1-background);
+ border-bottom: none;
+
+ &:before,
+ &:after {
+ display: none;
+ }
+ }
+
+ :global(.progress-container) {
+ :global(.ant-progress-bg) {
+ height: 8px !important;
+ border-radius: 4px;
+ }
+ }
+
+ :global(.ant-table-tbody > tr:hover > td) {
+ background: var(--l1-background-hover);
+ }
+
+ :global(.ant-table-tbody > tr:not(.ant-table-expanded-row):hover > td) {
+ background: var(--l1-background-hover) !important;
+ }
+
+ :global(.ant-table-tbody > tr.ant-table-expanded-row:hover > td) {
+ background: var(--l1-background);
+ }
+
+ :global(.ant-table-tbody > tr > td) {
+ border-bottom: none;
+ }
+
+ :global(.ant-empty-normal) {
+ visibility: hidden;
+ }
+
+ :global(.ant-table-cell) {
+ min-width: 180px !important;
+ max-width: 180px !important;
+ }
+
+ :global(.ant-table-cell:first-of-type):not(:global(.ant-table-row-expand-icon-cell)) {
+ min-width: 250px !important;
+ max-width: 250px !important;
+ }
+
+ :global(.ant-table-row-expand-icon-cell) {
+ min-width: 40px !important;
+ max-width: 40px !important;
+ }
+
+ :global(.ant-table-content) {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+
+ &::-webkit-scrollbar {
+ width: 4px;
+ height: 4px;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: var(--accent-primary);
+ }
+
+ &::-webkit-scrollbar-thumb:hover {
+ background: color-mix(var(--accent-primary), transparent 40%);
+ }
+ }
+ }
+}
+
+.paginationDock {
+ position: fixed;
+ bottom: 0;
+ right: 0;
+ width: calc(100% - 340px) !important;
+ margin: 0 !important;
+ padding: 16px;
+ background-color: var(--l1-background);
+ z-index: 1;
+
+ :global(.ant-pagination-item) {
+ border-radius: 4px;
+ }
+
+ :global(.ant-pagination-item-active) {
+ background: var(--l2-background);
+ border-color: var(--l2-border);
+
+ a {
+ color: var(--l1-foreground) !important;
+ }
+ }
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/K8sBaseList.tsx b/frontend/src/container/InfraMonitoringK8s/Base/K8sBaseList.tsx
new file mode 100644
index 0000000000..998dbd4eec
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/K8sBaseList.tsx
@@ -0,0 +1,437 @@
+import React, { useCallback, useEffect, useMemo, useState } from 'react';
+import { useQuery } from 'react-query';
+// eslint-disable-next-line no-restricted-imports
+import { LoadingOutlined } from '@ant-design/icons';
+import {
+ Button,
+ Spin,
+ Table,
+ TableColumnType as ColumnType,
+ TablePaginationConfig,
+ TableProps,
+} from 'antd';
+import type { SorterResult } from 'antd/es/table/interface';
+import logEvent from 'api/common/logEvent';
+import { InfraMonitoringEvents } from 'constants/events';
+import { ChevronDown, ChevronRight } from 'lucide-react';
+import { parseAsString, useQueryState } from 'nuqs';
+import { useGlobalTimeStore } from 'store/globalTime';
+import {
+ getAutoRefreshQueryKey,
+ NANO_SECOND_MULTIPLIER,
+} from 'store/globalTime/utils';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { buildAbsolutePath, isModifierKeyPressed } from 'utils/app';
+import { openInNewTab } from 'utils/navigation';
+
+import { InfraMonitoringEntity } from '../constants';
+import {
+ useInfraMonitoringCurrentPage,
+ useInfraMonitoringFilters,
+ useInfraMonitoringGroupBy,
+ useInfraMonitoringOrderBy,
+} from '../hooks';
+import { usePageSize } from '../utils';
+import { K8sEmptyState } from './K8sEmptyState';
+import { K8sExpandedRow } from './K8sExpandedRow';
+import K8sHeader from './K8sHeader';
+import { K8sBaseFilters, K8sRenderedRowData } from './types';
+import {
+ IEntityColumn,
+ useInfraMonitoringTableColumnsForPage,
+ useInfraMonitoringTableColumnsStore,
+} from './useInfraMonitoringTableColumnsStore';
+
+import styles from './K8sBaseList.module.scss';
+
+export type K8sBaseListEmptyStateContext = {
+ isError: boolean;
+ error?: string | null;
+ totalCount: number;
+ hasFilters: boolean;
+ isLoading: boolean;
+ rawData?: unknown;
+};
+
+export type K8sBaseListProps<T = unknown> = {
+ controlListPrefix?: React.ReactNode;
+ entity: InfraMonitoringEntity;
+ tableColumnsDefinitions: IEntityColumn[];
+ tableColumns: ColumnType<K8sRenderedRowData>[];
+ fetchListData: (
+ filters: K8sBaseFilters,
+ signal?: AbortSignal,
+ ) => Promise<{
+ data: T[];
+ total: number;
+ error?: string | null;
+ rawData?: unknown;
+ }>;
+ renderRowData: (
+ record: T,
+ groupBy: BaseAutocompleteData[],
+ ) => K8sRenderedRowData;
+ eventCategory: InfraMonitoringEvents;
+ renderEmptyState?: (
+ context: K8sBaseListEmptyStateContext,
+ ) => React.ReactNode | null;
+};
+
+export function K8sBaseList<T>({
+ controlListPrefix,
+ entity,
+ tableColumnsDefinitions,
+ tableColumns,
+ fetchListData,
+ renderRowData,
+ eventCategory,
+ renderEmptyState,
+}: K8sBaseListProps<T>): JSX.Element {
+ const [queryFilters] = useInfraMonitoringFilters();
+ const [currentPage, setCurrentPage] = useInfraMonitoringCurrentPage();
+ const [groupBy] = useInfraMonitoringGroupBy();
+ const [orderBy, setOrderBy] = useInfraMonitoringOrderBy();
+ const [initialOrderBy] = useState(orderBy);
+ const [selectedItem, setSelectedItem] = useQueryState(
+ 'selectedItem',
+ parseAsString,
+ );
+
+ const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
+ useEffect(() => {
+ setExpandedRowKeys([]);
+ }, [groupBy, currentPage]);
+ const { pageSize, setPageSize } = usePageSize(entity);
+
+ const initializeTableColumns = useInfraMonitoringTableColumnsStore(
+ (state) => state.initializePageColumns,
+ );
+ useEffect(() => {
+ initializeTableColumns(entity, tableColumnsDefinitions);
+ }, [initializeTableColumns, entity, tableColumnsDefinitions]);
+
+ const selectedTime = useGlobalTimeStore((s) => s.selectedTime);
+ const refreshInterval = useGlobalTimeStore((s) => s.refreshInterval);
+ const isRefreshEnabled = useGlobalTimeStore((s) => s.isRefreshEnabled);
+ const getMinMaxTime = useGlobalTimeStore((s) => s.getMinMaxTime);
+
+ const queryKey = useMemo(() => {
+ return getAutoRefreshQueryKey(
+ selectedTime,
+ 'k8sBaseList',
+ entity,
+ String(pageSize),
+ String(currentPage),
+ JSON.stringify(queryFilters),
+ JSON.stringify(orderBy),
+ JSON.stringify(groupBy),
+ );
+ }, [
+ selectedTime,
+ entity,
+ pageSize,
+ currentPage,
+ queryFilters,
+ orderBy,
+ groupBy,
+ ]);
+
+ const { data, isLoading, isError } = useQuery({
+ queryKey,
+ queryFn: ({ signal }) => {
+ const { minTime, maxTime } = getMinMaxTime();
+
+ return fetchListData(
+ {
+ limit: pageSize,
+ offset: (currentPage - 1) * pageSize,
+ filters: queryFilters || { items: [], op: 'AND' },
+ start: Math.floor(minTime / NANO_SECOND_MULTIPLIER),
+ end: Math.floor(maxTime / NANO_SECOND_MULTIPLIER),
+ orderBy: orderBy || undefined,
+ groupBy: groupBy?.length > 0 ? groupBy : undefined,
+ },
+ signal,
+ );
+ },
+ refetchInterval: isRefreshEnabled ? refreshInterval : false,
+ });
+
+ const pageData = data?.data;
+ const totalCount = data?.total || 0;
+ const hasFilters = (queryFilters?.items?.length ?? 0) > 0;
+
+ const formattedItemsData = useMemo(() => {
+ if (!pageData) {
+ return undefined;
+ }
+
+ const rows = pageData.map((item) => renderRowData(item, groupBy));
+
+ // Without handling duplicated keys, the table became unpredictable/unstable
+ const keyCount = new Map<string, number>();
+ return rows.map(
+ // eslint-disable-next-line sonarjs/no-identical-functions
+ (row): K8sRenderedRowData => {
+ const count = keyCount.get(row.key) || 0;
+ keyCount.set(row.key, count + 1);
+
+ if (count > 0) {
+ return { ...row, key: `${row.key}-${count}` };
+ }
+ return row;
+ },
+ );
+ }, [pageData, renderRowData, groupBy]);
+
+ const handleTableChange: TableProps<K8sRenderedRowData>['onChange'] = useCallback(
+ (
+ pagination: TablePaginationConfig,
+ _filters: Record<string, (string | number | boolean)[] | null>,
+ sorter:
+ | SorterResult<K8sRenderedRowData>
+ | SorterResult<K8sRenderedRowData>[],
+ ): void => {
+ if (pagination.current) {
+ setCurrentPage(pagination.current);
+ logEvent(InfraMonitoringEvents.PageNumberChanged, {
+ entity: InfraMonitoringEvents.K8sEntity,
+ page: InfraMonitoringEvents.ListPage,
+ category: eventCategory,
+ });
+ }
+
+ if ('field' in sorter && sorter.order) {
+ setOrderBy({
+ columnName: sorter.field as string,
+ order: (sorter.order === 'ascend' ? 'asc' : 'desc') as 'asc' | 'desc',
+ });
+ } else {
+ setOrderBy(null);
+ }
+ },
+ [eventCategory, setCurrentPage, setOrderBy],
+ );
+
+ useEffect(() => {
+ logEvent(InfraMonitoringEvents.PageVisited, {
+ entity: InfraMonitoringEvents.K8sEntity,
+ page: InfraMonitoringEvents.ListPage,
+ category: eventCategory,
+ total: totalCount,
+ });
+ }, [eventCategory, totalCount]);
+
+ const handleGroupByRowClick = (record: K8sRenderedRowData): void => {
+ if (expandedRowKeys.includes(record.key)) {
+ setExpandedRowKeys(expandedRowKeys.filter((key) => key !== record.key));
+ } else {
+ setExpandedRowKeys([record.key]);
+ }
+ };
+
+ const openItemInNewTab = (record: K8sRenderedRowData): void => {
+ const newParams = new URLSearchParams(document.location.search);
+ newParams.set('selectedItem', record.itemKey);
+ openInNewTab(
+ buildAbsolutePath({
+ relativePath: '',
+ urlQueryString: newParams.toString(),
+ }),
+ );
+ };
+
+ const handleRowClick = (
+ record: K8sRenderedRowData,
+ event: React.MouseEvent,
+ ): void => {
+ if (event && isModifierKeyPressed(event)) {
+ openItemInNewTab(record);
+ return;
+ }
+ if (groupBy.length === 0) {
+ setSelectedItem(record.itemKey);
+ } else {
+ handleGroupByRowClick(record);
+ }
+
+ logEvent(InfraMonitoringEvents.ItemClicked, {
+ entity: InfraMonitoringEvents.K8sEntity,
+ page: InfraMonitoringEvents.ListPage,
+ category: eventCategory,
+ });
+ };
+
+ const [
+ columnsDefinitions,
+ columnsHidden,
+ ] = useInfraMonitoringTableColumnsForPage(entity);
+
+ const hiddenColumnIdsOnList = useMemo(
+ () =>
+ columnsDefinitions
+ .filter(
+ (col) =>
+ (groupBy?.length > 0 && col.behavior === 'hidden-on-expand') ||
+ (!groupBy?.length && col.behavior === 'hidden-on-collapse'),
+ )
+ .map((col) => col.id),
+ [columnsDefinitions, groupBy?.length],
+ );
+
+ const mapDefaultSort = useCallback(
+ (
+ tableColumn: ColumnType<K8sRenderedRowData>,
+ ): ColumnType<K8sRenderedRowData> => {
+ if (tableColumn.key === initialOrderBy?.columnName) {
+ return {
+ ...tableColumn,
+ defaultSortOrder: initialOrderBy?.order === 'asc' ? 'ascend' : 'descend',
+ };
+ }
+
+ return tableColumn;
+ },
+ [initialOrderBy?.columnName, initialOrderBy?.order],
+ );
+
+ const columns = useMemo(
+ () =>
+ tableColumns
+ .filter(
+ (c) =>
+ !hiddenColumnIdsOnList.includes(c.key?.toString() || '') &&
+ !columnsHidden.includes(c.key?.toString() || ''),
+ )
+ .map(mapDefaultSort),
+ [columnsHidden, hiddenColumnIdsOnList, mapDefaultSort, tableColumns],
+ );
+
+ const isGroupedByAttribute = groupBy.length > 0;
+
+ const expandedRowRender = (record: K8sRenderedRowData): JSX.Element => (
+ <K8sExpandedRow<T>
+ record={record}
+ entity={entity}
+ tableColumns={tableColumns}
+ fetchListData={fetchListData}
+ renderRowData={renderRowData}
+ />
+ );
+
+ const expandRowIconRenderer = ({
+ expanded,
+ onExpand,
+ record,
+ }: {
+ expanded: boolean;
+ onExpand: (
+ record: K8sRenderedRowData,
+ e: React.MouseEvent<HTMLButtonElement>,
+ ) => void;
+ record: K8sRenderedRowData;
+ }): JSX.Element | null => {
+ if (!isGroupedByAttribute) {
+ return null;
+ }
+
+ return expanded ? (
+ <Button
+ className="periscope-btn ghost"
+ onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
+ onExpand(record, e)
+ }
+ role="button"
+ >
+ <ChevronDown size={14} />
+ </Button>
+ ) : (
+ <Button
+ className="periscope-btn ghost"
+ onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
+ onExpand(record, e)
+ }
+ role="button"
+ >
+ <ChevronRight size={14} />
+ </Button>
+ );
+ };
+
+ const onPaginationChange = (page: number, pageSize: number): void => {
+ setCurrentPage(page);
+ setPageSize(pageSize);
+ logEvent(InfraMonitoringEvents.PageNumberChanged, {
+ entity: InfraMonitoringEvents.K8sEntity,
+ page: InfraMonitoringEvents.ListPage,
+ category: eventCategory,
+ });
+ };
+
+ const showTableLoadingState = isLoading;
+
+ const emptyStateContext: K8sBaseListEmptyStateContext = {
+ isError: isError || !!data?.error,
+ error: data?.error,
+ totalCount,
+ hasFilters,
+ isLoading: showTableLoadingState,
+ rawData: data?.rawData,
+ };
+
+ const emptyTableMessage: React.ReactNode = renderEmptyState?.(
+ emptyStateContext,
+ ) || (
+ <K8sEmptyState
+ isError={emptyStateContext.isError}
+ error={emptyStateContext.error}
+ isLoading={emptyStateContext.isLoading}
+ rawData={emptyStateContext.rawData}
+ />
+ );
+
+ return (
+ <>
+ <K8sHeader
+ controlListPrefix={controlListPrefix}
+ entity={entity}
+ showAutoRefresh={!selectedItem}
+ />
+ <Table
+ className={styles.k8SListTable}
+ dataSource={showTableLoadingState ? [] : formattedItemsData}
+ columns={columns}
+ pagination={{
+ current: currentPage,
+ pageSize,
+ total: totalCount,
+ showSizeChanger: true,
+ hideOnSinglePage: false,
+ onChange: onPaginationChange,
+ className: styles.paginationDock,
+ }}
+ loading={{
+ spinning: showTableLoadingState,
+ indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
+ }}
+ locale={{
+ emptyText: showTableLoadingState ? null : emptyTableMessage,
+ }}
+ scroll={{ x: true }}
+ tableLayout="fixed"
+ onChange={handleTableChange}
+ onRow={(
+ record,
+ ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
+ onClick: (event: React.MouseEvent): void => handleRowClick(record, event),
+ className: styles.clickableRow,
+ })}
+ expandable={{
+ expandedRowRender: isGroupedByAttribute ? expandedRowRender : undefined,
+ expandIcon: expandRowIconRenderer,
+ expandedRowKeys,
+ }}
+ />
+ </>
+ );
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/K8sEmptyState.module.scss b/frontend/src/container/InfraMonitoringK8s/Base/K8sEmptyState.module.scss
new file mode 100644
index 0000000000..7a68268978
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/K8sEmptyState.module.scss
@@ -0,0 +1,55 @@
+.container {
+ height: 30vh;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+}
+
+.content {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: var(--spacing-3);
+ width: fit-content;
+ max-width: 500px;
+ padding: 24px;
+ text-align: center;
+}
+
+.title {
+ font-weight: 500;
+ margin: 0;
+}
+
+.message {
+ max-width: 400px;
+}
+
+.noDataMessage {
+ display: flex;
+ flex-direction: column;
+ gap: var(--spacing-1);
+}
+
+.emptyStateSvg {
+ width: 32px;
+ max-width: 100%;
+}
+
+.eyesEmoji {
+ height: 32px;
+ width: 32px;
+}
+
+.errorIcon {
+ color: var(--bg-cherry-500);
+}
+
+.actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 16px;
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/K8sEmptyState.tsx b/frontend/src/container/InfraMonitoringK8s/Base/K8sEmptyState.tsx
new file mode 100644
index 0000000000..4fbd422569
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/K8sEmptyState.tsx
@@ -0,0 +1,146 @@
+import { useCallback } from 'react';
+import { Button } from '@signozhq/ui';
+import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
+import history from 'lib/history';
+import { AlertTriangle, LifeBuoy } from 'lucide-react';
+
+import emptyStateUrl from '@/assets/Icons/emptyState.svg';
+import eyesEmojiUrl from '@/assets/Images/eyesEmoji.svg';
+
+import { K8sBaseListEmptyStateContext } from './K8sBaseList';
+
+import styles from './K8sEmptyState.module.scss';
+
+export interface K8sListResponseMetadata {
+ sentAnyHostMetricsData?: boolean;
+ isSendingK8SAgentMetrics?: boolean;
+ endTimeBeforeRetention?: boolean;
+}
+
+type K8sEmptyStateProps = Partial<K8sBaseListEmptyStateContext>;
+
+const handleContactSupport = (isCloudUser: boolean): void => {
+ if (isCloudUser) {
+ history.push('/support');
+ } else {
+ window.open('https://signoz.io/slack', '_blank');
+ }
+};
+
+export function K8sEmptyState({
+ isError,
+ error,
+ isLoading,
+ rawData,
+}: K8sEmptyStateProps): JSX.Element | null {
+ const { isCloudUser } = useGetTenantLicense();
+
+ const handleSupport = useCallback(() => {
+ handleContactSupport(isCloudUser);
+ }, [isCloudUser]);
+
+ if (isLoading) {
+ return null;
+ }
+
+ if (isError || error) {
+ return (
+ <div className={styles.container}>
+ <div className={styles.content}>
+ <AlertTriangle size={32} className={styles.errorIcon} />
+ <span className={styles.message}>
+ {error || 'An error occurred while fetching data.'}
+ </span>
+ <p>
+ Our team is getting on top to resolve this. Please reach out to support if
+ the issue persists.
+ </p>
+ <div className={styles.actions}>
+ <Button
+ onClick={handleSupport}
+ variant="solid"
+ color="secondary"
+ prefix={<LifeBuoy size={14} />}
+ >
+ Contact Support
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ const metadata = rawData as K8sListResponseMetadata | undefined;
+
+ if (metadata?.sentAnyHostMetricsData === false) {
+ return (
+ <div className={styles.container}>
+ <div className={styles.content}>
+ <img className={styles.eyesEmoji} src={eyesEmojiUrl} alt="eyes emoji" />
+ <div className={styles.noDataMessage}>
+ <h5 className={styles.title}>No host metrics data received yet</h5>
+ <span className={styles.message}>
+ Please refer to{' '}
+ <a
+ href="https://signoz.io/docs/userguide/hostmetrics/"
+ target="_blank"
+ rel="noreferrer"
+ >
+ our documentation
+ </a>{' '}
+ to learn how to send host metrics.
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ if (metadata?.isSendingK8SAgentMetrics) {
+ return (
+ <div className={styles.container}>
+ <div className={styles.content}>
+ <img className={styles.eyesEmoji} src={eyesEmojiUrl} alt="eyes emoji" />
+ <span className={styles.message}>
+ To see K8s metrics, upgrade to the latest version of SigNoz k8s-infra
+ chart. Please contact support if you need help.
+ </span>
+ </div>
+ </div>
+ );
+ }
+
+ if (metadata?.endTimeBeforeRetention) {
+ return (
+ <div className={styles.container}>
+ <div className={styles.content}>
+ <img className={styles.eyesEmoji} src={eyesEmojiUrl} alt="eyes emoji" />
+ <div className={styles.noDataMessage}>
+ <h5 className={styles.title}>
+ Queried time range is before earliest K8s metrics
+ </h5>
+ <span className={styles.message}>
+ Your requested end time is earlier than the earliest detected time of K8s
+ metrics data, please adjust your end time.
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className={styles.container}>
+ <div className={styles.content}>
+ <img
+ src={emptyStateUrl}
+ alt="empty-state"
+ className={styles.emptyStateSvg}
+ />
+ <span className={styles.message}>
+ This query had no results. Edit your query and try again!
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/K8sExpandedRow.module.scss b/frontend/src/container/InfraMonitoringK8s/Base/K8sExpandedRow.module.scss
new file mode 100644
index 0000000000..24085fdb4c
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/K8sExpandedRow.module.scss
@@ -0,0 +1,28 @@
+.expandedClickableRow {
+ cursor: pointer;
+}
+
+.expandedTableContainer {
+ border: 1px solid var(--l1-border);
+ overflow-x: auto;
+ padding-left: 48px;
+
+ :global(.ant-table-tbody > tr:hover > td) {
+ background: none !important;
+ }
+}
+
+.expandedTableFooter {
+ display: flex;
+ justify-content: flex-start;
+ gap: 8px;
+ padding: 8px;
+ padding-left: 42px;
+ margin-top: 8px;
+}
+
+.viewAllButton {
+ display: flex;
+ align-items: center;
+ gap: var(--spacing-2);
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/K8sExpandedRow.tsx b/frontend/src/container/InfraMonitoringK8s/Base/K8sExpandedRow.tsx
new file mode 100644
index 0000000000..5c35147ccf
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/K8sExpandedRow.tsx
@@ -0,0 +1,250 @@
+import React, { useCallback, useMemo } from 'react';
+import { useQuery } from 'react-query';
+// eslint-disable-next-line no-restricted-imports
+import { LoadingOutlined } from '@ant-design/icons';
+import {
+ Button,
+ Spin,
+ Table,
+ TableColumnType as ColumnType,
+ Typography,
+} from 'antd';
+import { CornerDownRight } from 'lucide-react';
+import { useGlobalTimeStore } from 'store/globalTime';
+import {
+ getAutoRefreshQueryKey,
+ NANO_SECOND_MULTIPLIER,
+} from 'store/globalTime/utils';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+import { buildAbsolutePath, isModifierKeyPressed } from 'utils/app';
+import { openInNewTab } from 'utils/navigation';
+
+import { InfraMonitoringEntity } from '../constants';
+import {
+ useInfraMonitoringCurrentPage,
+ useInfraMonitoringFilters,
+ useInfraMonitoringGroupBy,
+ useInfraMonitoringOrderBy,
+ useInfraMonitoringSelectedItem,
+} from '../hooks';
+import LoadingContainer from '../LoadingContainer';
+import { K8sBaseFilters, K8sRenderedRowData } from './types';
+import { useInfraMonitoringTableColumnsForPage } from './useInfraMonitoringTableColumnsStore';
+
+import styles from './K8sExpandedRow.module.scss';
+
+export type K8sExpandedRowProps<T> = {
+ record: K8sRenderedRowData;
+ entity: InfraMonitoringEntity;
+ tableColumns: ColumnType<K8sRenderedRowData>[];
+ fetchListData: (
+ filters: K8sBaseFilters,
+ signal?: AbortSignal,
+ ) => Promise<{
+ data: T[];
+ total: number;
+ error?: string | null;
+ rawData?: unknown;
+ }>;
+ renderRowData: (
+ record: T,
+ groupBy: BaseAutocompleteData[],
+ ) => K8sRenderedRowData;
+};
+
+export const MAX_ITEMS_TO_FETCH_WHEN_GROUP_BY = 10;
+
+export function K8sExpandedRow<T>({
+ record,
+ entity,
+ tableColumns,
+ fetchListData,
+ renderRowData,
+}: K8sExpandedRowProps<T>): JSX.Element {
+ const [groupBy, setGroupBy] = useInfraMonitoringGroupBy();
+ const [orderBy, setOrderBy] = useInfraMonitoringOrderBy();
+ const [, setCurrentPage] = useInfraMonitoringCurrentPage();
+ const [queryFilters, setFilters] = useInfraMonitoringFilters();
+ const [, setSelectedItem] = useInfraMonitoringSelectedItem();
+
+ const [
+ columnsDefinitions,
+ columnsHidden,
+ ] = useInfraMonitoringTableColumnsForPage(entity);
+
+ const hiddenColumnIdsForNested = useMemo(
+ () =>
+ columnsDefinitions
+ .filter((col) => col.behavior === 'hidden-on-collapse')
+ .map((col) => col.id),
+ [columnsDefinitions],
+ );
+
+ const nestedColumns = useMemo(
+ () =>
+ tableColumns.filter(
+ (c) =>
+ !columnsHidden.includes(c.key?.toString() || '') &&
+ !hiddenColumnIdsForNested.includes(c.key?.toString() || ''),
+ ),
+ [tableColumns, columnsHidden, hiddenColumnIdsForNested],
+ );
+
+ const createFiltersForRecord = useCallback((): NonNullable<
+ IBuilderQuery['filters']
+ > => {
+ const baseFilters: IBuilderQuery['filters'] = {
+ items: [...(queryFilters?.items || [])],
+ op: 'and',
+ };
+
+ const { groupedByMeta } = record;
+
+ for (const key of Object.keys(groupedByMeta)) {
+ baseFilters.items.push({
+ key: {
+ key,
+ type: null,
+ },
+ op: '=',
+ value: groupedByMeta[key],
+ id: key,
+ });
+ }
+
+ return baseFilters;
+ }, [queryFilters?.items, record]);
+
+ const selectedTime = useGlobalTimeStore((s) => s.selectedTime);
+ const refreshInterval = useGlobalTimeStore((s) => s.refreshInterval);
+ const isRefreshEnabled = useGlobalTimeStore((s) => s.isRefreshEnabled);
+ const getMinMaxTime = useGlobalTimeStore((s) => s.getMinMaxTime);
+
+ const queryKey = useMemo(() => {
+ return getAutoRefreshQueryKey(selectedTime, [
+ 'k8sExpandedRow',
+ record.key,
+ JSON.stringify(queryFilters),
+ JSON.stringify(orderBy),
+ ]);
+ }, [selectedTime, record.key, queryFilters, orderBy]);
+
+ const { data, isFetching, isLoading, isError } = useQuery({
+ queryKey,
+ queryFn: ({ signal }) => {
+ const { minTime, maxTime } = getMinMaxTime();
+
+ return fetchListData(
+ {
+ limit: MAX_ITEMS_TO_FETCH_WHEN_GROUP_BY,
+ offset: 0,
+ filters: createFiltersForRecord(),
+ start: Math.floor(minTime / NANO_SECOND_MULTIPLIER),
+ end: Math.floor(maxTime / NANO_SECOND_MULTIPLIER),
+ orderBy: orderBy || undefined,
+ groupBy: undefined,
+ },
+ signal,
+ );
+ },
+ refetchInterval: isRefreshEnabled ? refreshInterval : false,
+ });
+
+ const formattedData = useMemo(() => {
+ if (!data?.data) {
+ return undefined;
+ }
+
+ const rows = data.data.map((item) => renderRowData(item, groupBy));
+
+ // Without handling duplicated keys, the table became unpredictable/unstable
+ const keyCount = new Map<string, number>();
+ return rows.map(
+ (row): K8sRenderedRowData => {
+ const count = keyCount.get(row.key) || 0;
+ keyCount.set(row.key, count + 1);
+
+ if (count > 0) {
+ return { ...row, key: `${row.key}-${count}` };
+ }
+ return row;
+ },
+ );
+ }, [data?.data, renderRowData, groupBy]);
+
+ const openRecordInNewTab = (rowRecord: K8sRenderedRowData): void => {
+ const newParams = new URLSearchParams(document.location.search);
+ newParams.set('selectedItem', rowRecord.itemKey);
+ openInNewTab(
+ buildAbsolutePath({
+ relativePath: '',
+ urlQueryString: newParams.toString(),
+ }),
+ );
+ };
+
+ const handleViewAllClick = (): void => {
+ const filters = createFiltersForRecord();
+ setFilters(filters);
+ setCurrentPage(1);
+ setGroupBy([]);
+ setOrderBy(null);
+ };
+
+ return (
+ <div
+ className={styles.expandedTableContainer}
+ data-testid="expanded-table-container"
+ >
+ {isError && (
+ <Typography>{data?.error?.toString() || 'Something went wrong'}</Typography>
+ )}
+
+ {isFetching || isLoading ? (
+ <LoadingContainer />
+ ) : (
+ <div data-testid="expanded-table">
+ <Table
+ columns={nestedColumns}
+ dataSource={formattedData}
+ pagination={false}
+ scroll={{ x: true }}
+ tableLayout="fixed"
+ showHeader={false}
+ loading={{
+ spinning: isFetching || isLoading,
+ indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
+ }}
+ onRow={(
+ rowRecord: K8sRenderedRowData,
+ ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
+ onClick: (event: React.MouseEvent): void => {
+ if (isModifierKeyPressed(event)) {
+ openRecordInNewTab(rowRecord);
+ return;
+ }
+ setSelectedItem(rowRecord.itemKey);
+ },
+ className: styles.expandedClickableRow,
+ })}
+ />
+
+ {data?.total && data?.total > MAX_ITEMS_TO_FETCH_WHEN_GROUP_BY && (
+ <div className={styles.expandedTableFooter}>
+ <Button
+ type="default"
+ size="small"
+ className={styles.viewAllButton}
+ onClick={handleViewAllClick}
+ >
+ <CornerDownRight size={14} />
+ View All
+ </Button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/K8sFiltersSidePanel.module.scss b/frontend/src/container/InfraMonitoringK8s/Base/K8sFiltersSidePanel.module.scss
new file mode 100644
index 0000000000..83213d0d9a
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/K8sFiltersSidePanel.module.scss
@@ -0,0 +1,36 @@
+.drawer {
+ --dialog-description-padding: 0px 0px var(--spacing-8) 0px;
+}
+
+.columnItem {
+ display: flex;
+ align-items: center;
+}
+
+.columnsTitle {
+ color: var(--l2-foreground);
+ font-size: var(--periscope-font-size-small, 11px);
+ font-weight: var(--periscope-font-weight-medium, 500);
+ text-transform: uppercase;
+
+ padding: var(--spacing-4) var(--spacing-8);
+ border-bottom: 1px solid var(--l2-border);
+
+ &:not(:first-of-type) {
+ border-top: 1px solid var(--l2-border);
+ }
+}
+
+.columnsList {
+ display: flex;
+ flex-direction: column;
+}
+
+.columnItem {
+ justify-content: flex-start !important;
+ width: 100%;
+}
+
+.horizontalDivider {
+ border-top: 1px solid var(--l1-border);
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/K8sFiltersSidePanel.tsx b/frontend/src/container/InfraMonitoringK8s/Base/K8sFiltersSidePanel.tsx
new file mode 100644
index 0000000000..a0235da5df
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/K8sFiltersSidePanel.tsx
@@ -0,0 +1,102 @@
+import { Button, DrawerWrapper } from '@signozhq/ui';
+
+import { InfraMonitoringEntity } from '../constants';
+import {
+ useInfraMonitoringTableColumnsForPage,
+ useInfraMonitoringTableColumnsStore,
+} from './useInfraMonitoringTableColumnsStore';
+
+import styles from './K8sFiltersSidePanel.module.scss';
+
+function K8sFiltersSidePanel({
+ open,
+ onClose,
+ entity,
+}: {
+ open: boolean;
+ onClose: () => void;
+ entity: InfraMonitoringEntity;
+}): JSX.Element {
+ const addColumn = useInfraMonitoringTableColumnsStore(
+ (state) => state.addColumn,
+ );
+ const removeColumn = useInfraMonitoringTableColumnsStore(
+ (state) => state.removeColumn,
+ );
+
+ const [columns, columnsHidden] = useInfraMonitoringTableColumnsForPage(entity);
+
+ const drawerContent = (
+ <>
+ <div className={styles.columnsTitle}>Added Columns (Click to remove)</div>
+
+ <div className={styles.columnsList}>
+ {columns
+ .filter(
+ (column) =>
+ !columnsHidden.includes(column.id) &&
+ column.behavior !== 'hidden-on-collapse',
+ )
+ .map((column) => (
+ <div className={styles.columnItem} key={column.value}>
+ {/*<GripVertical size={16} /> TODO: Add support back when update the table component */}
+ <Button
+ variant="ghost"
+ color="none"
+ className={styles.columnItem}
+ disabled={!column.canBeHidden}
+ data-testid={`remove-column-${column.id}`}
+ onClick={(): void => removeColumn(entity, column.id)}
+ >
+ {column.label}
+ </Button>
+ </div>
+ ))}
+ </div>
+
+ <div className={styles.horizontalDivider} />
+
+ <div className={styles.columnsTitle}>Other Columns (Click to add)</div>
+
+ <div className={styles.columnsList}>
+ {columns
+ .filter((column) => columnsHidden.includes(column.id))
+ .map((column) => (
+ <div className={styles.columnItem} key={column.value}>
+ <Button
+ variant="ghost"
+ color="none"
+ className={styles.columnItem}
+ data-can-be-added="true"
+ data-testid={`add-column-${column.id}`}
+ onClick={(): void => addColumn(entity, column.id)}
+ tabIndex={0}
+ >
+ {column.label}
+ </Button>
+ </div>
+ ))}
+ </div>
+ </>
+ );
+
+ return (
+ <DrawerWrapper
+ open={open}
+ onOpenChange={(isOpen): void => {
+ if (!isOpen) {
+ onClose();
+ }
+ }}
+ title="Columns"
+ direction="right"
+ showCloseButton
+ showOverlay={false}
+ className={styles.drawer}
+ >
+ {drawerContent}
+ </DrawerWrapper>
+ );
+}
+
+export default K8sFiltersSidePanel;
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/K8sHeader.module.scss b/frontend/src/container/InfraMonitoringK8s/Base/K8sHeader.module.scss
new file mode 100644
index 0000000000..508f1a2ac3
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/K8sHeader.module.scss
@@ -0,0 +1,80 @@
+.k8SListControls {
+ padding: var(--spacing-4);
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: var(--spacing-4);
+
+ :global(.ant-select-selector) {
+ border-radius: 2px;
+ border: 1px solid var(--border) !important;
+ background-color: var(--l2-background) !important;
+
+ input {
+ font-size: 12px;
+ }
+
+ :global(.ant-tag .ant-typography) {
+ font-size: 12px;
+ }
+ }
+}
+
+.k8SListControlsLeft {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: var(--spacing-4);
+
+ .k8SQbSearchContainer {
+ flex: 1;
+ min-width: 240px;
+ max-width: 60%;
+ }
+}
+
+.k8SAttributeSearchContainer {
+ flex: 1;
+ min-width: 240px;
+ max-width: 40%;
+ display: flex;
+ align-items: center;
+}
+
+.groupByLabel {
+ min-width: max-content;
+ font-size: var(--periscope-font-size-base, 13px);
+ font-weight: var(--periscope-font-weight-regular, 400);
+ line-height: 18px;
+ letter-spacing: -0.07px;
+
+ border-radius: 2px 0px 0px 2px;
+ border: 1px solid var(--border);
+ border-right: none;
+ border-top-right-radius: 0px;
+ border-bottom-right-radius: 0px;
+
+ display: flex;
+ height: 32px;
+ padding: var(--spacing-3) var(--spacing-3) var(--spacing-3) var(--spacing-4);
+ justify-content: center;
+ align-items: center;
+ gap: var(--spacing-2);
+}
+
+.groupBySelect {
+ :global(.ant-select-selector) {
+ border-left: none;
+ border-top-left-radius: 0px;
+ border-bottom-left-radius: 0px;
+ }
+}
+
+.k8SListControlsRight {
+ min-width: 240px;
+
+ display: flex;
+ align-items: center;
+ gap: var(--spacing-2);
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/K8sHeader.tsx b/frontend/src/container/InfraMonitoringK8s/Base/K8sHeader.tsx
new file mode 100644
index 0000000000..2fdc67358a
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/K8sHeader.tsx
@@ -0,0 +1,229 @@
+import React, { useCallback, useMemo, useState } from 'react';
+import { Button } from '@signozhq/button';
+import { Select } from 'antd';
+import logEvent from 'api/common/logEvent';
+import { InfraMonitoringEvents } from 'constants/events';
+import { FeatureKeys } from 'constants/features';
+import { initialQueriesMap } from 'constants/queryBuilder';
+import QueryBuilderSearch from 'container/QueryBuilder/filters/QueryBuilderSearch';
+import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
+import { useGetAggregateKeys } from 'hooks/queryBuilder/useGetAggregateKeys';
+import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
+import { SlidersHorizontal } from 'lucide-react';
+import { useAppContext } from 'providers/App/App';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+import { DataSource } from 'types/common/queryBuilder';
+
+import {
+ GetK8sEntityToAggregateAttribute,
+ InfraMonitoringEntity,
+} from '../constants';
+import {
+ useInfraMonitoringCurrentPage,
+ useInfraMonitoringFilters,
+ useInfraMonitoringGroupBy,
+} from '../hooks';
+import K8sFiltersSidePanel from './K8sFiltersSidePanel';
+
+import styles from './K8sHeader.module.scss';
+
+interface K8sHeaderProps {
+ controlListPrefix?: React.ReactNode;
+ entity: InfraMonitoringEntity;
+ showAutoRefresh: boolean;
+}
+
+function K8sHeader({
+ controlListPrefix,
+ entity,
+ showAutoRefresh,
+}: K8sHeaderProps): JSX.Element {
+ const [isFiltersSidePanelOpen, setIsFiltersSidePanelOpen] = useState(false);
+ const [urlFilters, setUrlFilters] = useInfraMonitoringFilters();
+
+ const currentQuery = initialQueriesMap[DataSource.METRICS];
+
+ const updatedCurrentQuery = useMemo(() => {
+ let { filters } = currentQuery.builder.queryData[0];
+ if (urlFilters) {
+ filters = urlFilters;
+ }
+ return {
+ ...currentQuery,
+ builder: {
+ ...currentQuery.builder,
+ queryData: [
+ {
+ ...currentQuery.builder.queryData[0],
+ aggregateOperator: 'noop',
+ aggregateAttribute: {
+ ...currentQuery.builder.queryData[0].aggregateAttribute,
+ },
+ filters,
+ },
+ ],
+ },
+ };
+ }, [currentQuery, urlFilters]);
+
+ const query = useMemo(
+ () => updatedCurrentQuery?.builder?.queryData[0] || null,
+ [updatedCurrentQuery],
+ );
+
+ const { handleChangeQueryData } = useQueryOperations({
+ index: 0,
+ query: currentQuery.builder.queryData[0],
+ entityVersion: '',
+ });
+
+ const [, setCurrentPage] = useInfraMonitoringCurrentPage();
+ const handleChangeTagFilters = useCallback(
+ (value: IBuilderQuery['filters']) => {
+ setUrlFilters(value || null);
+ handleChangeQueryData('filters', value);
+ setCurrentPage(1);
+
+ if (value?.items && value?.items?.length > 0) {
+ logEvent(InfraMonitoringEvents.FilterApplied, {
+ entity: InfraMonitoringEvents.K8sEntity,
+ page: InfraMonitoringEvents.ListPage,
+ category: InfraMonitoringEvents.Pod,
+ });
+ }
+ },
+ [handleChangeQueryData, setCurrentPage, setUrlFilters],
+ );
+
+ const { featureFlags } = useAppContext();
+ const dotMetricsEnabled =
+ featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
+ ?.active || false;
+
+ const {
+ data: groupByFiltersData,
+ isLoading: isLoadingGroupByFilters,
+ } = useGetAggregateKeys(
+ {
+ dataSource: currentQuery.builder.queryData[0].dataSource,
+ aggregateAttribute: GetK8sEntityToAggregateAttribute(
+ entity,
+ dotMetricsEnabled,
+ ),
+ aggregateOperator: 'noop',
+ searchText: '',
+ tagType: '',
+ },
+ {
+ queryKey: [currentQuery.builder.queryData[0].dataSource, 'noop'],
+ },
+ true,
+ entity,
+ );
+
+ const groupByOptions = useMemo(
+ () =>
+ groupByFiltersData?.payload?.attributeKeys?.map((filter) => ({
+ value: filter.key,
+ label: filter.key,
+ })) || [],
+ [groupByFiltersData],
+ );
+
+ const [groupBy, setGroupBy] = useInfraMonitoringGroupBy();
+
+ const handleGroupByChange = useCallback(
+ (value: IBuilderQuery['groupBy']) => {
+ const newGroupBy = [];
+
+ for (let index = 0; index < value.length; index++) {
+ const element = (value[index] as unknown) as string;
+
+ const key = groupByFiltersData?.payload?.attributeKeys?.find(
+ (k) => k.key === element,
+ );
+
+ if (key) {
+ newGroupBy.push(key);
+ }
+ }
+
+ // Reset pagination on switching to groupBy
+ setCurrentPage(1);
+ setGroupBy(newGroupBy);
+
+ logEvent(InfraMonitoringEvents.GroupByChanged, {
+ entity: InfraMonitoringEvents.K8sEntity,
+ page: InfraMonitoringEvents.ListPage,
+ category: InfraMonitoringEvents.Pod,
+ });
+ },
+ [groupByFiltersData, setCurrentPage, setGroupBy],
+ );
+
+ const onClickOutside = useCallback(() => {
+ setIsFiltersSidePanelOpen(false);
+ }, []);
+
+ return (
+ <div className={styles.k8SListControls}>
+ <div className={styles.k8SListControlsLeft}>
+ {controlListPrefix}
+
+ <div className={styles.k8SQbSearchContainer}>
+ <QueryBuilderSearch
+ query={query as IBuilderQuery}
+ onChange={handleChangeTagFilters}
+ isInfraMonitoring
+ disableNavigationShortcuts
+ entity={entity}
+ />
+ </div>
+
+ <div className={styles.k8SAttributeSearchContainer}>
+ <div className={styles.groupByLabel}> Group by </div>
+ <Select
+ className={styles.groupBySelect}
+ loading={isLoadingGroupByFilters}
+ mode="multiple"
+ value={groupBy}
+ allowClear
+ maxTagCount="responsive"
+ placeholder="Search for attribute"
+ style={{ width: '100%' }}
+ options={groupByOptions}
+ onChange={handleGroupByChange}
+ />
+ </div>
+ </div>
+
+ <div className={styles.k8SListControlsRight}>
+ <DateTimeSelectionV2
+ showAutoRefresh={showAutoRefresh}
+ showRefreshText={false}
+ hideShareModal
+ />
+
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ color="none"
+ disabled={groupBy?.length > 0}
+ data-testid="k8s-list-filters-button"
+ onClick={(): void => setIsFiltersSidePanelOpen(true)}
+ >
+ <SlidersHorizontal size={14} />
+ </Button>
+ </div>
+
+ <K8sFiltersSidePanel
+ open={isFiltersSidePanelOpen}
+ entity={entity}
+ onClose={onClickOutside}
+ />
+ </div>
+ );
+}
+
+export default K8sHeader;
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/__tests__/K8sBaseList.test.tsx b/frontend/src/container/InfraMonitoringK8s/Base/__tests__/K8sBaseList.test.tsx
new file mode 100644
index 0000000000..87fa04c958
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/__tests__/K8sBaseList.test.tsx
@@ -0,0 +1,1312 @@
+import { QueryClient, QueryClientProvider } from 'react-query';
+// eslint-disable-next-line no-restricted-imports
+import { Provider } from 'react-redux';
+import { MemoryRouter } from 'react-router-dom';
+import { MemoryRouter as MemoryRouterV5 } from 'react-router-dom-v5-compat';
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { InfraMonitoringEvents } from 'constants/events';
+import {
+ NuqsTestingAdapter,
+ OnUrlUpdateFunction,
+ UrlUpdateEvent,
+} from 'nuqs/adapters/testing';
+import { AppProvider } from 'providers/App/App';
+import TimezoneProvider from 'providers/Timezone';
+import store from 'store';
+import { openInNewTab } from 'utils/navigation';
+
+import { InfraMonitoringEntity } from '../../constants';
+import { K8sBaseList, K8sBaseListProps } from '../K8sBaseList';
+import {
+ IEntityColumn,
+ useInfraMonitoringTableColumnsStore,
+} from '../useInfraMonitoringTableColumnsStore';
+
+jest.mock('utils/navigation', () => ({
+ ...jest.requireActual('utils/navigation'),
+ openInNewTab: jest.fn(),
+}));
+
+const openInNewTabMock = openInNewTab as jest.Mock;
+
+// Mock DrawerWrapper to avoid CSS issues with jsdom
+// SyntaxError: 'div#radix-:rbv,,._dialog__content_qf8bf_22 :focus' is not a valid selector
+jest.mock('@signozhq/ui', () => ({
+ ...jest.requireActual('@signozhq/ui'),
+ DrawerWrapper: ({
+ open,
+ children,
+ title,
+ }: {
+ open: boolean;
+ children: React.ReactNode;
+ title: string;
+ onOpenChange?: (isOpen: boolean) => void;
+ }): JSX.Element | null =>
+ open ? (
+ <div data-testid="drawer-wrapper" data-title={title}>
+ {children}
+ </div>
+ ) : null,
+}));
+
+// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
+function renderComponent<T>({
+ queryParams,
+ onUrlUpdate,
+ ...props
+}: K8sBaseListProps<T> & {
+ queryParams?: Record<string, string>;
+ onUrlUpdate?: OnUrlUpdateFunction;
+}) {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ },
+ });
+
+ return render(
+ <MemoryRouter>
+ <MemoryRouterV5>
+ <TimezoneProvider>
+ <QueryClientProvider client={queryClient}>
+ <AppProvider>
+ <Provider store={store}>
+ <NuqsTestingAdapter
+ searchParams={queryParams}
+ onUrlUpdate={onUrlUpdate}
+ >
+ <K8sBaseList {...props} />
+ </NuqsTestingAdapter>
+ </Provider>
+ </AppProvider>
+ </QueryClientProvider>
+ </TimezoneProvider>
+ </MemoryRouterV5>
+ </MemoryRouter>,
+ );
+}
+
+describe('K8sBaseList', () => {
+ describe('with items in the list', () => {
+ const itemId = Math.random().toString(36).substring(7);
+ const itemId2 = Math.random().toString(36).substring(7);
+ const onUrlUpdateMock = jest.fn<void, [UrlUpdateEvent]>();
+ const fetchListDataMock = jest.fn<
+ ReturnType<K8sBaseListProps<{ id: string; title: string }>['fetchListData']>,
+ Parameters<K8sBaseListProps<{ id: string; title: string }>['fetchListData']>
+ >();
+
+ beforeEach(() => {
+ onUrlUpdateMock.mockClear();
+ fetchListDataMock.mockClear();
+ openInNewTabMock.mockClear();
+ fetchListDataMock.mockResolvedValue({
+ data: [
+ { id: `PodId:${itemId}`, title: `PodTitle:${itemId}` },
+ { id: `PodId:${itemId2}`, title: `PodTitle:${itemId2}` },
+ ],
+ total: 25,
+ error: null,
+ });
+
+ renderComponent<{ id: string; title: string }>({
+ onUrlUpdate: onUrlUpdateMock,
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ renderRowData: (data) => ({
+ id: <>{data.id}</>,
+ title: <>{data.title}</>,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions: [
+ {
+ id: 'id',
+ label: 'Id',
+ value: 'id',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'always-visible',
+ },
+ {
+ id: 'title',
+ label: 'Title',
+ value: 'title',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'always-visible',
+ },
+ ],
+ tableColumns: [
+ { key: 'id', title: 'Id', dataIndex: 'id', sorter: true },
+ { key: 'title', title: 'Title', dataIndex: 'title' },
+ ],
+ });
+ });
+
+ it('should render all the items in the list', async () => {
+ await waitFor(async () => {
+ expect(await screen.findByText(`PodId:${itemId}`)).toBeInTheDocument();
+ expect(await screen.findByText(`PodTitle:${itemId}`)).toBeInTheDocument();
+ expect(await screen.findByText(`PodId:${itemId2}`)).toBeInTheDocument();
+ expect(await screen.findByText(`PodTitle:${itemId2}`)).toBeInTheDocument();
+ });
+ });
+
+ it('should call fetchListData with default filters', async () => {
+ await waitFor(() => {
+ expect(fetchListDataMock).toHaveBeenCalled();
+ });
+
+ const [filters] = fetchListDataMock.mock.calls[0];
+ expect(filters.limit).toBe(10);
+ expect(filters.offset).toBe(0);
+ expect(filters.filters).toEqual({ items: [], op: 'AND' });
+ expect(filters.groupBy).toBeUndefined();
+ expect(filters.orderBy).toBeUndefined();
+ });
+
+ it('should click to open the row details and update selectedItem in URL', async () => {
+ const user = userEvent.setup();
+
+ const firstRowEl = await screen.findByText(`PodId:${itemId}`);
+ await user.click(firstRowEl);
+
+ await waitFor(() => {
+ const selectedItem = onUrlUpdateMock.mock.calls
+ .map((call) => call[0].searchParams.get('selectedItem'))
+ .pop();
+ expect(selectedItem).toBe(`PodId:${itemId}`);
+ });
+ });
+
+ it('should update orderBy in URL when clicking sortable column header', async () => {
+ const user = userEvent.setup();
+
+ await waitFor(() => {
+ expect(screen.getByText(`PodId:${itemId}`)).toBeInTheDocument();
+ });
+
+ const idHeader = screen.getByRole('columnheader', { name: /id/i });
+ await user.click(idHeader);
+
+ await waitFor(() => {
+ const lastOrderBy = onUrlUpdateMock.mock.calls
+ .map((call) => call[0].searchParams.get('orderBy'))
+ .filter(Boolean)
+ .pop();
+
+ expect(lastOrderBy).toBeDefined();
+ const parsed = JSON.parse(lastOrderBy as string);
+ expect(parsed.columnName).toBe('id');
+ expect(parsed.order).toBe('asc');
+ });
+ });
+
+ it('should toggle sort order in URL on subsequent header clicks', async () => {
+ const user = userEvent.setup();
+
+ await waitFor(() => {
+ expect(screen.getByText(`PodId:${itemId}`)).toBeInTheDocument();
+ });
+
+ const idHeader = screen.getByRole('columnheader', { name: /id/i });
+
+ // First click - ascending
+ await user.click(idHeader);
+ // Second click - descending
+ await user.click(idHeader);
+
+ await waitFor(() => {
+ const lastOrderBy = onUrlUpdateMock.mock.calls
+ .map((call) => call[0].searchParams.get('orderBy'))
+ .filter(Boolean)
+ .pop();
+
+ if (lastOrderBy) {
+ const parsed = JSON.parse(lastOrderBy);
+ expect(parsed.order).toBe('desc');
+ }
+ });
+ });
+
+ it('should update currentPage in URL when clicking pagination', async () => {
+ const user = userEvent.setup();
+
+ await waitFor(() => {
+ expect(screen.getByText(`PodId:${itemId}`)).toBeInTheDocument();
+ });
+
+ const page2Button = screen.getByRole('listitem', { name: '2' });
+ await user.click(page2Button);
+
+ await waitFor(() => {
+ const lastPage = onUrlUpdateMock.mock.calls
+ .map((call) => call[0].searchParams.get('currentPage'))
+ .filter(Boolean)
+ .pop();
+
+ expect(lastPage).toBe('2');
+ });
+ });
+
+ it('should open row in new tab when ctrl+click on row', async () => {
+ await waitFor(() => {
+ expect(screen.getByText(`PodId:${itemId}`)).toBeInTheDocument();
+ });
+
+ const firstRow = screen.getByText(`PodId:${itemId}`);
+ // Ctrl+click to open in new tab
+ fireEvent.click(firstRow, { ctrlKey: true });
+
+ await waitFor(() => {
+ expect(openInNewTabMock).toHaveBeenCalledTimes(1);
+ expect(openInNewTabMock).toHaveBeenCalledWith(
+ expect.stringContaining(`selectedItem=PodId%3A${itemId}`),
+ );
+ });
+ });
+
+ it('should open row in new tab when meta+click (cmd on Mac) on row', async () => {
+ await waitFor(() => {
+ expect(screen.getByText(`PodId:${itemId}`)).toBeInTheDocument();
+ });
+
+ const firstRow = screen.getByText(`PodId:${itemId}`);
+ // Meta+click (cmd on Mac) to open in new tab
+ fireEvent.click(firstRow, { metaKey: true });
+
+ await waitFor(() => {
+ expect(openInNewTabMock).toHaveBeenCalledTimes(1);
+ expect(openInNewTabMock).toHaveBeenCalledWith(
+ expect.stringContaining(`selectedItem=PodId%3A${itemId}`),
+ );
+ });
+ });
+ });
+
+ describe('with URL params (orderBy, groupBy, pagination)', () => {
+ const onUrlUpdateMock = jest.fn<void, [UrlUpdateEvent]>();
+ const fetchListDataMock = jest.fn<
+ ReturnType<K8sBaseListProps<{ id: string }>['fetchListData']>,
+ Parameters<K8sBaseListProps<{ id: string }>['fetchListData']>
+ >();
+ const groupByValue = [
+ { key: 'k8s.namespace.name', dataType: 'string', type: 'resource' },
+ ];
+
+ beforeEach(() => {
+ onUrlUpdateMock.mockClear();
+ fetchListDataMock.mockClear();
+ fetchListDataMock.mockResolvedValue({
+ data: [{ id: 'namespace-default' }],
+ total: 50,
+ error: null,
+ });
+
+ renderComponent<{ id: string }>({
+ onUrlUpdate: onUrlUpdateMock,
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ queryParams: {
+ orderBy: JSON.stringify({ columnName: 'cpu', order: 'desc' }),
+ groupBy: JSON.stringify(groupByValue),
+ currentPage: '3',
+ },
+ renderRowData: (data) => ({
+ id: data.id,
+ itemKey: data.id,
+ groupedByMeta: { 'k8s.namespace.name': 'default' },
+ key: data.id,
+ }),
+ tableColumnsDefinitions: [
+ {
+ id: 'id',
+ label: 'Id',
+ value: 'id',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'always-visible',
+ },
+ ],
+ tableColumns: [{ key: 'id', title: 'Id', dataIndex: 'id' }],
+ });
+ });
+
+ it('should call fetchListData with orderBy/groupBy/offset/limit from URL', async () => {
+ await waitFor(() => {
+ expect(fetchListDataMock).toHaveBeenCalled();
+ });
+
+ const [filters] = fetchListDataMock.mock.calls[0];
+ expect(filters.orderBy).toEqual({ columnName: 'cpu', order: 'desc' });
+ expect(filters.groupBy).toEqual(groupByValue);
+ expect(filters.offset).toBe(20); // (3 - 1) * 10 = 20
+ expect(filters.limit).toBe(10);
+ });
+
+ it('should render expand icons when groupBy is set', async () => {
+ await waitFor(() => {
+ expect(screen.getByText('namespace-default')).toBeInTheDocument();
+ });
+
+ const expandButtons = screen.getAllByRole('button');
+ expect(expandButtons.length).toBeGreaterThan(0);
+ });
+
+ it('should expand row and fetch without groupBy when clicking grouped row', async () => {
+ const user = userEvent.setup();
+
+ await waitFor(() => {
+ expect(screen.getByText('namespace-default')).toBeInTheDocument();
+ });
+
+ const row = screen.getByText('namespace-default');
+ await user.click(row);
+
+ await waitFor(() => {
+ expect(fetchListDataMock).toHaveBeenCalledTimes(4);
+ });
+
+ const [filters] = fetchListDataMock.mock.calls.find((c) => !c[0].groupBy)!;
+ expect(filters.offset).toBe(0);
+ expect(filters.limit).toBe(10);
+ expect(filters.orderBy?.columnName).toBe('cpu');
+ expect(filters.orderBy?.order).toBe('desc');
+ });
+ });
+
+ describe('with empty data', () => {
+ const fetchListDataMock = jest.fn<
+ ReturnType<K8sBaseListProps<{ id: string }>['fetchListData']>,
+ Parameters<K8sBaseListProps<{ id: string }>['fetchListData']>
+ >();
+
+ beforeEach(() => {
+ fetchListDataMock.mockClear();
+ fetchListDataMock.mockResolvedValue({
+ data: [],
+ total: 0,
+ error: null,
+ rawData: {
+ sentAnyHostMetricsData: true,
+ isSendingK8SAgentMetrics: false,
+ },
+ });
+
+ renderComponent<{ id: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ renderRowData: (data) => ({
+ id: data.id,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions: [
+ {
+ id: 'id',
+ label: 'Id',
+ value: 'id',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'always-visible',
+ },
+ ],
+ tableColumns: [{ key: 'id', title: 'Id', dataIndex: 'id' }],
+ });
+ });
+
+ it('should display empty state when no data is returned', async () => {
+ await waitFor(() => {
+ expect(screen.getByText(/This query had no results/i)).toBeInTheDocument();
+ });
+ });
+
+ it('should still call fetchListData', async () => {
+ await waitFor(() => {
+ expect(fetchListDataMock).toHaveBeenCalled();
+ });
+ });
+ });
+
+ describe('with error response', () => {
+ const fetchListDataMock = jest.fn<
+ ReturnType<K8sBaseListProps<{ id: string }>['fetchListData']>,
+ Parameters<K8sBaseListProps<{ id: string }>['fetchListData']>
+ >();
+
+ beforeEach(() => {
+ fetchListDataMock.mockClear();
+ fetchListDataMock.mockResolvedValue({
+ data: [],
+ total: 0,
+ error: 'Failed to fetch pods',
+ });
+
+ renderComponent<{ id: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ renderRowData: (data) => ({
+ id: data.id,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions: [
+ {
+ id: 'id',
+ label: 'Id',
+ value: 'id',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'always-visible',
+ },
+ ],
+ tableColumns: [{ key: 'id', title: 'Id', dataIndex: 'id' }],
+ });
+ });
+
+ it('should call fetchListData even when error occurs', async () => {
+ await waitFor(() => {
+ expect(fetchListDataMock).toHaveBeenCalled();
+ });
+ });
+
+ it('should display error message when data.error is set', async () => {
+ await waitFor(() => {
+ expect(screen.getByText(/Failed to fetch pods/i)).toBeInTheDocument();
+ });
+ });
+ });
+
+ describe('with no metrics data (sentAnyHostMetricsData=false)', () => {
+ const fetchListDataMock = jest.fn<
+ ReturnType<K8sBaseListProps<{ id: string }>['fetchListData']>,
+ Parameters<K8sBaseListProps<{ id: string }>['fetchListData']>
+ >();
+
+ beforeEach(() => {
+ fetchListDataMock.mockClear();
+ fetchListDataMock.mockResolvedValue({
+ data: [],
+ total: 0,
+ error: null,
+ rawData: {
+ sentAnyHostMetricsData: false,
+ isSendingK8SAgentMetrics: false,
+ },
+ });
+
+ renderComponent<{ id: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ renderRowData: (data) => ({
+ id: data.id,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions: [
+ {
+ id: 'id',
+ label: 'Id',
+ value: 'id',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'always-visible',
+ },
+ ],
+ tableColumns: [{ key: 'id', title: 'Id', dataIndex: 'id' }],
+ });
+ });
+
+ it('should display no metrics data message', async () => {
+ await waitFor(() => {
+ expect(
+ screen.getByText(/No host metrics data received yet/i),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it('should display link to documentation', async () => {
+ await waitFor(() => {
+ const link = screen.getByRole('link', { name: /our documentation/i });
+ expect(link).toBeInTheDocument();
+ expect(link).toHaveAttribute(
+ 'href',
+ 'https://signoz.io/docs/userguide/hostmetrics/',
+ );
+ });
+ });
+ });
+
+ describe('with incorrect K8s agent metrics (isSendingK8SAgentMetrics=true)', () => {
+ const fetchListDataMock = jest.fn<
+ ReturnType<K8sBaseListProps<{ id: string }>['fetchListData']>,
+ Parameters<K8sBaseListProps<{ id: string }>['fetchListData']>
+ >();
+
+ beforeEach(() => {
+ fetchListDataMock.mockClear();
+ fetchListDataMock.mockResolvedValue({
+ data: [],
+ total: 0,
+ error: null,
+ rawData: {
+ sentAnyHostMetricsData: true,
+ isSendingK8SAgentMetrics: true,
+ },
+ });
+
+ renderComponent<{ id: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ renderRowData: (data) => ({
+ id: data.id,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions: [
+ {
+ id: 'id',
+ label: 'Id',
+ value: 'id',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'always-visible',
+ },
+ ],
+ tableColumns: [{ key: 'id', title: 'Id', dataIndex: 'id' }],
+ });
+ });
+
+ it('should display upgrade message', async () => {
+ await waitFor(() => {
+ expect(
+ screen.getByText(/upgrade to the latest version of SigNoz k8s-infra/i),
+ ).toBeInTheDocument();
+ });
+ });
+ });
+
+ describe('with end time before retention (endTimeBeforeRetention=true)', () => {
+ const fetchListDataMock = jest.fn<
+ ReturnType<K8sBaseListProps<{ id: string }>['fetchListData']>,
+ Parameters<K8sBaseListProps<{ id: string }>['fetchListData']>
+ >();
+
+ beforeEach(() => {
+ fetchListDataMock.mockClear();
+ fetchListDataMock.mockResolvedValue({
+ data: [],
+ total: 0,
+ error: null,
+ rawData: {
+ sentAnyHostMetricsData: true,
+ isSendingK8SAgentMetrics: false,
+ endTimeBeforeRetention: true,
+ },
+ });
+
+ renderComponent<{ id: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ renderRowData: (data) => ({
+ id: data.id,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions: [
+ {
+ id: 'id',
+ label: 'Id',
+ value: 'id',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'always-visible',
+ },
+ ],
+ tableColumns: [{ key: 'id', title: 'Id', dataIndex: 'id' }],
+ });
+ });
+
+ it('should display time range before retention message', async () => {
+ await waitFor(() => {
+ expect(
+ screen.getByText(/Queried time range is before earliest K8s metrics/i),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(/please adjust your end time/i),
+ ).toBeInTheDocument();
+ });
+ });
+ });
+
+ describe('column visibility based on defaultVisibility', () => {
+ const fetchListDataMock = jest.fn<
+ ReturnType<
+ K8sBaseListProps<{
+ id: string;
+ name: string;
+ desc: string;
+ }>['fetchListData']
+ >,
+ Parameters<
+ K8sBaseListProps<{
+ id: string;
+ name: string;
+ desc: string;
+ }>['fetchListData']
+ >
+ >();
+
+ const tableColumnsDefinitions: IEntityColumn[] = [
+ {
+ id: 'id',
+ label: 'Id',
+ value: 'id',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'always-visible',
+ },
+ {
+ id: 'name',
+ label: 'Name',
+ value: 'name',
+ defaultVisibility: true,
+ canBeHidden: true,
+ behavior: 'always-visible',
+ },
+ {
+ id: 'description',
+ label: 'Description',
+ value: 'description',
+ defaultVisibility: false,
+ canBeHidden: true,
+ behavior: 'always-visible',
+ },
+ ];
+
+ const tableColumns = [
+ { key: 'id', title: 'Id', dataIndex: 'id' },
+ { key: 'name', title: 'Name', dataIndex: 'name' },
+ { key: 'description', title: 'Description', dataIndex: 'description' },
+ ];
+
+ beforeEach(() => {
+ // Reset the store before each test
+ useInfraMonitoringTableColumnsStore.setState({
+ columns: {},
+ columnsHidden: {},
+ });
+
+ fetchListDataMock.mockClear();
+ fetchListDataMock.mockResolvedValue({
+ data: [{ id: 'item-1', name: 'Item 1', desc: 'Description 1' }],
+ total: 1,
+ error: null,
+ });
+ });
+
+ it('should show columns with defaultVisibility=true', async () => {
+ renderComponent<{ id: string; name: string; desc: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ renderRowData: (data) => ({
+ id: data.id,
+ name: data.name,
+ description: data.desc,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions,
+ tableColumns,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText('item-1')).toBeInTheDocument();
+ });
+
+ // Id and Name should be visible (defaultVisibility=true)
+ expect(
+ screen.getByRole('columnheader', { name: /id/i }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('columnheader', { name: /name/i }),
+ ).toBeInTheDocument();
+ });
+
+ it('should hide columns with defaultVisibility=false', async () => {
+ renderComponent<{ id: string; name: string; desc: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ renderRowData: (data) => ({
+ id: data.id,
+ name: data.name,
+ description: data.desc,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions,
+ tableColumns,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText('item-1')).toBeInTheDocument();
+ });
+
+ // Description should be hidden (defaultVisibility=false)
+ expect(
+ screen.queryByRole('columnheader', { name: /description/i }),
+ ).not.toBeInTheDocument();
+ });
+
+ it('should respect user changes to column visibility via store', async () => {
+ // Manually set the store state to hide the 'name' column
+ act(() => {
+ useInfraMonitoringTableColumnsStore.setState({
+ columns: {
+ [InfraMonitoringEntity.PODS]: tableColumnsDefinitions,
+ },
+ columnsHidden: {
+ [InfraMonitoringEntity.PODS]: ['name', 'description'],
+ },
+ });
+ });
+
+ renderComponent<{ id: string; name: string; desc: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ renderRowData: (data) => ({
+ id: data.id,
+ name: data.name,
+ description: data.desc,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions,
+ tableColumns,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText('item-1')).toBeInTheDocument();
+ });
+
+ // Name column should be hidden by user preference
+ expect(
+ screen.queryByRole('columnheader', { name: /^name$/i }),
+ ).not.toBeInTheDocument();
+ // Id should still be visible
+ expect(
+ screen.getByRole('columnheader', { name: /id/i }),
+ ).toBeInTheDocument();
+ });
+ });
+
+ describe('column behavior with groupBy (expanded/collapsed)', () => {
+ const fetchListDataMock = jest.fn<
+ ReturnType<
+ K8sBaseListProps<{
+ id: string;
+ name: string;
+ group: string;
+ }>['fetchListData']
+ >,
+ Parameters<
+ K8sBaseListProps<{
+ id: string;
+ name: string;
+ group: string;
+ }>['fetchListData']
+ >
+ >();
+
+ const tableColumnsDefinitions: IEntityColumn[] = [
+ {
+ id: 'group',
+ label: 'Group',
+ value: 'group',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'hidden-on-collapse', // Only visible when grouped
+ },
+ {
+ id: 'name',
+ label: 'Name',
+ value: 'name',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'hidden-on-expand', // Only visible when NOT grouped
+ },
+ {
+ id: 'id',
+ label: 'Id',
+ value: 'id',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'always-visible',
+ },
+ ];
+
+ const tableColumns = [
+ { key: 'group', title: 'Group', dataIndex: 'group' },
+ { key: 'name', title: 'Name', dataIndex: 'name' },
+ { key: 'id', title: 'Id', dataIndex: 'id' },
+ ];
+
+ beforeEach(() => {
+ useInfraMonitoringTableColumnsStore.setState({
+ columns: {},
+ columnsHidden: {},
+ });
+
+ fetchListDataMock.mockClear();
+ fetchListDataMock.mockResolvedValue({
+ data: [{ id: 'item-1', name: 'Item 1', group: 'Group A' }],
+ total: 1,
+ error: null,
+ });
+ });
+
+ it('should hide "hidden-on-collapse" columns when NOT grouped', async () => {
+ renderComponent<{ id: string; name: string; group: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ queryParams: {}, // No groupBy
+ renderRowData: (data) => ({
+ id: data.id,
+ name: data.name,
+ group: data.group,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions,
+ tableColumns,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText('item-1')).toBeInTheDocument();
+ });
+
+ // Group column should be hidden (hidden-on-collapse means visible only when expanded/grouped)
+ expect(
+ screen.queryByRole('columnheader', { name: /group/i }),
+ ).not.toBeInTheDocument();
+ // Name column should be visible (hidden-on-expand means visible when NOT grouped)
+ expect(
+ screen.getByRole('columnheader', { name: /name/i }),
+ ).toBeInTheDocument();
+ // Id should always be visible
+ expect(
+ screen.getByRole('columnheader', { name: /id/i }),
+ ).toBeInTheDocument();
+ });
+
+ it('should hide "hidden-on-expand" columns when grouped', async () => {
+ const groupByValue = [
+ { key: 'k8s.namespace.name', dataType: 'string', type: 'resource' },
+ ];
+
+ renderComponent<{ id: string; name: string; group: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ queryParams: {
+ groupBy: JSON.stringify(groupByValue),
+ },
+ renderRowData: (data) => ({
+ id: data.id,
+ name: data.name,
+ group: data.group,
+ itemKey: data.id,
+ groupedByMeta: { 'k8s.namespace.name': 'default' },
+ key: data.id,
+ }),
+ tableColumnsDefinitions,
+ tableColumns,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText('item-1')).toBeInTheDocument();
+ });
+
+ // Group column should be visible (hidden-on-collapse means visible when grouped)
+ expect(
+ screen.getByRole('columnheader', { name: /group/i }),
+ ).toBeInTheDocument();
+ // Name column should be hidden (hidden-on-expand means hidden when grouped)
+ expect(
+ screen.queryByRole('columnheader', { name: /name/i }),
+ ).not.toBeInTheDocument();
+ // Id should always be visible
+ expect(
+ screen.getByRole('columnheader', { name: /id/i }),
+ ).toBeInTheDocument();
+ });
+
+ it('should show "always-visible" columns regardless of groupBy state', async () => {
+ // Test without groupBy
+ renderComponent<{ id: string; name: string; group: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ queryParams: {},
+ renderRowData: (data) => ({
+ id: data.id,
+ name: data.name,
+ group: data.group,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions,
+ tableColumns,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText('item-1')).toBeInTheDocument();
+ });
+
+ expect(
+ screen.getByRole('columnheader', { name: /id/i }),
+ ).toBeInTheDocument();
+ });
+ });
+
+ describe('column visibility in expanded row (nested table)', () => {
+ const fetchListDataMock = jest.fn<
+ ReturnType<K8sBaseListProps<{ id: string }>['fetchListData']>,
+ Parameters<K8sBaseListProps<{ id: string }>['fetchListData']>
+ >();
+ const groupByValue = [
+ { key: 'k8s.namespace.name', dataType: 'string', type: 'resource' },
+ ];
+
+ const tableColumnsDefinitions: IEntityColumn[] = [
+ {
+ id: 'id',
+ label: 'Id',
+ value: 'id',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'always-visible',
+ },
+ ];
+
+ const tableColumns = [{ key: 'id', title: 'Id', dataIndex: 'id' }];
+
+ // Initialize the component once without groupBy to set up the store state
+ // This mimics what happens when running with other tests that render first
+ beforeAll(() => {
+ const initMock = jest.fn().mockResolvedValue({
+ data: [{ id: 'init' }],
+ total: 1,
+ error: null,
+ });
+
+ renderComponent<{ id: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: initMock,
+ renderRowData: (data) => ({
+ id: data.id,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions,
+ tableColumns,
+ });
+ });
+
+ beforeEach(() => {
+ fetchListDataMock.mockClear();
+ fetchListDataMock.mockResolvedValue({
+ data: [{ id: 'namespace-default' }],
+ total: 50,
+ error: null,
+ });
+
+ // Render in beforeEach with groupBy for the actual test
+ renderComponent<{ id: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ queryParams: {
+ groupBy: JSON.stringify(groupByValue),
+ },
+ renderRowData: (data) => ({
+ id: data.id,
+ itemKey: data.id,
+ groupedByMeta: { 'k8s.namespace.name': 'default' },
+ key: data.id,
+ }),
+ tableColumnsDefinitions,
+ tableColumns,
+ });
+ });
+
+ it('should hide "hidden-on-collapse" columns in nested expanded table', async () => {
+ const user = userEvent.setup();
+
+ await waitFor(() => {
+ expect(screen.getByText('namespace-default')).toBeInTheDocument();
+ });
+
+ const row = screen.getByText('namespace-default');
+ await user.click(row);
+
+ // Wait for both expanded-table-container and expanded-table to appear
+ // The expanded-table only appears after loading completes
+ await waitFor(() => {
+ expect(screen.getByTestId('expanded-table-container')).toBeInTheDocument();
+ expect(screen.getByTestId('expanded-table')).toBeInTheDocument();
+ });
+
+ // In the nested table, hidden-on-collapse columns should be hidden
+ const expandedTable = screen.getByTestId('expanded-table');
+ const nestedTableWrapper = within(expandedTable as HTMLElement);
+ // The nested table should NOT have the Group column header
+ // Note: headers are hidden in nested table (showHeader={false}), so we check data cells
+ expect(nestedTableWrapper.queryByText('Group A')).not.toBeInTheDocument();
+ });
+ });
+
+ describe('column add/remove via store', () => {
+ const fetchListDataMock = jest.fn<
+ ReturnType<
+ K8sBaseListProps<{
+ id: string;
+ name: string;
+ desc: string;
+ }>['fetchListData']
+ >,
+ Parameters<
+ K8sBaseListProps<{
+ id: string;
+ name: string;
+ desc: string;
+ }>['fetchListData']
+ >
+ >();
+
+ const tableColumnsDefinitions: IEntityColumn[] = [
+ {
+ id: 'id',
+ label: 'Id',
+ value: 'id',
+ defaultVisibility: true,
+ canBeHidden: false,
+ behavior: 'always-visible',
+ },
+ {
+ id: 'name',
+ label: 'Name',
+ value: 'name',
+ defaultVisibility: true,
+ canBeHidden: true,
+ behavior: 'always-visible',
+ },
+ {
+ id: 'description',
+ label: 'Description',
+ value: 'description',
+ defaultVisibility: false,
+ canBeHidden: true,
+ behavior: 'always-visible',
+ },
+ ];
+
+ const tableColumns = [
+ { key: 'id', title: 'Id', dataIndex: 'id' },
+ { key: 'name', title: 'Name', dataIndex: 'name' },
+ { key: 'description', title: 'Description', dataIndex: 'description' },
+ ];
+
+ beforeEach(() => {
+ useInfraMonitoringTableColumnsStore.setState({
+ columns: {},
+ columnsHidden: {},
+ });
+
+ fetchListDataMock.mockClear();
+ fetchListDataMock.mockResolvedValue({
+ data: [
+ { id: 'item-1', name: 'Item 1', desc: 'Description 1' },
+ { id: 'item-2', name: 'Item 2', desc: 'Description 2' },
+ ],
+ total: 2,
+ error: null,
+ });
+ });
+
+ it('should hide column when clicking remove in K8sFiltersSidePanel', async () => {
+ const user = userEvent.setup();
+
+ renderComponent<{
+ id: string;
+ name: string;
+ desc: string;
+ }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ renderRowData: (data) => ({
+ id: data.id,
+ name: data.name,
+ description: data.desc,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions,
+ tableColumns,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText('item-1')).toBeInTheDocument();
+ });
+
+ expect(
+ screen.getByRole('columnheader', { name: /^name$/i }),
+ ).toBeInTheDocument();
+
+ const filterButton = screen.getByTestId('k8s-list-filters-button');
+ expect(filterButton).toBeDefined();
+ await user.click(filterButton!);
+
+ await waitFor(() => {
+ expect(
+ screen.getByText('Added Columns (Click to remove)'),
+ ).toBeInTheDocument();
+ });
+
+ const nameColumnButton = screen.getByTestId(`remove-column-name`);
+ await user.click(nameColumnButton);
+
+ // Name column should now be hidden from the table
+ await waitFor(() => {
+ expect(
+ screen.queryByRole('columnheader', { name: /^name$/i }),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ it('should show column when clicking add in K8sFiltersSidePanel', async () => {
+ const user = userEvent.setup();
+
+ renderComponent<{
+ id: string;
+ name: string;
+ desc: string;
+ }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ renderRowData: (data) => ({
+ id: data.id,
+ name: data.name,
+ description: data.desc,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions,
+ tableColumns,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText('item-1')).toBeInTheDocument();
+ });
+
+ // Initially Description column should be hidden (defaultVisibility=false)
+ expect(
+ screen.queryByRole('columnheader', { name: /description/i }),
+ ).not.toBeInTheDocument();
+
+ const filterButton = screen.getByTestId('k8s-list-filters-button');
+ await user.click(filterButton!);
+
+ await waitFor(() => {
+ expect(
+ screen.getByText('Other Columns (Click to add)'),
+ ).toBeInTheDocument();
+ });
+
+ const descriptionColumnButton = screen.getByTestId('add-column-description');
+ await user.click(descriptionColumnButton);
+
+ // Description column should now be visible in the table
+ await waitFor(() => {
+ expect(
+ screen.getByRole('columnheader', { name: /description/i }),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it('should not allow removing column with canBeHidden=false', async () => {
+ renderComponent<{ id: string; name: string; desc: string }>({
+ entity: InfraMonitoringEntity.PODS,
+ eventCategory: InfraMonitoringEvents.Pod,
+ fetchListData: fetchListDataMock,
+ renderRowData: (data) => ({
+ id: data.id,
+ name: data.name,
+ description: data.desc,
+ itemKey: data.id,
+ groupedByMeta: {},
+ key: data.id,
+ }),
+ tableColumnsDefinitions,
+ tableColumns,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText('item-1')).toBeInTheDocument();
+ });
+
+ // Try to remove the Id column (canBeHidden=false)
+ act(() => {
+ // eslint-disable-next-line no-restricted-syntax
+ useInfraMonitoringTableColumnsStore
+ .getState()
+ .removeColumn(InfraMonitoringEntity.PODS, 'id');
+ });
+
+ // Id column should still be visible (canBeHidden=false prevents removal)
+ expect(
+ screen.getByRole('columnheader', { name: /id/i }),
+ ).toBeInTheDocument();
+ });
+ });
+});
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/types.ts b/frontend/src/container/InfraMonitoringK8s/Base/types.ts
new file mode 100644
index 0000000000..578e919872
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/types.ts
@@ -0,0 +1,27 @@
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
+
+import { OrderBySchemaType } from '../schemas';
+
+export type K8sBaseFilters = {
+ filters: TagFilter;
+ groupBy?: BaseAutocompleteData[];
+ offset?: number;
+ limit?: number;
+ start: number;
+ end: number;
+ orderBy?: OrderBySchemaType;
+};
+
+export type K8sRenderedRowData = {
+ /**
+ * The unique ID for the row
+ */
+ key: string;
+ /**
+ * The ID to the selectedItem
+ */
+ itemKey: string;
+ groupedByMeta: Record<string, string>;
+ [key: string]: unknown;
+};
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/useInfraMonitoringTableColumnsStore.ts b/frontend/src/container/InfraMonitoringK8s/Base/useInfraMonitoringTableColumnsStore.ts
new file mode 100644
index 0000000000..83d490afbe
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/useInfraMonitoringTableColumnsStore.ts
@@ -0,0 +1,113 @@
+import { create } from 'zustand';
+import { persist } from 'zustand/middleware';
+
+export interface IEntityColumn {
+ label: string;
+ value: string;
+ id: string;
+ defaultVisibility: boolean;
+ canBeHidden: boolean;
+ behavior: 'hidden-on-expand' | 'hidden-on-collapse' | 'always-visible';
+}
+
+export interface IInfraMonitoringTableColumnsStore {
+ columns: Record<string, IEntityColumn[]>;
+ columnsHidden: Record<string, string[]>;
+ addColumn: (page: string, columnId: string) => void;
+ removeColumn: (page: string, columnId: string) => void;
+ initializePageColumns: (page: string, columns: IEntityColumn[]) => void;
+}
+
+export const useInfraMonitoringTableColumnsStore = create<IInfraMonitoringTableColumnsStore>()(
+ persist(
+ (set, get) => ({
+ columns: {},
+ columnsHidden: {},
+ addColumn: (page, columnId): void => {
+ const state = get();
+ const columnDefinition = state.columns[page]?.find(
+ (c) => c.id === columnId,
+ );
+
+ if (!columnDefinition) {
+ return;
+ }
+
+ if (!columnDefinition.canBeHidden) {
+ return;
+ }
+
+ const columnsHidden = state.columnsHidden[page];
+
+ if (columnsHidden.includes(columnId)) {
+ set({
+ columnsHidden: {
+ ...state.columnsHidden,
+ [page]: columnsHidden.filter((id) => id !== columnId),
+ },
+ });
+ }
+ },
+ removeColumn: (page, columnId): void => {
+ const state = get();
+ const columnDefinition = state.columns[page]?.find(
+ (c) => c.id === columnId,
+ );
+
+ if (!columnDefinition) {
+ return;
+ }
+
+ if (!columnDefinition.canBeHidden) {
+ return;
+ }
+
+ const columnsHidden = state.columnsHidden[page];
+
+ if (!columnsHidden.includes(columnId)) {
+ set({
+ columnsHidden: {
+ ...state.columnsHidden,
+ [page]: [...columnsHidden, columnId],
+ },
+ });
+ }
+ },
+ initializePageColumns: (page, columns): void => {
+ const state = get();
+
+ set({
+ columns: {
+ ...state.columns,
+ [page]: columns,
+ },
+ });
+
+ if (state.columnsHidden[page] === undefined) {
+ set({
+ columnsHidden: {
+ ...state.columnsHidden,
+ [page]: columns
+ .filter((c) => c.defaultVisibility === false)
+ .map((c) => c.id),
+ },
+ });
+ }
+ },
+ }),
+ {
+ name: '@signoz/infra-monitoring-columns',
+ },
+ ),
+);
+
+export const useInfraMonitoringTableColumnsForPage = (
+ page: string,
+): [columns: IEntityColumn[], columnsHidden: string[]] => {
+ const state = useInfraMonitoringTableColumnsStore((s) => s.columns);
+ const columnsHidden = useInfraMonitoringTableColumnsStore(
+ (s) => s.columnsHidden,
+ );
+
+ return [state[page] ?? [], columnsHidden[page] ?? []];
+};
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/utils.module.scss b/frontend/src/container/InfraMonitoringK8s/Base/utils.module.scss
new file mode 100644
index 0000000000..c6e9d30e01
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/utils.module.scss
@@ -0,0 +1,18 @@
+.itemDataGroup {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ flex-wrap: wrap;
+
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.itemDataGroupTagItem {
+ display: block !important;
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Base/utils.tsx b/frontend/src/container/InfraMonitoringK8s/Base/utils.tsx
new file mode 100644
index 0000000000..3b0f432915
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Base/utils.tsx
@@ -0,0 +1,96 @@
+import { Badge } from '@signozhq/ui';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+
+import styles from './utils.module.scss';
+
+const dotToUnder: Record<string, string> = {
+ 'os.type': 'os_type',
+ 'host.name': 'host_name',
+ 'deployment.environment': 'deployment_environment',
+ 'k8s.node.name': 'k8s_node_name',
+ 'k8s.cluster.name': 'k8s_cluster_name',
+ 'k8s.node.uid': 'k8s_node_uid',
+ 'k8s.cronjob.name': 'k8s_cronjob_name',
+ 'k8s.daemonset.name': 'k8s_daemonset_name',
+ 'k8s.deployment.name': 'k8s_deployment_name',
+ 'k8s.job.name': 'k8s_job_name',
+ 'k8s.namespace.name': 'k8s_namespace_name',
+ 'k8s.pod.name': 'k8s_pod_name',
+ 'k8s.pod.uid': 'k8s_pod_uid',
+ 'k8s.statefulset.name': 'k8s_statefulset_name',
+ 'k8s.persistentvolumeclaim.name': 'k8s_persistentvolumeclaim_name',
+};
+
+export function getGroupedByMeta<T extends { meta: Record<string, string> }>(
+ itemData: T,
+ groupBy: BaseAutocompleteData[],
+): Record<string, string> {
+ const result: Record<string, string> = {};
+
+ groupBy.forEach((group) => {
+ const rawKey = group.key as string;
+ const metaKey = (dotToUnder[rawKey] ?? rawKey) as keyof typeof itemData.meta;
+ result[rawKey] = (itemData.meta[metaKey] || itemData.meta[rawKey]) ?? '';
+ });
+
+ return result;
+}
+
+export function getRowKey<T extends { meta: Record<string, string> }>(
+ itemData: T,
+ getItemIdentifier: () => string,
+ groupBy: BaseAutocompleteData[],
+): string {
+ const nodeIdentifier = getItemIdentifier();
+
+ if (groupBy.length === 0) {
+ return nodeIdentifier || JSON.stringify(itemData.meta);
+ }
+
+ const groupedMeta = getGroupedByMeta(itemData, groupBy);
+ const groupKey = Object.values(groupedMeta).join('-');
+
+ if (groupKey && nodeIdentifier) {
+ return `${groupKey}-${nodeIdentifier}`;
+ }
+ if (groupKey) {
+ return groupKey;
+ }
+ if (nodeIdentifier) {
+ return nodeIdentifier;
+ }
+
+ return JSON.stringify(itemData.meta);
+}
+
+export function getGroupByEl<T extends { meta: Record<string, string> }>(
+ itemData: T,
+ groupBy: IBuilderQuery['groupBy'],
+): React.ReactNode {
+ const groupByValues: string[] = [];
+
+ groupBy.forEach((group) => {
+ const rawKey = group.key as string;
+
+ // Choose mapped key if present, otherwise use rawKey
+ const metaKey = (dotToUnder[rawKey] ?? rawKey) as keyof typeof itemData.meta;
+ const value = itemData.meta[metaKey] || itemData.meta[rawKey] || '<no-value>';
+
+ groupByValues.push(value);
+ });
+
+ return (
+ <div className={styles.itemDataGroup}>
+ {groupByValues.map((value) => (
+ <Badge
+ key={value}
+ color="secondary"
+ className={styles.itemDataGroupTagItem}
+ >
+ {value === '' ? '<no-value>' : value}
+ </Badge>
+ ))}
+ </div>
+ );
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Clusters/ClusterDetails/ClusterDetails.interfaces.ts b/frontend/src/container/InfraMonitoringK8s/Clusters/ClusterDetails/ClusterDetails.interfaces.ts
deleted file mode 100644
index 8126d50fba..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Clusters/ClusterDetails/ClusterDetails.interfaces.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { K8sClustersData } from 'api/infraMonitoring/getK8sClustersList';
-
-export type ClusterDetailsProps = {
- cluster: K8sClustersData | null;
- isModalTimeSelection: boolean;
- onClose: () => void;
-};
diff --git a/frontend/src/container/InfraMonitoringK8s/Clusters/ClusterDetails/ClusterDetails.tsx b/frontend/src/container/InfraMonitoringK8s/Clusters/ClusterDetails/ClusterDetails.tsx
deleted file mode 100644
index 22ad9eaa77..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Clusters/ClusterDetails/ClusterDetails.tsx
+++ /dev/null
@@ -1,624 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { Color, Spacing } from '@signozhq/design-tokens';
-import { Button, Divider, Drawer, Radio, Tooltip, Typography } from 'antd';
-import type { RadioChangeEvent } from 'antd/lib';
-import logEvent from 'api/common/logEvent';
-import { K8sClustersData } from 'api/infraMonitoring/getK8sClustersList';
-import { VIEW_TYPES, VIEWS } from 'components/HostMetricsDetail/constants';
-import { InfraMonitoringEvents } from 'constants/events';
-import { QueryParams } from 'constants/query';
-import {
- initialQueryBuilderFormValuesMap,
- initialQueryState,
-} from 'constants/queryBuilder';
-import ROUTES from 'constants/routes';
-import { filterDuplicateFilters } from 'container/InfraMonitoringK8s/commonUtils';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
-import { QUERY_KEYS } from 'container/InfraMonitoringK8s/EntityDetailsUtils/utils';
-import {
- useInfraMonitoringEventsFilters,
- useInfraMonitoringLogFilters,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from 'container/InfraMonitoringK8s/hooks';
-import {
- CustomTimeType,
- Time,
-} from 'container/TopNav/DateTimeSelectionV2/types';
-import { useIsDarkMode } from 'hooks/useDarkMode';
-import useUrlQuery from 'hooks/useUrlQuery';
-import GetMinMax from 'lib/getMinMax';
-import {
- BarChart2,
- ChevronsLeftRight,
- Compass,
- DraftingCompass,
- ScrollText,
- X,
-} from 'lucide-react';
-import { AppState } from 'store/reducers';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import {
- IBuilderQuery,
- TagFilterItem,
-} from 'types/api/queryBuilder/queryBuilderData';
-import {
- LogsAggregatorOperator,
- TracesAggregatorOperator,
-} from 'types/common/queryBuilder';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { v4 as uuidv4 } from 'uuid';
-
-import ClusterEvents from '../../EntityDetailsUtils/EntityEvents';
-import ClusterLogs from '../../EntityDetailsUtils/EntityLogs';
-import ClusterMetrics from '../../EntityDetailsUtils/EntityMetrics';
-import ClusterTraces from '../../EntityDetailsUtils/EntityTraces';
-import { ClusterDetailsProps } from './ClusterDetails.interfaces';
-import { clusterWidgetInfo, getClusterMetricsQueryPayload } from './constants';
-
-import '../../EntityDetailsUtils/entityDetails.styles.scss';
-
-function ClusterDetails({
- cluster,
- onClose,
- isModalTimeSelection,
-}: ClusterDetailsProps): JSX.Element {
- const { maxTime, minTime, selectedTime } = useSelector<
- AppState,
- GlobalReducer
- >((state) => state.globalTime);
-
- const startMs = useMemo(() => Math.floor(Number(minTime) / 1000000000), [
- minTime,
- ]);
- const endMs = useMemo(() => Math.floor(Number(maxTime) / 1000000000), [
- maxTime,
- ]);
-
- const urlQuery = useUrlQuery();
-
- const [modalTimeRange, setModalTimeRange] = useState(() => ({
- startTime: startMs,
- endTime: endMs,
- }));
-
- const lastSelectedInterval = useRef<Time | null>(null);
-
- const [selectedInterval, setSelectedInterval] = useState<Time>(
- lastSelectedInterval.current
- ? lastSelectedInterval.current
- : (selectedTime as Time),
- );
-
- const [selectedView, setSelectedView] = useInfraMonitoringView();
- const [logFiltersParam, setLogFiltersParam] = useInfraMonitoringLogFilters();
- const [
- tracesFiltersParam,
- setTracesFiltersParam,
- ] = useInfraMonitoringTracesFilters();
- const [
- eventsFiltersParam,
- setEventsFiltersParam,
- ] = useInfraMonitoringEventsFilters();
- const isDarkMode = useIsDarkMode();
-
- const initialFilters = useMemo(() => {
- const filters =
- selectedView === VIEW_TYPES.LOGS ? logFiltersParam : tracesFiltersParam;
- if (filters) {
- return filters;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_CLUSTER_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s_cluster_name--string--resource--false',
- },
- op: '=',
- value: cluster?.meta.k8s_cluster_name || '',
- },
- ],
- };
- }, [
- cluster?.meta.k8s_cluster_name,
- selectedView,
- logFiltersParam,
- tracesFiltersParam,
- ]);
-
- const initialEventsFilters = useMemo(() => {
- if (eventsFiltersParam) {
- return eventsFiltersParam;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_KIND,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.kind--string--resource--false',
- },
- op: '=',
- value: 'Cluster',
- },
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.name--string--resource--false',
- },
- op: '=',
- value: cluster?.meta.k8s_cluster_name || '',
- },
- ],
- };
- }, [cluster?.meta.k8s_cluster_name, eventsFiltersParam]);
-
- const [logsAndTracesFilters, setLogsAndTracesFilters] = useState<
- IBuilderQuery['filters']
- >(initialFilters);
-
- const [eventsFilters, setEventsFilters] = useState<IBuilderQuery['filters']>(
- initialEventsFilters,
- );
-
- useEffect(() => {
- if (cluster) {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Cluster,
- });
- }
- }, [cluster]);
-
- useEffect(() => {
- setLogsAndTracesFilters(initialFilters);
- setEventsFilters(initialEventsFilters);
- }, [initialFilters, initialEventsFilters]);
-
- useEffect(() => {
- const currentSelectedInterval = lastSelectedInterval.current || selectedTime;
- setSelectedInterval(currentSelectedInterval as Time);
-
- if (currentSelectedInterval !== 'custom') {
- const { maxTime, minTime } = GetMinMax(currentSelectedInterval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- }, [selectedTime, minTime, maxTime]);
-
- const handleTabChange = (e: RadioChangeEvent): void => {
- setSelectedView(e.target.value);
- setLogFiltersParam(null);
- setTracesFiltersParam(null);
- setEventsFiltersParam(null);
- logEvent(InfraMonitoringEvents.TabChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Cluster,
- view: e.target.value,
- });
- };
-
- const handleTimeChange = useCallback(
- (interval: Time | CustomTimeType, dateTimeRange?: [number, number]): void => {
- lastSelectedInterval.current = interval as Time;
- setSelectedInterval(interval as Time);
-
- if (interval === 'custom' && dateTimeRange) {
- setModalTimeRange({
- startTime: Math.floor(dateTimeRange[0] / 1000),
- endTime: Math.floor(dateTimeRange[1] / 1000),
- });
- } else {
- const { maxTime, minTime } = GetMinMax(interval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
-
- logEvent(InfraMonitoringEvents.TimeUpdated, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Cluster,
- interval,
- view: selectedView,
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeLogFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogsAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_CLUSTER_NAME].includes(item.key?.key ?? ''),
- );
- const paginationFilter = value?.items?.find(
- (item) => item.key?.key === 'id',
- );
- const newFilters = value?.items?.filter(
- (item) =>
- item.key?.key !== 'id' && item.key?.key !== QUERY_KEYS.K8S_CLUSTER_NAME,
- );
-
- if (newFilters && newFilters?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- view: InfraMonitoringEvents.LogsView,
- category: InfraMonitoringEvents.Cluster,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(newFilters || []),
- ...(paginationFilter ? [paginationFilter] : []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setLogFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeTracesFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogsAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_CLUSTER_NAME].includes(item.key?.key ?? ''),
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- view: InfraMonitoringEvents.TracesView,
- category: InfraMonitoringEvents.Cluster,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(value?.items?.filter(
- (item) => item.key?.key !== QUERY_KEYS.K8S_CLUSTER_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setTracesFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeEventsFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setEventsFilters((prevFilters) => {
- const clusterKindFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_KIND,
- );
- const clusterNameFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_NAME,
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- view: InfraMonitoringEvents.EventsView,
- category: InfraMonitoringEvents.Cluster,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- clusterKindFilter,
- clusterNameFilter,
- ...(value?.items?.filter(
- (item) =>
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_KIND &&
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setEventsFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleExplorePagesRedirect = (): void => {
- if (selectedInterval !== 'custom') {
- urlQuery.set(QueryParams.relativeTime, selectedInterval);
- } else {
- urlQuery.delete(QueryParams.relativeTime);
- urlQuery.set(QueryParams.startTime, modalTimeRange.startTime.toString());
- urlQuery.set(QueryParams.endTime, modalTimeRange.endTime.toString());
- }
-
- logEvent(InfraMonitoringEvents.ExploreClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Cluster,
- view: selectedView,
- });
-
- if (selectedView === VIEW_TYPES.LOGS) {
- const filtersWithoutPagination = {
- ...logsAndTracesFilters,
- items:
- logsAndTracesFilters?.items?.filter((item) => item.key?.key !== 'id') ||
- [],
- };
-
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.logs,
- aggregateOperator: LogsAggregatorOperator.NOOP,
- filters: filtersWithoutPagination,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.LOGS_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- } else if (selectedView === VIEW_TYPES.TRACES) {
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.traces,
- aggregateOperator: TracesAggregatorOperator.NOOP,
- filters: logsAndTracesFilters,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.TRACES_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- }
- };
-
- const handleClose = (): void => {
- lastSelectedInterval.current = null;
- setSelectedInterval(selectedTime as Time);
-
- if (selectedTime !== 'custom') {
- const { maxTime, minTime } = GetMinMax(selectedTime);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- setSelectedView(VIEW_TYPES.METRICS);
- onClose();
- };
-
- return (
- <Drawer
- width="70%"
- title={
- <>
- <Divider type="vertical" />
- <Typography.Text className="title">
- {cluster?.meta.k8s_cluster_name}
- </Typography.Text>
- </>
- }
- placement="right"
- onClose={handleClose}
- open={!!cluster}
- style={{
- overscrollBehavior: 'contain',
- background: isDarkMode ? Color.BG_INK_400 : Color.BG_VANILLA_100,
- }}
- className="entity-detail-drawer"
- destroyOnClose
- closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
- >
- {cluster && (
- <>
- <div className="entity-detail-drawer__entity">
- <div className="entity-details-grid">
- <div className="labels-row">
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Cluster Name
- </Typography.Text>
- </div>
- <div className="values-row">
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={cluster.meta.k8s_cluster_name}>
- {cluster.meta.k8s_cluster_name}
- </Tooltip>
- </Typography.Text>
- </div>
- </div>
- </div>
-
- <div className="views-tabs-container">
- <Radio.Group
- className="views-tabs"
- onChange={handleTabChange}
- value={selectedView}
- >
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.METRICS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.METRICS}
- >
- <div className="view-title">
- <BarChart2 size={14} />
- Metrics
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.LOGS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.LOGS}
- >
- <div className="view-title">
- <ScrollText size={14} />
- Logs
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.TRACES ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.TRACES}
- >
- <div className="view-title">
- <DraftingCompass size={14} />
- Traces
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.EVENTS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.EVENTS}
- >
- <div className="view-title">
- <ChevronsLeftRight size={14} />
- Events
- </div>
- </Radio.Button>
- </Radio.Group>
-
- {(selectedView === VIEW_TYPES.LOGS ||
- selectedView === VIEW_TYPES.TRACES) && (
- <Button
- icon={<Compass size={18} />}
- className="compass-button"
- onClick={handleExplorePagesRedirect}
- />
- )}
- </div>
- {selectedView === VIEW_TYPES.METRICS && (
- <ClusterMetrics<K8sClustersData>
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- entity={cluster}
- entityWidgetInfo={clusterWidgetInfo}
- getEntityQueryPayload={getClusterMetricsQueryPayload}
- category={K8sCategory.CLUSTERS}
- queryKey="clusterMetrics"
- />
- )}
- {selectedView === VIEW_TYPES.LOGS && (
- <ClusterLogs
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeLogFilters={handleChangeLogFilters}
- logFilters={logsAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKey="clusterLogs"
- category={K8sCategory.CLUSTERS}
- queryKeyFilters={[QUERY_KEYS.K8S_CLUSTER_NAME]}
- />
- )}
- {selectedView === VIEW_TYPES.TRACES && (
- <ClusterTraces
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeTracesFilters={handleChangeTracesFilters}
- tracesFilters={logsAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKey="clusterTraces"
- category={InfraMonitoringEvents.Cluster}
- queryKeyFilters={[QUERY_KEYS.K8S_CLUSTER_NAME]}
- />
- )}
- {selectedView === VIEW_TYPES.EVENTS && (
- <ClusterEvents
- timeRange={modalTimeRange}
- handleChangeEventFilters={handleChangeEventsFilters}
- filters={eventsFilters}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- category={K8sCategory.CLUSTERS}
- queryKey="clusterEvents"
- />
- )}
- </>
- )}
- </Drawer>
- );
-}
-
-export default ClusterDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/Clusters/ClusterDetails/index.ts b/frontend/src/container/InfraMonitoringK8s/Clusters/ClusterDetails/index.ts
deleted file mode 100644
index a183c3be4f..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Clusters/ClusterDetails/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import ClusterDetails from './ClusterDetails';
-
-export default ClusterDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/Clusters/K8sClustersList.styles.scss b/frontend/src/container/InfraMonitoringK8s/Clusters/K8sClustersList.styles.scss
deleted file mode 100644
index a7c5686eb0..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Clusters/K8sClustersList.styles.scss
+++ /dev/null
@@ -1,17 +0,0 @@
-.infra-monitoring-container {
- .clusters-list-table {
- .expanded-table-container {
- padding-left: 40px;
- }
-
- .ant-table-cell {
- min-width: 223px !important;
- max-width: 223px !important;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
- }
-}
diff --git a/frontend/src/container/InfraMonitoringK8s/Clusters/K8sClustersList.tsx b/frontend/src/container/InfraMonitoringK8s/Clusters/K8sClustersList.tsx
index a3722a8490..72cb75eb64 100644
--- a/frontend/src/container/InfraMonitoringK8s/Clusters/K8sClustersList.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/Clusters/K8sClustersList.tsx
@@ -1,695 +1,118 @@
-import React, { useCallback, useEffect, useMemo, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { LoadingOutlined } from '@ant-design/icons';
-import {
- Button,
- Spin,
- Table,
- TableColumnType as ColumnType,
- TablePaginationConfig,
- TableProps,
- Typography,
-} from 'antd';
-import type { SorterResult } from 'antd/es/table/interface';
-import logEvent from 'api/common/logEvent';
-import { K8sClustersListPayload } from 'api/infraMonitoring/getK8sClustersList';
+import React, { useCallback } from 'react';
import { InfraMonitoringEvents } from 'constants/events';
-import { useGetK8sClustersList } from 'hooks/infraMonitoring/useGetK8sClustersList';
-import { useGetAggregateKeys } from 'hooks/queryBuilder/useGetAggregateKeys';
-import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
-import { ChevronDown, ChevronRight } from 'lucide-react';
-import { AppState } from 'store/reducers';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { buildAbsolutePath, isModifierKeyPressed } from 'utils/app';
-import { openInNewTab } from 'utils/navigation';
-
-import emptyStateUrl from '@/assets/Icons/emptyState.svg';
-
-import { FeatureKeys } from '../../../constants/features';
-import { useAppContext } from '../../../providers/App/App';
+import { FeatureKeys } from 'constants/features';
+import { useAppContext } from 'providers/App/App';
+
+import K8sBaseDetails, { K8sDetailsFilters } from '../Base/K8sBaseDetails';
+import { K8sBaseList } from '../Base/K8sBaseList';
+import { K8sBaseFilters } from '../Base/types';
+import { InfraMonitoringEntity } from '../constants';
+import { getK8sClustersList, K8sClusterData } from './api';
import {
- GetK8sEntityToAggregateAttribute,
- INFRA_MONITORING_K8S_PARAMS_KEYS,
- K8sCategory,
-} from '../constants';
+ clusterWidgetInfo,
+ getClusterMetricsQueryPayload,
+ k8sClusterDetailsMetadataConfig,
+ k8sClusterGetEntityName,
+ k8sClusterGetSelectedItemFilters,
+ k8sClusterInitialEventsFilter,
+ k8sClusterInitialFilters,
+ k8sClusterInitialLogTracesFilter,
+} from './constants';
import {
- useInfraMonitoringClusterName,
- useInfraMonitoringCurrentPage,
- useInfraMonitoringGroupBy,
- useInfraMonitoringOrderBy,
-} from '../hooks';
-import K8sHeader from '../K8sHeader';
-import LoadingContainer from '../LoadingContainer';
-import { usePageSize } from '../utils';
-import ClusterDetails from './ClusterDetails';
-import {
- defaultAddedColumns,
- formatDataForTable,
- getK8sClustersListColumns,
- getK8sClustersListQuery,
- K8sClustersRowData,
-} from './utils';
-
-import '../InfraMonitoringK8s.styles.scss';
-import './K8sClustersList.styles.scss';
+ k8sClustersColumns,
+ k8sClustersColumnsConfig,
+ k8sClustersRenderRowData,
+} from './table.config';
function K8sClustersList({
- isFiltersVisible,
- handleFilterVisibilityChange,
- quickFiltersLastUpdated,
+ controlListPrefix,
}: {
- isFiltersVisible: boolean;
- handleFilterVisibilityChange: () => void;
- quickFiltersLastUpdated: number;
+ controlListPrefix?: React.ReactNode;
}): JSX.Element {
- const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
- (state) => state.globalTime,
- );
-
- const [currentPage, setCurrentPage] = useInfraMonitoringCurrentPage();
- const [groupBy, setGroupBy] = useInfraMonitoringGroupBy();
- const [orderBy, setOrderBy] = useInfraMonitoringOrderBy();
- const [
- selectedClusterName,
- setselectedClusterName,
- ] = useInfraMonitoringClusterName();
-
- const [filtersInitialised, setFiltersInitialised] = useState(false);
- const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
-
- const { pageSize, setPageSize } = usePageSize(K8sCategory.CLUSTERS);
-
- const [
- selectedRowData,
- setSelectedRowData,
- ] = useState<K8sClustersRowData | null>(null);
-
- const [groupByOptions, setGroupByOptions] = useState<
- { value: string; label: string }[]
- >([]);
-
- const { currentQuery } = useQueryBuilder();
-
- const queryFilters = useMemo(
- () =>
- currentQuery?.builder?.queryData[0]?.filters || {
- items: [],
- op: 'and',
- },
- [currentQuery?.builder?.queryData],
- );
-
- // Reset pagination every time quick filters are changed
- useEffect(() => {
- if (quickFiltersLastUpdated !== -1) {
- setCurrentPage(1);
- }
- }, [quickFiltersLastUpdated, setCurrentPage]);
-
const { featureFlags } = useAppContext();
const dotMetricsEnabled =
featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
?.active || false;
- const createFiltersForSelectedRowData = (
- selectedRowData: K8sClustersRowData,
- groupBy: IBuilderQuery['groupBy'],
- ): IBuilderQuery['filters'] => {
- const baseFilters: IBuilderQuery['filters'] = {
- items: [...queryFilters.items],
- op: 'and',
- };
-
- if (!selectedRowData) {
- return baseFilters;
- }
-
- const { groupedByMeta } = selectedRowData;
-
- for (const key of groupBy) {
- baseFilters.items.push({
- key: {
- key: key.key,
- type: null,
- },
- op: '=',
- value: groupedByMeta[key.key],
- id: key.key,
- });
- }
-
- return baseFilters;
- };
-
- const fetchGroupedByRowDataQuery = useMemo(() => {
- if (!selectedRowData) {
- return null;
- }
-
- const baseQuery = getK8sClustersListQuery();
-
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- return {
- ...baseQuery,
- limit: 10,
- offset: 0,
- filters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [minTime, maxTime, orderBy, selectedRowData, groupBy]);
-
- const groupedByRowDataQueryKey = useMemo(() => {
- // be careful with what you serialize from selectedRowData
- // since it's react node, it could contain circular references
- const selectedRowDataKey = JSON.stringify(selectedRowData?.groupedByMeta);
- if (selectedClusterName) {
- return [
- 'clusterList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- ];
- }
- return [
- 'clusterList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- String(minTime),
- String(maxTime),
- ];
- }, [
- queryFilters,
- orderBy,
- selectedClusterName,
- minTime,
- maxTime,
- selectedRowData,
- ]);
-
- const {
- data: groupedByRowData,
- isFetching: isFetchingGroupedByRowData,
- isLoading: isLoadingGroupedByRowData,
- isError: isErrorGroupedByRowData,
- refetch: fetchGroupedByRowData,
- } = useGetK8sClustersList(
- fetchGroupedByRowDataQuery as K8sClustersListPayload,
- {
- queryKey: groupedByRowDataQueryKey,
- enabled: !!fetchGroupedByRowDataQuery && !!selectedRowData,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const {
- data: groupByFiltersData,
- isLoading: isLoadingGroupByFilters,
- } = useGetAggregateKeys(
- {
- dataSource: currentQuery.builder.queryData[0].dataSource,
- aggregateAttribute: GetK8sEntityToAggregateAttribute(
- K8sCategory.CLUSTERS,
+ const fetchListData = useCallback(
+ async (filters: K8sBaseFilters, signal?: AbortSignal) => {
+ filters.orderBy ||= {
+ columnName: 'cpu',
+ order: 'desc',
+ };
+
+ const response = await getK8sClustersList(
+ filters,
+ signal,
+ undefined,
dotMetricsEnabled,
- ),
- aggregateOperator: 'noop',
- searchText: '',
- tagType: '',
- },
- {
- queryKey: [currentQuery.builder.queryData[0].dataSource, 'noop'],
- },
- true,
- K8sCategory.NODES,
- );
-
- const query = useMemo(() => {
- const baseQuery = getK8sClustersListQuery();
- const queryPayload = {
- ...baseQuery,
- limit: pageSize,
- offset: (currentPage - 1) * pageSize,
- filters: queryFilters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- if (groupBy.length > 0) {
- queryPayload.groupBy = groupBy;
- }
- return queryPayload;
- }, [pageSize, currentPage, queryFilters, minTime, maxTime, orderBy, groupBy]);
-
- const formattedGroupedByClustersData = useMemo(
- () =>
- formatDataForTable(groupedByRowData?.payload?.data?.records || [], groupBy),
- [groupedByRowData, groupBy],
- );
-
- const nestedClustersData = useMemo(() => {
- if (!selectedRowData || !groupedByRowData?.payload?.data.records) {
- return [];
- }
- return groupedByRowData?.payload?.data?.records || [];
- }, [groupedByRowData, selectedRowData]);
-
- const queryKey = useMemo(() => {
- if (selectedClusterName) {
- return [
- 'clusterList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- ];
- }
- return [
- 'clusterList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- String(minTime),
- String(maxTime),
- ];
- }, [
- selectedClusterName,
- pageSize,
- currentPage,
- queryFilters,
- orderBy,
- groupBy,
- minTime,
- maxTime,
- ]);
-
- const { data, isFetching, isLoading, isError } = useGetK8sClustersList(
- query as K8sClustersListPayload,
- {
- queryKey,
- enabled: !!query,
- keepPreviousData: true,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const clustersData = useMemo(() => data?.payload?.data?.records || [], [data]);
- const totalCount = data?.payload?.data?.total || 0;
-
- const formattedClustersData = useMemo(
- () => formatDataForTable(clustersData, groupBy),
- [clustersData, groupBy],
- );
-
- const columns = useMemo(() => getK8sClustersListColumns(groupBy), [groupBy]);
-
- const handleGroupByRowClick = (record: K8sClustersRowData): void => {
- setSelectedRowData(record);
-
- if (expandedRowKeys.includes(record.key)) {
- setExpandedRowKeys(expandedRowKeys.filter((key) => key !== record.key));
- } else {
- setExpandedRowKeys([record.key]);
- }
- };
-
- useEffect(() => {
- if (selectedRowData) {
- fetchGroupedByRowData();
- }
- }, [selectedRowData, fetchGroupedByRowData]);
-
- const handleTableChange: TableProps<K8sClustersRowData>['onChange'] = useCallback(
- (
- pagination: TablePaginationConfig,
- _filters: Record<string, (string | number | boolean)[] | null>,
- sorter:
- | SorterResult<K8sClustersRowData>
- | SorterResult<K8sClustersRowData>[],
- ): void => {
- if (pagination.current) {
- setCurrentPage(pagination.current);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Cluster,
- });
- }
-
- if ('field' in sorter && sorter.order) {
- setOrderBy({
- columnName: sorter.field as string,
- order: (sorter.order === 'ascend' ? 'asc' : 'desc') as 'asc' | 'desc',
- });
- } else {
- setOrderBy(null);
- }
- },
- [setCurrentPage, setOrderBy],
- );
-
- const { handleChangeQueryData } = useQueryOperations({
- index: 0,
- query: currentQuery.builder.queryData[0],
- entityVersion: '',
- });
-
- const handleFiltersChange = useCallback(
- (value: IBuilderQuery['filters']): void => {
- handleChangeQueryData('filters', value);
- if (filtersInitialised) {
- setCurrentPage(1);
- } else {
- setFiltersInitialised(true);
- }
+ );
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- category: InfraMonitoringEvents.Cluster,
- page: InfraMonitoringEvents.ListPage,
- });
- }
+ return {
+ data: response.payload?.data.records || [],
+ total: response.payload?.data.total || 0,
+ error: response.error,
+ rawData: response.payload?.data,
+ };
},
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- category: InfraMonitoringEvents.Cluster,
- page: InfraMonitoringEvents.ListPage,
- total: data?.payload?.data?.total,
- });
- }, [data?.payload?.data?.total]);
-
- const selectedClusterData = useMemo(() => {
- if (!selectedClusterName) {
- return null;
- }
- if (groupBy.length > 0) {
- // If grouped by, return the cluster from the formatted grouped by clusters data
- return (
- nestedClustersData.find(
- (cluster) => cluster.meta.k8s_cluster_name === selectedClusterName,
- ) || null
+ const fetchEntityData = useCallback(
+ async (
+ filters: K8sDetailsFilters,
+ signal?: AbortSignal,
+ ): Promise<{ data: K8sClusterData | null; error?: string | null }> => {
+ const response = await getK8sClustersList(
+ {
+ filters: filters.filters,
+ start: filters.start,
+ end: filters.end,
+ limit: 1,
+ offset: 0,
+ },
+ signal,
+ undefined,
+ dotMetricsEnabled,
);
- }
- // If not grouped by, return the cluster from the clusters data
- return (
- clustersData.find(
- (cluster) => cluster.meta.k8s_cluster_name === selectedClusterName,
- ) || null
- );
- }, [selectedClusterName, groupBy.length, clustersData, nestedClustersData]);
-
- const openClusterInNewTab = (record: K8sClustersRowData): void => {
- const newParams = new URLSearchParams(document.location.search);
- newParams.set(
- INFRA_MONITORING_K8S_PARAMS_KEYS.CLUSTER_NAME,
- record.clusterUID,
- );
- openInNewTab(
- buildAbsolutePath({
- relativePath: '',
- urlQueryString: newParams.toString(),
- }),
- );
- };
-
- const handleRowClick = (
- record: K8sClustersRowData,
- event: React.MouseEvent,
- ): void => {
- if (event && isModifierKeyPressed(event)) {
- openClusterInNewTab(record);
- return;
- }
- if (groupBy.length === 0) {
- setSelectedRowData(null);
- setselectedClusterName(record.clusterUID);
- } else {
- handleGroupByRowClick(record);
- }
-
- logEvent(InfraMonitoringEvents.ItemClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Cluster,
- });
- };
-
- const nestedColumns = useMemo(() => getK8sClustersListColumns([]), []);
-
- const isGroupedByAttribute = groupBy.length > 0;
- const handleExpandedRowViewAllClick = (): void => {
- if (!selectedRowData) {
- return;
- }
+ const records = response.payload?.data.records || [];
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- handleFiltersChange(filters);
-
- setCurrentPage(1);
- setSelectedRowData(null);
- setGroupBy([]);
- setOrderBy(null);
- };
-
- const expandedRowRender = (): JSX.Element => (
- <div className="expanded-table-container">
- {isErrorGroupedByRowData && (
- <Typography>{groupedByRowData?.error || 'Something went wrong'}</Typography>
- )}
- {isFetchingGroupedByRowData || isLoadingGroupedByRowData ? (
- <LoadingContainer />
- ) : (
- <div className="expanded-table">
- <Table
- columns={nestedColumns as ColumnType<K8sClustersRowData>[]}
- dataSource={formattedGroupedByClustersData}
- pagination={false}
- scroll={{ x: true }}
- tableLayout="fixed"
- size="small"
- loading={{
- spinning: isFetchingGroupedByRowData || isLoadingGroupedByRowData,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- showHeader={false}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => {
- if (event && isModifierKeyPressed(event)) {
- openClusterInNewTab(record);
- return;
- }
- setselectedClusterName(record.clusterUID);
- },
- className: 'expanded-clickable-row',
- })}
- />
-
- {groupedByRowData?.payload?.data?.total &&
- groupedByRowData?.payload?.data?.total > 10 ? (
- <div className="expanded-table-footer">
- <Button
- type="default"
- size="small"
- className="periscope-btn secondary"
- onClick={handleExpandedRowViewAllClick}
- >
- View All
- </Button>
- </div>
- ) : null}
- </div>
- )}
- </div>
- );
-
- const expandRowIconRenderer = ({
- expanded,
- onExpand,
- record,
- }: {
- expanded: boolean;
- onExpand: (
- record: K8sClustersRowData,
- e: React.MouseEvent<HTMLButtonElement>,
- ) => void;
- record: K8sClustersRowData;
- }): JSX.Element | null => {
- if (!isGroupedByAttribute) {
- return null;
- }
-
- return expanded ? (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronDown size={14} />
- </Button>
- ) : (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronRight size={14} />
- </Button>
- );
- };
-
- const handleCloseClusterDetail = (): void => {
- setselectedClusterName(null);
- };
-
- const handleGroupByChange = useCallback(
- (value: IBuilderQuery['groupBy']) => {
- const newGroupBy = [];
-
- for (let index = 0; index < value.length; index++) {
- const element = (value[index] as unknown) as string;
-
- const key = groupByFiltersData?.payload?.attributeKeys?.find(
- (key) => key.key === element,
- );
-
- if (key) {
- newGroupBy.push(key);
- }
- }
-
- // Reset pagination on switching to groupBy
- setCurrentPage(1);
- setGroupBy(newGroupBy);
- setExpandedRowKeys([]);
- logEvent(InfraMonitoringEvents.GroupByChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Cluster,
- });
+ return {
+ data: records.length > 0 ? records[0] : null,
+ error: response.error,
+ };
},
- [groupByFiltersData, setCurrentPage, setGroupBy],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- if (groupByFiltersData?.payload) {
- setGroupByOptions(
- groupByFiltersData?.payload?.attributeKeys?.map((filter) => ({
- value: filter.key,
- label: filter.key,
- })) || [],
- );
- }
- }, [groupByFiltersData]);
-
- const onPaginationChange = (page: number, pageSize: number): void => {
- setCurrentPage(page);
- setPageSize(pageSize);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Cluster,
- });
- };
-
- const showTableLoadingState =
- (isFetching || isLoading) && formattedClustersData.length === 0;
-
return (
- <div className="k8s-list">
- <K8sHeader
- isFiltersVisible={isFiltersVisible}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- defaultAddedColumns={defaultAddedColumns}
- handleFiltersChange={handleFiltersChange}
- groupByOptions={groupByOptions}
- isLoadingGroupByFilters={isLoadingGroupByFilters}
- handleGroupByChange={handleGroupByChange}
- selectedGroupBy={groupBy}
- entity={K8sCategory.NODES}
- showAutoRefresh={!selectedClusterData}
- />
- {isError && <Typography>{data?.error || 'Something went wrong'}</Typography>}
-
- <Table
- className="k8s-list-table clusters-list-table"
- dataSource={showTableLoadingState ? [] : formattedClustersData}
- columns={columns}
- pagination={{
- current: currentPage,
- pageSize,
- total: totalCount,
- showSizeChanger: true,
- hideOnSinglePage: false,
- onChange: onPaginationChange,
- }}
- scroll={{ x: true }}
- loading={{
- spinning: showTableLoadingState,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- locale={{
- emptyText: showTableLoadingState ? null : (
- <div className="no-filtered-hosts-message-container">
- <div className="no-filtered-hosts-message-content">
- <img
- src={emptyStateUrl}
- alt="thinking-emoji"
- className="empty-state-svg"
- />
-
- <Typography.Text className="no-filtered-hosts-message">
- This query had no results. Edit your query and try again!
- </Typography.Text>
- </div>
- </div>
- ),
- }}
- tableLayout="fixed"
- onChange={handleTableChange}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => handleRowClick(record, event),
- className: 'clickable-row',
- })}
- expandable={{
- expandedRowRender: isGroupedByAttribute ? expandedRowRender : undefined,
- expandIcon: expandRowIconRenderer,
- expandedRowKeys,
- }}
+ <>
+ <K8sBaseList<K8sClusterData>
+ controlListPrefix={controlListPrefix}
+ entity={InfraMonitoringEntity.CLUSTERS}
+ tableColumnsDefinitions={k8sClustersColumns}
+ tableColumns={k8sClustersColumnsConfig}
+ fetchListData={fetchListData}
+ renderRowData={k8sClustersRenderRowData}
+ eventCategory={InfraMonitoringEvents.Cluster}
/>
- <ClusterDetails
- cluster={selectedClusterData}
- isModalTimeSelection
- onClose={handleCloseClusterDetail}
+ <K8sBaseDetails<K8sClusterData>
+ category={InfraMonitoringEntity.CLUSTERS}
+ eventCategory={InfraMonitoringEvents.Cluster}
+ getSelectedItemFilters={k8sClusterGetSelectedItemFilters}
+ fetchEntityData={fetchEntityData}
+ getEntityName={k8sClusterGetEntityName}
+ getInitialLogTracesFilters={k8sClusterInitialLogTracesFilter}
+ getInitialEventsFilters={k8sClusterInitialEventsFilter}
+ primaryFilterKeys={k8sClusterInitialFilters}
+ metadataConfig={k8sClusterDetailsMetadataConfig}
+ entityWidgetInfo={clusterWidgetInfo}
+ getEntityQueryPayload={getClusterMetricsQueryPayload}
+ queryKeyPrefix="cluster"
/>
- </div>
+ </>
);
}
diff --git a/frontend/src/container/InfraMonitoringK8s/Clusters/api.ts b/frontend/src/container/InfraMonitoringK8s/Clusters/api.ts
new file mode 100644
index 0000000000..685bc6a032
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Clusters/api.ts
@@ -0,0 +1,125 @@
+import axios from 'api';
+import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
+import { UnderscoreToDotMap } from 'api/utils';
+import { AxiosError } from 'axios';
+import { ErrorResponse, SuccessResponse } from 'types/api';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
+
+import { K8sBaseFilters } from '../Base/types';
+
+export interface K8sClustersListPayload {
+ filters: TagFilter;
+ groupBy?: BaseAutocompleteData[];
+ offset?: number;
+ limit?: number;
+ orderBy?: {
+ columnName: string;
+ order: 'asc' | 'desc';
+ };
+}
+
+export interface K8sClusterData {
+ clusterUID: string;
+ cpuUsage: number;
+ cpuAllocatable: number;
+ memoryUsage: number;
+ memoryAllocatable: number;
+ meta: {
+ k8s_cluster_name: string;
+ k8s_cluster_uid: string;
+ };
+}
+
+export interface K8sClustersListResponse {
+ status: string;
+ data: {
+ type: string;
+ records: K8sClusterData[];
+ groups: null;
+ total: number;
+ sentAnyHostMetricsData: boolean;
+ isSendingK8SAgentMetrics: boolean;
+ };
+}
+
+// TODO(H4ad): Erase this whole file when migrating to openapi
+export const clustersMetaMap = [
+ { dot: 'k8s.cluster.name', under: 'k8s_cluster_name' },
+ { dot: 'k8s.cluster.uid', under: 'k8s_cluster_uid' },
+] as const;
+
+export function mapClustersMeta(
+ raw: Record<string, unknown>,
+): K8sClusterData['meta'] {
+ const out: Record<string, unknown> = { ...raw };
+ clustersMetaMap.forEach(({ dot, under }) => {
+ if (dot in raw) {
+ const v = raw[dot];
+ out[under] = typeof v === 'string' ? v : raw[under];
+ }
+ });
+ return out as K8sClusterData['meta'];
+}
+
+export const getK8sClustersList = async (
+ props: K8sBaseFilters,
+ signal?: AbortSignal,
+ headers?: Record<string, string>,
+ dotMetricsEnabled = false,
+): Promise<SuccessResponse<K8sClustersListResponse> | ErrorResponse> => {
+ try {
+ const requestProps = dotMetricsEnabled
+ ? {
+ ...props,
+ filters: {
+ ...props.filters,
+ items: props.filters.items.reduce<typeof props.filters.items>(
+ (acc, item) => {
+ if (item.value === undefined) {
+ return acc;
+ }
+ if (
+ item.key &&
+ typeof item.key === 'object' &&
+ 'key' in item.key &&
+ typeof item.key.key === 'string'
+ ) {
+ const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
+ acc.push({
+ ...item,
+ key: { ...item.key, key: mappedKey },
+ });
+ } else {
+ acc.push(item);
+ }
+ return acc;
+ },
+ [] as typeof props.filters.items,
+ ),
+ },
+ }
+ : props;
+
+ const response = await axios.post('/clusters/list', requestProps, {
+ signal,
+ headers,
+ });
+ const payload: K8sClustersListResponse = response.data;
+
+ payload.data.records = payload.data.records.map((record) => ({
+ ...record,
+ meta: mapClustersMeta(record.meta as Record<string, unknown>),
+ }));
+
+ return {
+ statusCode: 200,
+ error: null,
+ message: 'Success',
+ payload,
+ params: requestProps,
+ };
+ } catch (error) {
+ return ErrorResponseHandler(error as AxiosError);
+ }
+};
diff --git a/frontend/src/container/InfraMonitoringK8s/Clusters/ClusterDetails/constants.ts b/frontend/src/container/InfraMonitoringK8s/Clusters/constants.ts
similarity index 96%
rename from frontend/src/container/InfraMonitoringK8s/Clusters/ClusterDetails/constants.ts
rename to frontend/src/container/InfraMonitoringK8s/Clusters/constants.ts
index 04a4588c82..b7868f7378 100644
--- a/frontend/src/container/InfraMonitoringK8s/Clusters/ClusterDetails/constants.ts
+++ b/frontend/src/container/InfraMonitoringK8s/Clusters/constants.ts
@@ -1,11 +1,57 @@
-import { K8sClustersData } from 'api/infraMonitoring/getK8sClustersList';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { v4 } from 'uuid';
+import {
+ createFilterItem,
+ K8sDetailsMetadataConfig,
+} from '../Base/K8sBaseDetails';
+import { QUERY_KEYS } from '../EntityDetailsUtils/utils';
+import { K8sClusterData } from './api';
+
+export const k8sClusterGetSelectedItemFilters = (
+ selectedItemId: string,
+): TagFilter => ({
+ op: 'AND',
+ items: [
+ {
+ id: 'k8s_cluster_name',
+ key: {
+ key: 'k8s_cluster_name',
+ type: null,
+ },
+ op: '=',
+ value: selectedItemId,
+ },
+ ],
+});
+
+export const k8sClusterDetailsMetadataConfig: K8sDetailsMetadataConfig<K8sClusterData>[] = [
+ { label: 'Cluster Name', getValue: (p): string => p.meta.k8s_cluster_name },
+];
+
+export const k8sClusterInitialFilters = [QUERY_KEYS.K8S_CLUSTER_NAME];
+
+export const k8sClusterInitialEventsFilter = (
+ item: K8sClusterData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_KIND, 'Cluster'),
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_NAME, item.meta.k8s_cluster_name),
+];
+
+export const k8sClusterInitialLogTracesFilter = (
+ item: K8sClusterData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(QUERY_KEYS.K8S_CLUSTER_NAME, item.meta.k8s_cluster_name),
+];
+
+export const k8sClusterGetEntityName = (item: K8sClusterData): string =>
+ item.meta.k8s_cluster_name;
+
export const clusterWidgetInfo = [
{
title: 'CPU Usage, allocatable',
@@ -42,7 +88,7 @@ export const clusterWidgetInfo = [
];
export const getClusterMetricsQueryPayload = (
- cluster: K8sClustersData,
+ cluster: K8sClusterData,
start: number,
end: number,
dotMetricsEnabled: boolean,
diff --git a/frontend/src/container/InfraMonitoringK8s/Clusters/table.config.tsx b/frontend/src/container/InfraMonitoringK8s/Clusters/table.config.tsx
new file mode 100644
index 0000000000..4edab75d13
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Clusters/table.config.tsx
@@ -0,0 +1,183 @@
+import { TableColumnType as ColumnType, Tooltip } from 'antd';
+import { Group } from 'lucide-react';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+
+import { K8sRenderedRowData } from '../Base/types';
+import { IEntityColumn } from '../Base/useInfraMonitoringTableColumnsStore';
+import { getGroupByEl, getGroupedByMeta, getRowKey } from '../Base/utils';
+import { formatBytes, ValidateColumnValueWrapper } from '../commonUtils';
+import { K8sClusterData, K8sClustersListPayload } from './api';
+
+import styles from './table.module.scss';
+
+export interface K8sClustersRowData {
+ key: string;
+ itemKey: string;
+ clusterUID: string;
+ clusterName: React.ReactNode;
+ cpu: React.ReactNode;
+ cpu_allocatable: React.ReactNode;
+ memory: React.ReactNode;
+ memory_allocatable: React.ReactNode;
+ groupedByMeta?: Record<string, string>;
+}
+
+export const k8sClustersColumns: IEntityColumn[] = [
+ {
+ label: 'Cluster Group',
+ value: 'clusterGroup',
+ id: 'clusterGroup',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-collapse',
+ },
+ {
+ label: 'Cluster Name',
+ value: 'clusterName',
+ id: 'clusterName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-expand',
+ },
+ {
+ label: 'CPU Usage (cores)',
+ value: 'cpu',
+ id: 'cpu',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Alloc (cores)',
+ value: 'cpu_allocatable',
+ id: 'cpu_allocatable',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Memory Usage (WSS)',
+ value: 'memory',
+ id: 'memory',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Memory Alloc (bytes)',
+ value: 'memory_allocatable',
+ id: 'memory_allocatable',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+];
+
+export const getK8sClustersListQuery = (): K8sClustersListPayload => ({
+ filters: {
+ items: [],
+ op: 'and',
+ },
+ orderBy: { columnName: 'cpu', order: 'desc' },
+});
+
+export const k8sClustersColumnsConfig: ColumnType<K8sRenderedRowData>[] = [
+ {
+ title: (
+ <div className={styles.entityGroupHeader}>
+ <Group size={14} /> CLUSTER GROUP
+ </div>
+ ),
+ dataIndex: 'clusterGroup',
+ key: 'clusterGroup',
+ ellipsis: true,
+ width: 150,
+ align: 'left',
+ sorter: false,
+ },
+ {
+ title: <div>Cluster Name</div>,
+ dataIndex: 'clusterName',
+ key: 'clusterName',
+ ellipsis: true,
+ width: 150,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Usage (cores)</div>,
+ dataIndex: 'cpu',
+ key: 'cpu',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Alloc (cores)</div>,
+ dataIndex: 'cpu_allocatable',
+ key: 'cpu_allocatable',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Memory Usage (WSS)</div>,
+ dataIndex: 'memory',
+ key: 'memory',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Memory Allocatable</div>,
+ dataIndex: 'memory_allocatable',
+ key: 'memory_allocatable',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+];
+
+export const k8sClustersRenderRowData = (
+ cluster: K8sClusterData,
+ groupBy: BaseAutocompleteData[],
+): K8sRenderedRowData => ({
+ key: getRowKey(
+ cluster,
+ () =>
+ cluster.clusterUID ||
+ cluster.meta.k8s_cluster_uid ||
+ cluster.meta.k8s_cluster_name,
+ groupBy,
+ ),
+ itemKey: cluster.meta.k8s_cluster_name,
+ clusterUID: cluster.clusterUID || cluster.meta.k8s_cluster_uid,
+ clusterName: (
+ <Tooltip title={cluster.meta.k8s_cluster_name}>
+ {cluster.meta.k8s_cluster_name || ''}
+ </Tooltip>
+ ),
+ cpu: (
+ <ValidateColumnValueWrapper value={cluster.cpuUsage}>
+ {cluster.cpuUsage}
+ </ValidateColumnValueWrapper>
+ ),
+ memory: (
+ <ValidateColumnValueWrapper value={cluster.memoryUsage}>
+ {formatBytes(cluster.memoryUsage)}
+ </ValidateColumnValueWrapper>
+ ),
+ cpu_allocatable: (
+ <ValidateColumnValueWrapper value={cluster.cpuAllocatable}>
+ {cluster.cpuAllocatable}
+ </ValidateColumnValueWrapper>
+ ),
+ memory_allocatable: (
+ <ValidateColumnValueWrapper value={cluster.memoryAllocatable}>
+ {formatBytes(cluster.memoryAllocatable)}
+ </ValidateColumnValueWrapper>
+ ),
+ clusterGroup: getGroupByEl(cluster, groupBy),
+ ...cluster.meta,
+ groupedByMeta: getGroupedByMeta(cluster, groupBy),
+});
diff --git a/frontend/src/container/InfraMonitoringK8s/Clusters/table.module.scss b/frontend/src/container/InfraMonitoringK8s/Clusters/table.module.scss
new file mode 100644
index 0000000000..a2cdaf51c3
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Clusters/table.module.scss
@@ -0,0 +1,6 @@
+.entityGroupHeader {
+ display: flex;
+ align-items: center;
+ padding-left: var(--spacing-5);
+ gap: var(--spacing-5);
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Clusters/utils.tsx b/frontend/src/container/InfraMonitoringK8s/Clusters/utils.tsx
deleted file mode 100644
index 71d7bf849c..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Clusters/utils.tsx
+++ /dev/null
@@ -1,206 +0,0 @@
-import { Color } from '@signozhq/design-tokens';
-import { TableColumnType as ColumnType, Tag, Tooltip } from 'antd';
-import {
- K8sClustersData,
- K8sClustersListPayload,
-} from 'api/infraMonitoring/getK8sClustersList';
-import { Group } from 'lucide-react';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-
-import { formatBytes, ValidateColumnValueWrapper } from '../commonUtils';
-import { IEntityColumn } from '../utils';
-
-export const defaultAddedColumns: IEntityColumn[] = [
- {
- label: 'Cluster Name',
- value: 'clusterName',
- id: 'cluster',
- canRemove: false,
- },
- {
- label: 'CPU Usage (cores)',
- value: 'cpu',
- id: 'cpu',
- canRemove: false,
- },
- {
- label: 'CPU Allocatable (cores)',
- value: 'cpu_allocatable',
- id: 'cpu_allocatable',
- canRemove: false,
- },
- {
- label: 'Mem Usage (WSS)',
- value: 'memory',
- id: 'memory',
- canRemove: false,
- },
- {
- label: 'Mem Allocatable',
- value: 'memory_allocatable',
- id: 'memory_allocatable',
- canRemove: false,
- },
-];
-
-export interface K8sClustersRowData {
- key: string;
- clusterUID: string;
- clusterName: React.ReactNode;
- cpu: React.ReactNode;
- memory: React.ReactNode;
- cpu_allocatable: React.ReactNode;
- memory_allocatable: React.ReactNode;
- groupedByMeta?: any;
-}
-
-const clusterGroupColumnConfig = {
- title: (
- <div className="column-header entity-group-header">
- <Group size={14} /> CLUSTER GROUP
- </div>
- ),
- dataIndex: 'clusterGroup',
- key: 'clusterGroup',
- ellipsis: true,
- width: 150,
- align: 'left',
- sorter: false,
- className: 'column entity-group-header',
-};
-
-export const getK8sClustersListQuery = (): K8sClustersListPayload => ({
- filters: {
- items: [],
- op: 'and',
- },
- orderBy: { columnName: 'cpu', order: 'desc' },
-});
-
-const columnsConfig = [
- {
- title: <div className="column-header-left">Cluster Name</div>,
- dataIndex: 'clusterName',
- key: 'clusterName',
- ellipsis: true,
- width: 150,
- sorter: false,
- align: 'left',
- },
- {
- title: <div className="column-header-left">CPU Utilization (cores)</div>,
- dataIndex: 'cpu',
- key: 'cpu',
- width: 80,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header-left">CPU Allocatable (cores)</div>,
- dataIndex: 'cpu_allocatable',
- key: 'cpu_allocatable',
- width: 80,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header-left">Memory Utilization (WSS)</div>,
- dataIndex: 'memory',
- key: 'memory',
- width: 80,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header-left">Memory Allocatable</div>,
- dataIndex: 'memory_allocatable',
- key: 'memory_allocatable',
- width: 80,
- sorter: true,
- align: 'left',
- },
-];
-
-export const getK8sClustersListColumns = (
- groupBy: IBuilderQuery['groupBy'],
-): ColumnType<K8sClustersRowData>[] => {
- if (groupBy.length > 0) {
- const filteredColumns = [...columnsConfig].filter(
- (column) => column.key !== 'clusterName',
- );
- filteredColumns.unshift(clusterGroupColumnConfig);
- return filteredColumns as ColumnType<K8sClustersRowData>[];
- }
-
- return columnsConfig as ColumnType<K8sClustersRowData>[];
-};
-
-const dotToUnder: Record<string, keyof K8sClustersData['meta']> = {
- 'k8s.cluster.name': 'k8s_cluster_name',
- 'k8s.cluster.uid': 'k8s_cluster_uid',
-};
-
-const getGroupByEle = (
- cluster: K8sClustersData,
- groupBy: IBuilderQuery['groupBy'],
-): React.ReactNode => {
- const groupByValues: string[] = [];
-
- groupBy.forEach((group) => {
- const rawKey = group.key as string;
-
- // Choose mapped key if present, otherwise use rawKey
- const metaKey = (dotToUnder[rawKey] ?? rawKey) as keyof typeof cluster.meta;
- const value = cluster.meta[metaKey];
-
- groupByValues.push(value);
- });
-
- return (
- <div className="pod-group">
- {groupByValues.map((value) => (
- <Tag key={value} color={Color.BG_SLATE_400} className="pod-group-tag-item">
- {value === '' ? '<no-value>' : value}
- </Tag>
- ))}
- </div>
- );
-};
-
-export const formatDataForTable = (
- data: K8sClustersData[],
- groupBy: IBuilderQuery['groupBy'],
-): K8sClustersRowData[] =>
- data.map((cluster, index) => ({
- key: index.toString(),
- clusterUID: cluster.meta.k8s_cluster_name,
- clusterName: (
- <Tooltip title={cluster.meta.k8s_cluster_name}>
- {cluster.meta.k8s_cluster_name}
- </Tooltip>
- ),
- cpu: (
- <ValidateColumnValueWrapper value={cluster.cpuUsage}>
- {cluster.cpuUsage}
- </ValidateColumnValueWrapper>
- ),
- memory: (
- <ValidateColumnValueWrapper value={cluster.memoryUsage}>
- {formatBytes(cluster.memoryUsage)}
- </ValidateColumnValueWrapper>
- ),
- cpu_allocatable: (
- <ValidateColumnValueWrapper value={cluster.cpuAllocatable}>
- {cluster.cpuAllocatable}
- </ValidateColumnValueWrapper>
- ),
- memory_allocatable: (
- <ValidateColumnValueWrapper value={cluster.memoryAllocatable}>
- {formatBytes(cluster.memoryAllocatable)}
- </ValidateColumnValueWrapper>
- ),
- clusterGroup: getGroupByEle(cluster, groupBy),
- meta: cluster.meta,
- ...cluster.meta,
- groupedByMeta: cluster.meta,
- }));
diff --git a/frontend/src/container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/DaemonSetDetails.interfaces.ts b/frontend/src/container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/DaemonSetDetails.interfaces.ts
deleted file mode 100644
index 6b21b2f77e..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/DaemonSetDetails.interfaces.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { K8sDaemonSetsData } from 'api/infraMonitoring/getK8sDaemonSetsList';
-
-export type DaemonSetDetailsProps = {
- daemonSet: K8sDaemonSetsData | null;
- isModalTimeSelection: boolean;
- onClose: () => void;
-};
diff --git a/frontend/src/container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/DaemonSetDetails.tsx b/frontend/src/container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/DaemonSetDetails.tsx
deleted file mode 100644
index 89196cfd4a..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/DaemonSetDetails.tsx
+++ /dev/null
@@ -1,667 +0,0 @@
-/* eslint-disable sonarjs/no-identical-functions */
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { Color, Spacing } from '@signozhq/design-tokens';
-import { Button, Divider, Drawer, Radio, Tooltip, Typography } from 'antd';
-import type { RadioChangeEvent } from 'antd/lib';
-import logEvent from 'api/common/logEvent';
-import { VIEW_TYPES, VIEWS } from 'components/HostMetricsDetail/constants';
-import { InfraMonitoringEvents } from 'constants/events';
-import { QueryParams } from 'constants/query';
-import {
- initialQueryBuilderFormValuesMap,
- initialQueryState,
-} from 'constants/queryBuilder';
-import ROUTES from 'constants/routes';
-import { filterDuplicateFilters } from 'container/InfraMonitoringK8s/commonUtils';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
-import {
- useInfraMonitoringEventsFilters,
- useInfraMonitoringLogFilters,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from 'container/InfraMonitoringK8s/hooks';
-import {
- CustomTimeType,
- Time,
-} from 'container/TopNav/DateTimeSelectionV2/types';
-import { useIsDarkMode } from 'hooks/useDarkMode';
-import useUrlQuery from 'hooks/useUrlQuery';
-import GetMinMax from 'lib/getMinMax';
-import {
- BarChart2,
- ChevronsLeftRight,
- Compass,
- DraftingCompass,
- ScrollText,
- X,
-} from 'lucide-react';
-import { AppState } from 'store/reducers';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import {
- IBuilderQuery,
- TagFilterItem,
-} from 'types/api/queryBuilder/queryBuilderData';
-import {
- LogsAggregatorOperator,
- TracesAggregatorOperator,
-} from 'types/common/queryBuilder';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { v4 as uuidv4 } from 'uuid';
-
-import DaemonSetEvents from '../../EntityDetailsUtils/EntityEvents';
-import DaemonSetLogs from '../../EntityDetailsUtils/EntityLogs';
-import DaemonSetMetrics from '../../EntityDetailsUtils/EntityMetrics';
-import DaemonSetTraces from '../../EntityDetailsUtils/EntityTraces';
-import { QUERY_KEYS } from '../../EntityDetailsUtils/utils';
-import {
- daemonSetWidgetInfo,
- getDaemonSetMetricsQueryPayload,
-} from './constants';
-import { DaemonSetDetailsProps } from './DaemonSetDetails.interfaces';
-
-import '../../EntityDetailsUtils/entityDetails.styles.scss';
-
-function DaemonSetDetails({
- daemonSet,
- onClose,
- isModalTimeSelection,
-}: DaemonSetDetailsProps): JSX.Element {
- const { maxTime, minTime, selectedTime } = useSelector<
- AppState,
- GlobalReducer
- >((state) => state.globalTime);
-
- const startMs = useMemo(() => Math.floor(Number(minTime) / 1000000000), [
- minTime,
- ]);
- const endMs = useMemo(() => Math.floor(Number(maxTime) / 1000000000), [
- maxTime,
- ]);
-
- const urlQuery = useUrlQuery();
-
- const [modalTimeRange, setModalTimeRange] = useState(() => ({
- startTime: startMs,
- endTime: endMs,
- }));
-
- const lastSelectedInterval = useRef<Time | null>(null);
-
- const [selectedInterval, setSelectedInterval] = useState<Time>(
- lastSelectedInterval.current
- ? lastSelectedInterval.current
- : (selectedTime as Time),
- );
-
- const [selectedView, setSelectedView] = useInfraMonitoringView();
- const [logFiltersParam, setLogFiltersParam] = useInfraMonitoringLogFilters();
- const [
- tracesFiltersParam,
- setTracesFiltersParam,
- ] = useInfraMonitoringTracesFilters();
- const [
- eventsFiltersParam,
- setEventsFiltersParam,
- ] = useInfraMonitoringEventsFilters();
- const isDarkMode = useIsDarkMode();
-
- const initialFilters = useMemo(() => {
- const filters =
- selectedView === VIEW_TYPES.LOGS ? logFiltersParam : tracesFiltersParam;
- if (filters) {
- return filters;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_DAEMON_SET_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s_daemonSet_name--string--resource--false',
- },
- op: '=',
- value: daemonSet?.meta.k8s_daemonset_name || '',
- },
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_NAMESPACE_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s_daemonSet_name--string--resource--false',
- },
- op: '=',
- value: daemonSet?.meta.k8s_namespace_name || '',
- },
- ],
- };
- }, [
- daemonSet?.meta.k8s_daemonset_name,
- daemonSet?.meta.k8s_namespace_name,
- selectedView,
- logFiltersParam,
- tracesFiltersParam,
- ]);
-
- const initialEventsFilters = useMemo(() => {
- if (eventsFiltersParam) {
- return eventsFiltersParam;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_KIND,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.kind--string--resource--false',
- },
- op: '=',
- value: 'DaemonSet',
- },
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.name--string--resource--false',
- },
- op: '=',
- value: daemonSet?.meta.k8s_daemonset_name || '',
- },
- ],
- };
- }, [daemonSet?.meta.k8s_daemonset_name, eventsFiltersParam]);
-
- const [logAndTracesFilters, setLogAndTracesFilters] = useState<
- IBuilderQuery['filters']
- >(initialFilters);
-
- const [eventsFilters, setEventsFilters] = useState<IBuilderQuery['filters']>(
- initialEventsFilters,
- );
-
- useEffect(() => {
- if (daemonSet) {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.DaemonSet,
- });
- }
- }, [daemonSet]);
-
- useEffect(() => {
- setLogAndTracesFilters(initialFilters);
- setEventsFilters(initialEventsFilters);
- }, [initialFilters, initialEventsFilters]);
-
- useEffect(() => {
- const currentSelectedInterval = lastSelectedInterval.current || selectedTime;
- setSelectedInterval(currentSelectedInterval as Time);
-
- if (currentSelectedInterval !== 'custom') {
- const { maxTime, minTime } = GetMinMax(currentSelectedInterval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- }, [selectedTime, minTime, maxTime]);
-
- const handleTabChange = (e: RadioChangeEvent): void => {
- setSelectedView(e.target.value);
- setLogFiltersParam(null);
- setTracesFiltersParam(null);
- setEventsFiltersParam(null);
- logEvent(InfraMonitoringEvents.TabChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.DaemonSet,
- view: e.target.value,
- });
- };
-
- const handleTimeChange = useCallback(
- (interval: Time | CustomTimeType, dateTimeRange?: [number, number]): void => {
- lastSelectedInterval.current = interval as Time;
- setSelectedInterval(interval as Time);
-
- if (interval === 'custom' && dateTimeRange) {
- setModalTimeRange({
- startTime: Math.floor(dateTimeRange[0] / 1000),
- endTime: Math.floor(dateTimeRange[1] / 1000),
- });
- } else {
- const { maxTime, minTime } = GetMinMax(interval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
-
- logEvent(InfraMonitoringEvents.TimeUpdated, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.DaemonSet,
- interval,
- view: selectedView,
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeLogFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_DAEMON_SET_NAME, QUERY_KEYS.K8S_NAMESPACE_NAME].includes(
- item.key?.key ?? '',
- ),
- );
- const paginationFilter = value?.items?.find(
- (item) => item.key?.key === 'id',
- );
- const newFilters = value?.items?.filter(
- (item) =>
- item.key?.key !== 'id' &&
- item.key?.key !== QUERY_KEYS.K8S_DAEMON_SET_NAME,
- );
-
- if (newFilters && newFilters?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.DaemonSet,
- view: InfraMonitoringEvents.LogsView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(newFilters || []),
- ...(paginationFilter ? [paginationFilter] : []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setLogFiltersParam(updatedFilters);
- setSelectedView(view);
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeTracesFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_DAEMON_SET_NAME, QUERY_KEYS.K8S_NAMESPACE_NAME].includes(
- item.key?.key ?? '',
- ),
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.DaemonSet,
- view: InfraMonitoringEvents.TracesView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(value?.items?.filter(
- (item) => item.key?.key !== QUERY_KEYS.K8S_DAEMON_SET_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setTracesFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeEventsFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setEventsFilters((prevFilters) => {
- const daemonSetKindFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_KIND,
- );
- const daemonSetNameFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_NAME,
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.DaemonSet,
- view: InfraMonitoringEvents.EventsView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: [
- daemonSetKindFilter,
- daemonSetNameFilter,
- ...(value?.items?.filter(
- (item) =>
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_KIND &&
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- };
-
- setEventsFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleExplorePagesRedirect = (): void => {
- if (selectedInterval !== 'custom') {
- urlQuery.set(QueryParams.relativeTime, selectedInterval);
- } else {
- urlQuery.delete(QueryParams.relativeTime);
- urlQuery.set(QueryParams.startTime, modalTimeRange.startTime.toString());
- urlQuery.set(QueryParams.endTime, modalTimeRange.endTime.toString());
- }
-
- logEvent(InfraMonitoringEvents.ExploreClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.DaemonSet,
- view: selectedView,
- });
-
- if (selectedView === VIEW_TYPES.LOGS) {
- const filtersWithoutPagination = {
- ...logAndTracesFilters,
- items: logAndTracesFilters?.items?.filter((item) => item.key?.key !== 'id'),
- };
-
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.logs,
- aggregateOperator: LogsAggregatorOperator.NOOP,
- filters: filtersWithoutPagination,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.LOGS_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- } else if (selectedView === VIEW_TYPES.TRACES) {
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.traces,
- aggregateOperator: TracesAggregatorOperator.NOOP,
- filters: logAndTracesFilters,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.TRACES_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- }
- };
-
- const handleClose = (): void => {
- lastSelectedInterval.current = null;
- setSelectedInterval(selectedTime as Time);
-
- if (selectedTime !== 'custom') {
- const { maxTime, minTime } = GetMinMax(selectedTime);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- setSelectedView(VIEW_TYPES.METRICS);
- onClose();
- };
-
- return (
- <Drawer
- width="70%"
- title={
- <>
- <Divider type="vertical" />
- <Typography.Text className="title">
- {daemonSet?.meta.k8s_daemonset_name}
- </Typography.Text>
- </>
- }
- placement="right"
- onClose={handleClose}
- open={!!daemonSet}
- style={{
- overscrollBehavior: 'contain',
- background: isDarkMode ? Color.BG_INK_400 : Color.BG_VANILLA_100,
- }}
- className="entity-detail-drawer"
- destroyOnClose
- closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
- >
- {daemonSet && (
- <>
- <div className="entity-detail-drawer__entity">
- <div className="entity-details-grid">
- <div className="labels-row">
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Daemonset Name
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Cluster Name
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Namespace Name
- </Typography.Text>
- </div>
- <div className="values-row">
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={daemonSet.meta.k8s_daemonset_name}>
- {daemonSet.meta.k8s_daemonset_name}
- </Tooltip>
- </Typography.Text>
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={daemonSet.meta.k8s_cluster_name}>
- {daemonSet.meta.k8s_cluster_name}
- </Tooltip>
- </Typography.Text>
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={daemonSet.meta.k8s_namespace_name}>
- {daemonSet.meta.k8s_namespace_name}
- </Tooltip>
- </Typography.Text>
- </div>
- </div>
- </div>
-
- <div className="views-tabs-container">
- <Radio.Group
- className="views-tabs"
- onChange={handleTabChange}
- value={selectedView}
- >
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.METRICS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.METRICS}
- >
- <div className="view-title">
- <BarChart2 size={14} />
- Metrics
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.LOGS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.LOGS}
- >
- <div className="view-title">
- <ScrollText size={14} />
- Logs
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.TRACES ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.TRACES}
- >
- <div className="view-title">
- <DraftingCompass size={14} />
- Traces
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.EVENTS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.EVENTS}
- >
- <div className="view-title">
- <ChevronsLeftRight size={14} />
- Events
- </div>
- </Radio.Button>
- </Radio.Group>
-
- {(selectedView === VIEW_TYPES.LOGS ||
- selectedView === VIEW_TYPES.TRACES) && (
- <Button
- icon={<Compass size={18} />}
- className="compass-button"
- onClick={handleExplorePagesRedirect}
- />
- )}
- </div>
- {selectedView === VIEW_TYPES.METRICS && (
- <DaemonSetMetrics
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- entity={daemonSet}
- entityWidgetInfo={daemonSetWidgetInfo}
- getEntityQueryPayload={getDaemonSetMetricsQueryPayload}
- category={K8sCategory.DAEMONSETS}
- queryKey="daemonsetMetrics"
- />
- )}
- {selectedView === VIEW_TYPES.LOGS && (
- <DaemonSetLogs
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeLogFilters={handleChangeLogFilters}
- logFilters={logAndTracesFilters}
- selectedInterval={selectedInterval}
- category={K8sCategory.DAEMONSETS}
- queryKey="daemonsetLogs"
- queryKeyFilters={[
- QUERY_KEYS.K8S_DAEMON_SET_NAME,
- QUERY_KEYS.K8S_NAMESPACE_NAME,
- ]}
- />
- )}
- {selectedView === VIEW_TYPES.TRACES && (
- <DaemonSetTraces
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeTracesFilters={handleChangeTracesFilters}
- tracesFilters={logAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKey="daemonsetTraces"
- category={InfraMonitoringEvents.DaemonSet}
- queryKeyFilters={[
- QUERY_KEYS.K8S_DAEMON_SET_NAME,
- QUERY_KEYS.K8S_NAMESPACE_NAME,
- ]}
- />
- )}
- {selectedView === VIEW_TYPES.EVENTS && (
- <DaemonSetEvents
- timeRange={modalTimeRange}
- handleChangeEventFilters={handleChangeEventsFilters}
- filters={eventsFilters}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- queryKey="daemonsetEvents"
- category={K8sCategory.DAEMONSETS}
- />
- )}
- </>
- )}
- </Drawer>
- );
-}
-
-export default DaemonSetDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/index.ts b/frontend/src/container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/index.ts
deleted file mode 100644
index 462ee23be4..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import DaemonSetDetails from './DaemonSetDetails';
-
-export default DaemonSetDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/DaemonSets/K8sDaemonSetsList.styles.scss b/frontend/src/container/InfraMonitoringK8s/DaemonSets/K8sDaemonSetsList.styles.scss
deleted file mode 100644
index 7c3d056dce..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/DaemonSets/K8sDaemonSetsList.styles.scss
+++ /dev/null
@@ -1,62 +0,0 @@
-.infra-monitoring-container {
- .daemonSets-list-table {
- .expanded-table-container {
- padding-left: 20px;
- }
-
- .ant-table-cell.column-progress-bar {
- min-width: 180px;
- max-width: 180px;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
-
- .progress-container {
- display: flex;
- justify-content: start;
- }
- }
-}
-
-.ant-table-cell {
- &:has(.daemonset-name-header) {
- min-width: 250px !important;
- max-width: 250px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.namespace-name-header) {
- min-width: 220px !important;
- max-width: 220px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.med-col) {
- min-width: 200px !important;
- max-width: 200px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.small-col) {
- min-width: 120px !important;
- max-width: 120px !important;
- }
-}
-
-.expanded-daemonsets-list-table {
- .ant-table-cell {
- min-width: 220px !important;
- max-width: 220px !important;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
-}
diff --git a/frontend/src/container/InfraMonitoringK8s/DaemonSets/K8sDaemonSetsList.tsx b/frontend/src/container/InfraMonitoringK8s/DaemonSets/K8sDaemonSetsList.tsx
index 0a633948ce..e9392ae444 100644
--- a/frontend/src/container/InfraMonitoringK8s/DaemonSets/K8sDaemonSetsList.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/DaemonSets/K8sDaemonSetsList.tsx
@@ -1,717 +1,118 @@
-import React, { useCallback, useEffect, useMemo, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { LoadingOutlined } from '@ant-design/icons';
-import {
- Button,
- Spin,
- Table,
- TableColumnType as ColumnType,
- TablePaginationConfig,
- TableProps,
- Typography,
-} from 'antd';
-import type { SorterResult } from 'antd/es/table/interface';
-import logEvent from 'api/common/logEvent';
-import { K8sDaemonSetsListPayload } from 'api/infraMonitoring/getK8sDaemonSetsList';
-import classNames from 'classnames';
+import React, { useCallback } from 'react';
import { InfraMonitoringEvents } from 'constants/events';
-import { useGetK8sDaemonSetsList } from 'hooks/infraMonitoring/useGetK8sDaemonSetsList';
-import { useGetAggregateKeys } from 'hooks/queryBuilder/useGetAggregateKeys';
-import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
-import { ChevronDown, ChevronRight } from 'lucide-react';
-import { AppState } from 'store/reducers';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { buildAbsolutePath, isModifierKeyPressed } from 'utils/app';
-import { openInNewTab } from 'utils/navigation';
-
-import emptyStateUrl from '@/assets/Icons/emptyState.svg';
-
-import { FeatureKeys } from '../../../constants/features';
-import { useAppContext } from '../../../providers/App/App';
+import { FeatureKeys } from 'constants/features';
+import { useAppContext } from 'providers/App/App';
+
+import K8sBaseDetails, { K8sDetailsFilters } from '../Base/K8sBaseDetails';
+import { K8sBaseList } from '../Base/K8sBaseList';
+import { K8sBaseFilters } from '../Base/types';
+import { InfraMonitoringEntity } from '../constants';
+import { getK8sDaemonSetsList, K8sDaemonSetsData } from './api';
import {
- GetK8sEntityToAggregateAttribute,
- INFRA_MONITORING_K8S_PARAMS_KEYS,
- K8sCategory,
-} from '../constants';
+ daemonSetWidgetInfo,
+ getDaemonSetMetricsQueryPayload,
+ k8sDaemonSetDetailsMetadataConfig,
+ k8sDaemonSetGetEntityName,
+ k8sDaemonSetGetSelectedItemFilters,
+ k8sDaemonSetInitialEventsFilter,
+ k8sDaemonSetInitialFilters,
+ k8sDaemonSetInitialLogTracesFilter,
+} from './constants';
import {
- useInfraMonitoringCurrentPage,
- useInfraMonitoringDaemonSetUID,
- useInfraMonitoringEventsFilters,
- useInfraMonitoringGroupBy,
- useInfraMonitoringLogFilters,
- useInfraMonitoringOrderBy,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from '../hooks';
-import K8sHeader from '../K8sHeader';
-import LoadingContainer from '../LoadingContainer';
-import { usePageSize } from '../utils';
-import DaemonSetDetails from './DaemonSetDetails';
-import {
- defaultAddedColumns,
- formatDataForTable,
- getK8sDaemonSetsListColumns,
- getK8sDaemonSetsListQuery,
- K8sDaemonSetsRowData,
-} from './utils';
-
-import '../InfraMonitoringK8s.styles.scss';
-import './K8sDaemonSetsList.styles.scss';
+ k8sDaemonSetsColumns,
+ k8sDaemonSetsColumnsConfig,
+ k8sDaemonSetsRenderRowData,
+} from './table.config';
function K8sDaemonSetsList({
- isFiltersVisible,
- handleFilterVisibilityChange,
- quickFiltersLastUpdated,
+ controlListPrefix,
}: {
- isFiltersVisible: boolean;
- handleFilterVisibilityChange: () => void;
- quickFiltersLastUpdated: number;
+ controlListPrefix?: React.ReactNode;
}): JSX.Element {
- const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
- (state) => state.globalTime,
- );
-
- const [currentPage, setCurrentPage] = useInfraMonitoringCurrentPage();
- const [filtersInitialised, setFiltersInitialised] = useState(false);
- const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
-
- const [orderBy, setOrderBy] = useInfraMonitoringOrderBy();
-
- const [
- selectedDaemonSetUID,
- setSelectedDaemonSetUID,
- ] = useInfraMonitoringDaemonSetUID();
-
- const { pageSize, setPageSize } = usePageSize(K8sCategory.DAEMONSETS);
-
- const [groupBy, setGroupBy] = useInfraMonitoringGroupBy();
-
- const [, setView] = useInfraMonitoringView();
- const [, setTracesFilters] = useInfraMonitoringTracesFilters();
- const [, setEventsFilters] = useInfraMonitoringEventsFilters();
- const [, setLogFilters] = useInfraMonitoringLogFilters();
-
- const [
- selectedRowData,
- setSelectedRowData,
- ] = useState<K8sDaemonSetsRowData | null>(null);
-
- const [groupByOptions, setGroupByOptions] = useState<
- { value: string; label: string }[]
- >([]);
-
- const { currentQuery } = useQueryBuilder();
-
- const queryFilters = useMemo(
- () =>
- currentQuery?.builder?.queryData[0]?.filters || {
- items: [],
- op: 'and',
- },
- [currentQuery?.builder?.queryData],
- );
-
- // Reset pagination every time quick filters are changed
- useEffect(() => {
- if (quickFiltersLastUpdated !== -1) {
- setCurrentPage(1);
- }
- }, [quickFiltersLastUpdated, setCurrentPage]);
-
const { featureFlags } = useAppContext();
const dotMetricsEnabled =
featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
?.active || false;
- const createFiltersForSelectedRowData = (
- selectedRowData: K8sDaemonSetsRowData,
- groupBy: IBuilderQuery['groupBy'],
- ): IBuilderQuery['filters'] => {
- const baseFilters: IBuilderQuery['filters'] = {
- items: [...queryFilters.items],
- op: 'and',
- };
-
- if (!selectedRowData) {
- return baseFilters;
- }
-
- const { groupedByMeta } = selectedRowData;
-
- for (const key of groupBy) {
- baseFilters.items.push({
- key: {
- key: key.key,
- type: null,
- },
- op: '=',
- value: groupedByMeta[key.key],
- id: key.key,
- });
- }
-
- return baseFilters;
- };
-
- const fetchGroupedByRowDataQuery = useMemo(() => {
- if (!selectedRowData) {
- return null;
- }
-
- const baseQuery = getK8sDaemonSetsListQuery();
-
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- return {
- ...baseQuery,
- limit: 10,
- offset: 0,
- filters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [minTime, maxTime, orderBy, selectedRowData, groupBy]);
-
- const groupedByRowDataQueryKey = useMemo(() => {
- // be careful with what you serialize from selectedRowData
- // since it's react node, it could contain circular references
- const selectedRowDataKey = JSON.stringify(selectedRowData?.groupedByMeta);
- if (selectedDaemonSetUID) {
- return [
- 'daemonSetList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- ];
- }
- return [
- 'daemonSetList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- String(minTime),
- String(maxTime),
- ];
- }, [
- queryFilters,
- orderBy,
- selectedDaemonSetUID,
- minTime,
- maxTime,
- selectedRowData,
- ]);
-
- const {
- data: groupedByRowData,
- isFetching: isFetchingGroupedByRowData,
- isLoading: isLoadingGroupedByRowData,
- isError: isErrorGroupedByRowData,
- refetch: fetchGroupedByRowData,
- } = useGetK8sDaemonSetsList(
- fetchGroupedByRowDataQuery as K8sDaemonSetsListPayload,
- {
- queryKey: groupedByRowDataQueryKey,
- enabled: !!fetchGroupedByRowDataQuery && !!selectedRowData,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const {
- data: groupByFiltersData,
- isLoading: isLoadingGroupByFilters,
- } = useGetAggregateKeys(
- {
- dataSource: currentQuery.builder.queryData[0].dataSource,
- aggregateAttribute: GetK8sEntityToAggregateAttribute(
- K8sCategory.DAEMONSETS,
+ const fetchListData = useCallback(
+ async (filters: K8sBaseFilters, signal?: AbortSignal) => {
+ filters.orderBy ||= {
+ columnName: 'cpu',
+ order: 'desc',
+ };
+
+ const response = await getK8sDaemonSetsList(
+ filters,
+ signal,
+ undefined,
dotMetricsEnabled,
- ),
- aggregateOperator: 'noop',
- searchText: '',
- tagType: '',
- },
- {
- queryKey: [currentQuery.builder.queryData[0].dataSource, 'noop'],
- },
- true,
- K8sCategory.DAEMONSETS,
- );
-
- const query = useMemo(() => {
- const baseQuery = getK8sDaemonSetsListQuery();
- const queryPayload = {
- ...baseQuery,
- limit: pageSize,
- offset: (currentPage - 1) * pageSize,
- filters: queryFilters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- if (groupBy.length > 0) {
- queryPayload.groupBy = groupBy;
- }
- return queryPayload;
- }, [pageSize, currentPage, queryFilters, minTime, maxTime, orderBy, groupBy]);
-
- const formattedGroupedByDaemonSetsData = useMemo(
- () =>
- formatDataForTable(groupedByRowData?.payload?.data?.records || [], groupBy),
- [groupedByRowData, groupBy],
- );
-
- const queryKey = useMemo(() => {
- if (selectedDaemonSetUID) {
- return [
- 'daemonSetList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- ];
- }
- return [
- 'daemonSetList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- String(minTime),
- String(maxTime),
- ];
- }, [
- selectedDaemonSetUID,
- pageSize,
- currentPage,
- queryFilters,
- orderBy,
- groupBy,
- minTime,
- maxTime,
- ]);
-
- const { data, isFetching, isLoading, isError } = useGetK8sDaemonSetsList(
- query as K8sDaemonSetsListPayload,
- {
- queryKey,
- enabled: !!query,
- keepPreviousData: true,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const daemonSetsData = useMemo(() => data?.payload?.data?.records || [], [
- data,
- ]);
- const totalCount = data?.payload?.data?.total || 0;
-
- const formattedDaemonSetsData = useMemo(
- () => formatDataForTable(daemonSetsData, groupBy),
- [daemonSetsData, groupBy],
- );
-
- const nestedDaemonSetsData = useMemo(() => {
- if (!selectedRowData || !groupedByRowData?.payload?.data.records) {
- return [];
- }
- return groupedByRowData?.payload?.data?.records || [];
- }, [groupedByRowData, selectedRowData]);
-
- const columns = useMemo(() => getK8sDaemonSetsListColumns(groupBy), [groupBy]);
-
- const handleGroupByRowClick = (record: K8sDaemonSetsRowData): void => {
- setSelectedRowData(record);
-
- if (expandedRowKeys.includes(record.key)) {
- setExpandedRowKeys(expandedRowKeys.filter((key) => key !== record.key));
- } else {
- setExpandedRowKeys([record.key]);
- }
- };
-
- useEffect(() => {
- if (selectedRowData) {
- fetchGroupedByRowData();
- }
- }, [selectedRowData, fetchGroupedByRowData]);
-
- const handleTableChange: TableProps<K8sDaemonSetsRowData>['onChange'] = useCallback(
- (
- pagination: TablePaginationConfig,
- _filters: Record<string, (string | number | boolean)[] | null>,
- sorter:
- | SorterResult<K8sDaemonSetsRowData>
- | SorterResult<K8sDaemonSetsRowData>[],
- ): void => {
- if (pagination.current) {
- setCurrentPage(pagination.current);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.DaemonSet,
- });
- }
-
- if ('field' in sorter && sorter.order) {
- setOrderBy({
- columnName: sorter.field as string,
- order: (sorter.order === 'ascend' ? 'asc' : 'desc') as 'asc' | 'desc',
- });
- } else {
- setOrderBy(null);
- }
- },
- [setCurrentPage, setOrderBy],
- );
-
- const { handleChangeQueryData } = useQueryOperations({
- index: 0,
- query: currentQuery.builder.queryData[0],
- entityVersion: '',
- });
-
- const handleFiltersChange = useCallback(
- (value: IBuilderQuery['filters']): void => {
- handleChangeQueryData('filters', value);
- if (filtersInitialised) {
- setCurrentPage(1);
- } else {
- setFiltersInitialised(true);
- }
+ );
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.DaemonSet,
- });
- }
+ return {
+ data: response.payload?.data.records || [],
+ total: response.payload?.data.total || 0,
+ error: response.error,
+ rawData: response.payload?.data,
+ };
},
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.DaemonSet,
- total: data?.payload?.data?.total,
- });
- }, [data?.payload?.data?.total]);
-
- const selectedDaemonSetData = useMemo(() => {
- if (groupBy.length > 0) {
- // If grouped by, return the daemonset from the formatted grouped by data
- return (
- nestedDaemonSetsData.find(
- (daemonSet) => daemonSet.daemonSetName === selectedDaemonSetUID,
- ) || null
+ const fetchEntityData = useCallback(
+ async (
+ filters: K8sDetailsFilters,
+ signal?: AbortSignal,
+ ): Promise<{ data: K8sDaemonSetsData | null; error?: string | null }> => {
+ const response = await getK8sDaemonSetsList(
+ {
+ filters: filters.filters,
+ start: filters.start,
+ end: filters.end,
+ limit: 1,
+ offset: 0,
+ },
+ signal,
+ undefined,
+ dotMetricsEnabled,
);
- }
- // If not grouped by, return the daemonset from the daemonsets data
- return (
- daemonSetsData.find(
- (daemonSet) => daemonSet.daemonSetName === selectedDaemonSetUID,
- ) || null
- );
- }, [
- selectedDaemonSetUID,
- groupBy.length,
- daemonSetsData,
- nestedDaemonSetsData,
- ]);
-
- const openDaemonSetInNewTab = (record: K8sDaemonSetsRowData): void => {
- const newParams = new URLSearchParams(document.location.search);
- newParams.set(
- INFRA_MONITORING_K8S_PARAMS_KEYS.DAEMONSET_UID,
- record.daemonsetUID,
- );
- openInNewTab(
- buildAbsolutePath({
- relativePath: '',
- urlQueryString: newParams.toString(),
- }),
- );
- };
-
- const handleRowClick = (
- record: K8sDaemonSetsRowData,
- event?: React.MouseEvent,
- ): void => {
- if (event && isModifierKeyPressed(event)) {
- openDaemonSetInNewTab(record);
- return;
- }
- if (groupBy.length === 0) {
- setSelectedRowData(null);
- setSelectedDaemonSetUID(record.daemonsetUID);
- } else {
- handleGroupByRowClick(record);
- }
-
- logEvent(InfraMonitoringEvents.ItemClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.DaemonSet,
- });
- };
-
- const nestedColumns = useMemo(() => getK8sDaemonSetsListColumns([]), []);
-
- const isGroupedByAttribute = groupBy.length > 0;
- const handleExpandedRowViewAllClick = (): void => {
- if (!selectedRowData) {
- return;
- }
+ const records = response.payload?.data.records || [];
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- handleFiltersChange(filters);
-
- setCurrentPage(1);
- setSelectedRowData(null);
- setGroupBy([]);
- setOrderBy(null);
- };
-
- const expandedRowRender = (): JSX.Element => (
- <div className="expanded-table-container">
- {isErrorGroupedByRowData && (
- <Typography>{groupedByRowData?.error || 'Something went wrong'}</Typography>
- )}
- {isFetchingGroupedByRowData || isLoadingGroupedByRowData ? (
- <LoadingContainer />
- ) : (
- <div className="expanded-table">
- <Table
- columns={nestedColumns as ColumnType<K8sDaemonSetsRowData>[]}
- dataSource={formattedGroupedByDaemonSetsData}
- pagination={false}
- scroll={{ x: true }}
- tableLayout="fixed"
- size="small"
- loading={{
- spinning: isFetchingGroupedByRowData || isLoadingGroupedByRowData,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- showHeader={false}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => {
- if (event && isModifierKeyPressed(event)) {
- openDaemonSetInNewTab(record);
- return;
- }
- setSelectedDaemonSetUID(record.daemonsetUID);
- },
- className: 'expanded-clickable-row',
- })}
- />
-
- {groupedByRowData?.payload?.data?.total &&
- groupedByRowData?.payload?.data?.total > 10 ? (
- <div className="expanded-table-footer">
- <Button
- type="default"
- size="small"
- className="periscope-btn secondary"
- onClick={handleExpandedRowViewAllClick}
- >
- View All
- </Button>
- </div>
- ) : null}
- </div>
- )}
- </div>
- );
-
- const expandRowIconRenderer = ({
- expanded,
- onExpand,
- record,
- }: {
- expanded: boolean;
- onExpand: (
- record: K8sDaemonSetsRowData,
- e: React.MouseEvent<HTMLButtonElement>,
- ) => void;
- record: K8sDaemonSetsRowData;
- }): JSX.Element | null => {
- if (!isGroupedByAttribute) {
- return null;
- }
-
- return expanded ? (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronDown size={14} />
- </Button>
- ) : (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronRight size={14} />
- </Button>
- );
- };
-
- const handleCloseDaemonSetDetail = (): void => {
- setSelectedDaemonSetUID(null);
- setView(null);
- setTracesFilters(null);
- setEventsFilters(null);
- setLogFilters(null);
- };
-
- const handleGroupByChange = useCallback(
- (value: IBuilderQuery['groupBy']) => {
- const groupBy = [];
-
- for (let index = 0; index < value.length; index++) {
- const element = (value[index] as unknown) as string;
-
- const key = groupByFiltersData?.payload?.attributeKeys?.find(
- (key) => key.key === element,
- );
-
- if (key) {
- groupBy.push(key);
- }
- }
-
- setCurrentPage(1);
- setGroupBy(groupBy);
- setExpandedRowKeys([]);
-
- logEvent(InfraMonitoringEvents.GroupByChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.DaemonSet,
- });
+ return {
+ data: records.length > 0 ? records[0] : null,
+ error: response.error,
+ };
},
- [groupByFiltersData, setCurrentPage, setGroupBy],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- if (groupByFiltersData?.payload) {
- setGroupByOptions(
- groupByFiltersData?.payload?.attributeKeys?.map((filter) => ({
- value: filter.key,
- label: filter.key,
- })) || [],
- );
- }
- }, [groupByFiltersData]);
-
- const onPaginationChange = (page: number, pageSize: number): void => {
- setCurrentPage(page);
- setPageSize(pageSize);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.DaemonSet,
- });
- };
-
- const showTableLoadingState =
- (isFetching || isLoading) && formattedDaemonSetsData.length === 0;
-
return (
- <div className="k8s-list">
- <K8sHeader
- isFiltersVisible={isFiltersVisible}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- defaultAddedColumns={defaultAddedColumns}
- handleFiltersChange={handleFiltersChange}
- groupByOptions={groupByOptions}
- isLoadingGroupByFilters={isLoadingGroupByFilters}
- handleGroupByChange={handleGroupByChange}
- selectedGroupBy={groupBy}
- entity={K8sCategory.DAEMONSETS}
- showAutoRefresh={!selectedDaemonSetData}
- />
- {isError && <Typography>{data?.error || 'Something went wrong'}</Typography>}
-
- <Table
- className={classNames('k8s-list-table', 'daemonSets-list-table', {
- 'expanded-daemonsets-list-table': isGroupedByAttribute,
- })}
- dataSource={showTableLoadingState ? [] : formattedDaemonSetsData}
- columns={columns}
- pagination={{
- current: currentPage,
- pageSize,
- total: totalCount,
- showSizeChanger: true,
- hideOnSinglePage: false,
- onChange: onPaginationChange,
- }}
- scroll={{ x: true }}
- loading={{
- spinning: showTableLoadingState,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- locale={{
- emptyText: showTableLoadingState ? null : (
- <div className="no-filtered-hosts-message-container">
- <div className="no-filtered-hosts-message-content">
- <img
- src={emptyStateUrl}
- alt="thinking-emoji"
- className="empty-state-svg"
- />
-
- <Typography.Text className="no-filtered-hosts-message">
- This query had no results. Edit your query and try again!
- </Typography.Text>
- </div>
- </div>
- ),
- }}
- tableLayout="fixed"
- onChange={handleTableChange}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => handleRowClick(record, event),
- className: 'clickable-row',
- })}
- expandable={{
- expandedRowRender: isGroupedByAttribute ? expandedRowRender : undefined,
- expandIcon: expandRowIconRenderer,
- expandedRowKeys,
- }}
+ <>
+ <K8sBaseList<K8sDaemonSetsData>
+ controlListPrefix={controlListPrefix}
+ entity={InfraMonitoringEntity.DAEMONSETS}
+ tableColumnsDefinitions={k8sDaemonSetsColumns}
+ tableColumns={k8sDaemonSetsColumnsConfig}
+ fetchListData={fetchListData}
+ renderRowData={k8sDaemonSetsRenderRowData}
+ eventCategory={InfraMonitoringEvents.DaemonSet}
/>
- <DaemonSetDetails
- daemonSet={selectedDaemonSetData}
- isModalTimeSelection
- onClose={handleCloseDaemonSetDetail}
+ <K8sBaseDetails<K8sDaemonSetsData>
+ category={InfraMonitoringEntity.DAEMONSETS}
+ eventCategory={InfraMonitoringEvents.DaemonSet}
+ getSelectedItemFilters={k8sDaemonSetGetSelectedItemFilters}
+ fetchEntityData={fetchEntityData}
+ getEntityName={k8sDaemonSetGetEntityName}
+ getInitialLogTracesFilters={k8sDaemonSetInitialLogTracesFilter}
+ getInitialEventsFilters={k8sDaemonSetInitialEventsFilter}
+ primaryFilterKeys={k8sDaemonSetInitialFilters}
+ metadataConfig={k8sDaemonSetDetailsMetadataConfig}
+ entityWidgetInfo={daemonSetWidgetInfo}
+ getEntityQueryPayload={getDaemonSetMetricsQueryPayload}
+ queryKeyPrefix="daemonset"
/>
- </div>
+ </>
);
}
diff --git a/frontend/src/api/infraMonitoring/getK8sDaemonSetsList.ts b/frontend/src/container/InfraMonitoringK8s/DaemonSets/api.ts
similarity index 61%
rename from frontend/src/api/infraMonitoring/getK8sDaemonSetsList.ts
rename to frontend/src/container/InfraMonitoringK8s/DaemonSets/api.ts
index 75ea41f64d..e8f72ab6e4 100644
--- a/frontend/src/api/infraMonitoring/getK8sDaemonSetsList.ts
+++ b/frontend/src/container/InfraMonitoringK8s/DaemonSets/api.ts
@@ -1,22 +1,10 @@
import axios from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
+import { UnderscoreToDotMap } from 'api/utils';
import { AxiosError } from 'axios';
import { ErrorResponse, SuccessResponse } from 'types/api';
-import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
-import { UnderscoreToDotMap } from '../utils';
-
-export interface K8sDaemonSetsListPayload {
- filters: TagFilter;
- groupBy?: BaseAutocompleteData[];
- offset?: number;
- limit?: number;
- orderBy?: {
- columnName: string;
- order: 'asc' | 'desc';
- };
-}
+import { K8sBaseFilters } from '../Base/types';
export interface K8sDaemonSetsData {
daemonSetName: string;
@@ -48,6 +36,7 @@ export interface K8sDaemonSetsListResponse {
};
}
+// TODO(H4ad): Erase this whole file when migrating to openapi
export const daemonSetsMetaMap = [
{ dot: 'k8s.namespace.name', under: 'k8s_namespace_name' },
{ dot: 'k8s.daemonset.name', under: 'k8s_daemonset_name' },
@@ -68,45 +57,43 @@ export function mapDaemonSetsMeta(
}
export const getK8sDaemonSetsList = async (
- props: K8sDaemonSetsListPayload,
+ props: K8sBaseFilters,
signal?: AbortSignal,
headers?: Record<string, string>,
dotMetricsEnabled = false,
): Promise<SuccessResponse<K8sDaemonSetsListResponse> | ErrorResponse> => {
try {
- // filter prep (unchanged)…
- const requestProps =
- dotMetricsEnabled && Array.isArray(props.filters?.items)
- ? {
- ...props,
- filters: {
- ...props.filters,
- items: props.filters.items.reduce<typeof props.filters.items>(
- (acc, item) => {
- if (item.value === undefined) {
- return acc;
- }
- if (
- item.key &&
- typeof item.key === 'object' &&
- 'key' in item.key &&
- typeof item.key.key === 'string'
- ) {
- const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
- acc.push({
- ...item,
- key: { ...item.key, key: mappedKey },
- });
- } else {
- acc.push(item);
- }
+ const requestProps = dotMetricsEnabled
+ ? {
+ ...props,
+ filters: {
+ ...props.filters,
+ items: props.filters.items.reduce<typeof props.filters.items>(
+ (acc, item) => {
+ if (item.value === undefined) {
return acc;
- },
- [] as typeof props.filters.items,
- ),
- },
- }
- : props;
+ }
+ if (
+ item.key &&
+ typeof item.key === 'object' &&
+ 'key' in item.key &&
+ typeof item.key.key === 'string'
+ ) {
+ const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
+ acc.push({
+ ...item,
+ key: { ...item.key, key: mappedKey },
+ });
+ } else {
+ acc.push(item);
+ }
+ return acc;
+ },
+ [] as typeof props.filters.items,
+ ),
+ },
+ }
+ : props;
const response = await axios.post('/daemonsets/list', requestProps, {
signal,
@@ -114,7 +101,6 @@ export const getK8sDaemonSetsList = async (
});
const payload: K8sDaemonSetsListResponse = response.data;
- // single-line meta mapping
payload.data.records = payload.data.records.map((record) => ({
...record,
meta: mapDaemonSetsMeta(record.meta as Record<string, unknown>),
diff --git a/frontend/src/container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/constants.ts b/frontend/src/container/InfraMonitoringK8s/DaemonSets/constants.ts
similarity index 90%
rename from frontend/src/container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/constants.ts
rename to frontend/src/container/InfraMonitoringK8s/DaemonSets/constants.ts
index ae45f84f19..42666a7063 100644
--- a/frontend/src/container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/constants.ts
+++ b/frontend/src/container/InfraMonitoringK8s/DaemonSets/constants.ts
@@ -1,11 +1,72 @@
-import { K8sDaemonSetsData } from 'api/infraMonitoring/getK8sDaemonSetsList';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { v4 } from 'uuid';
+import {
+ createFilterItem,
+ K8sDetailsMetadataConfig,
+} from '../Base/K8sBaseDetails';
+import { QUERY_KEYS } from '../EntityDetailsUtils/utils';
+import { K8sDaemonSetsData } from './api';
+
+export const k8sDaemonSetGetSelectedItemFilters = (
+ selectedItemId: string,
+): TagFilter => ({
+ op: 'AND',
+ items: [
+ {
+ id: 'k8s_daemonset_name',
+ key: {
+ key: 'k8s_daemonset_name',
+ type: null,
+ },
+ op: '=',
+ value: selectedItemId,
+ },
+ ],
+});
+
+export const k8sDaemonSetDetailsMetadataConfig: K8sDetailsMetadataConfig<K8sDaemonSetsData>[] = [
+ {
+ label: 'Daemonset Name',
+ getValue: (p): string => p.meta.k8s_daemonset_name,
+ },
+ {
+ label: 'Cluster Name',
+ getValue: (p): string => p.meta.k8s_cluster_name,
+ },
+ {
+ label: 'Namespace Name',
+ getValue: (p): string => p.meta.k8s_namespace_name,
+ },
+];
+
+export const k8sDaemonSetInitialFilters = [
+ QUERY_KEYS.K8S_DAEMON_SET_NAME,
+ QUERY_KEYS.K8S_NAMESPACE_NAME,
+];
+
+export const k8sDaemonSetInitialEventsFilter = (
+ item: K8sDaemonSetsData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_KIND, 'DaemonSet'),
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_NAME, item.meta.k8s_daemonset_name),
+];
+
+export const k8sDaemonSetInitialLogTracesFilter = (
+ item: K8sDaemonSetsData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(QUERY_KEYS.K8S_DAEMON_SET_NAME, item.meta.k8s_daemonset_name),
+ createFilterItem(QUERY_KEYS.K8S_NAMESPACE_NAME, item.meta.k8s_namespace_name),
+];
+
+export const k8sDaemonSetGetEntityName = (item: K8sDaemonSetsData): string =>
+ item.meta.k8s_daemonset_name;
+
export const daemonSetWidgetInfo = [
{
title: 'CPU usage, request, limits',
diff --git a/frontend/src/container/InfraMonitoringK8s/DaemonSets/table.config.tsx b/frontend/src/container/InfraMonitoringK8s/DaemonSets/table.config.tsx
new file mode 100644
index 0000000000..78c13921e2
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/DaemonSets/table.config.tsx
@@ -0,0 +1,297 @@
+import { TableColumnType as ColumnType, Tooltip } from 'antd';
+import { Group } from 'lucide-react';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+
+import { K8sRenderedRowData } from '../Base/types';
+import { IEntityColumn } from '../Base/useInfraMonitoringTableColumnsStore';
+import { getGroupByEl, getGroupedByMeta, getRowKey } from '../Base/utils';
+import {
+ EntityProgressBar,
+ formatBytes,
+ ValidateColumnValueWrapper,
+} from '../commonUtils';
+import { InfraMonitoringEntity } from '../constants';
+import { K8sDaemonSetsData } from './api';
+
+import styles from './table.module.scss';
+
+export const k8sDaemonSetsColumns: IEntityColumn[] = [
+ {
+ label: 'DaemonSet Group',
+ value: 'daemonSetGroup',
+ id: 'daemonSetGroup',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-collapse',
+ },
+ {
+ label: 'DaemonSet Name',
+ value: 'daemonsetName',
+ id: 'daemonsetName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-expand',
+ },
+ {
+ label: 'Namespace Name',
+ value: 'namespaceName',
+ id: 'namespaceName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Available',
+ value: 'available_nodes',
+ id: 'available_nodes',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Desired',
+ value: 'desired_nodes',
+ id: 'desired_nodes',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Req Usage (%)',
+ value: 'cpu_request',
+ id: 'cpu_request',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Limit Usage (%)',
+ value: 'cpu_limit',
+ id: 'cpu_limit',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Usage (cores)',
+ value: 'cpu',
+ id: 'cpu',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Req Usage (%)',
+ value: 'memory_request',
+ id: 'memory_request',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Limit Usage (%)',
+ value: 'memory_limit',
+ id: 'memory_limit',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Usage (WSS)',
+ value: 'memory',
+ id: 'memory',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+];
+
+export const k8sDaemonSetsColumnsConfig: ColumnType<K8sRenderedRowData>[] = [
+ {
+ title: (
+ <div className={styles.entityGroupHeader}>
+ <Group size={14} /> DAEMONSET GROUP
+ </div>
+ ),
+ dataIndex: 'daemonSetGroup',
+ key: 'daemonSetGroup',
+ ellipsis: true,
+ width: 150,
+ align: 'left',
+ sorter: false,
+ },
+ {
+ title: <div>DaemonSet Name</div>,
+ dataIndex: 'daemonsetName',
+ key: 'daemonsetName',
+ ellipsis: true,
+ width: 150,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>Namespace Name</div>,
+ dataIndex: 'namespaceName',
+ key: 'namespaceName',
+ ellipsis: true,
+ width: 80,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>Available</div>,
+ dataIndex: 'available_nodes',
+ key: 'available_nodes',
+ width: 50,
+ ellipsis: true,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Desired</div>,
+ dataIndex: 'desired_nodes',
+ key: 'desired_nodes',
+ width: 50,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Req Usage (%)</div>,
+ dataIndex: 'cpu_request',
+ key: 'cpu_request',
+ width: 180,
+ ellipsis: true,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Limit Usage (%)</div>,
+ dataIndex: 'cpu_limit',
+ key: 'cpu_limit',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Usage (cores)</div>,
+ dataIndex: 'cpu',
+ key: 'cpu',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Req Usage (%)</div>,
+ dataIndex: 'memory_request',
+ key: 'memory_request',
+ width: 170,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Limit Usage (%)</div>,
+ dataIndex: 'memory_limit',
+ key: 'memory_limit',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Usage (WSS)</div>,
+ dataIndex: 'memory',
+ key: 'memory',
+ width: 120,
+ ellipsis: true,
+ sorter: true,
+ align: 'left',
+ },
+];
+
+export const k8sDaemonSetsRenderRowData = (
+ entity: K8sDaemonSetsData,
+ groupBy: BaseAutocompleteData[],
+): K8sRenderedRowData => ({
+ key: getRowKey(
+ entity,
+ () => entity.daemonSetName || entity.meta.k8s_daemonset_name || '',
+ groupBy,
+ ),
+ itemKey: entity.meta.k8s_daemonset_name,
+ daemonsetName: (
+ <Tooltip title={entity.meta.k8s_daemonset_name}>
+ {entity.meta.k8s_daemonset_name || ''}
+ </Tooltip>
+ ),
+ namespaceName: (
+ <Tooltip title={entity.meta.k8s_namespace_name}>
+ {entity.meta.k8s_namespace_name || ''}
+ </Tooltip>
+ ),
+ cpu_request: (
+ <ValidateColumnValueWrapper
+ value={entity.cpuRequest}
+ entity={InfraMonitoringEntity.DAEMONSETS}
+ attribute="CPU Request"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={entity.cpuRequest} type="request" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ cpu_limit: (
+ <ValidateColumnValueWrapper
+ value={entity.cpuLimit}
+ entity={InfraMonitoringEntity.DAEMONSETS}
+ attribute="CPU Limit"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={entity.cpuLimit} type="limit" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ cpu: (
+ <ValidateColumnValueWrapper value={entity.cpuUsage}>
+ {entity.cpuUsage}
+ </ValidateColumnValueWrapper>
+ ),
+ memory_request: (
+ <ValidateColumnValueWrapper
+ value={entity.memoryRequest}
+ entity={InfraMonitoringEntity.DAEMONSETS}
+ attribute="Memory Request"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={entity.memoryRequest} type="request" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ memory_limit: (
+ <ValidateColumnValueWrapper
+ value={entity.memoryLimit}
+ entity={InfraMonitoringEntity.DAEMONSETS}
+ attribute="Memory Limit"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={entity.memoryLimit} type="limit" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ memory: (
+ <ValidateColumnValueWrapper value={entity.memoryUsage}>
+ {formatBytes(entity.memoryUsage)}
+ </ValidateColumnValueWrapper>
+ ),
+ available_nodes: (
+ <ValidateColumnValueWrapper value={entity.availableNodes}>
+ {entity.availableNodes}
+ </ValidateColumnValueWrapper>
+ ),
+ desired_nodes: (
+ <ValidateColumnValueWrapper value={entity.desiredNodes}>
+ {entity.desiredNodes}
+ </ValidateColumnValueWrapper>
+ ),
+ daemonSetGroup: getGroupByEl(entity, groupBy),
+ ...entity.meta,
+ groupedByMeta: getGroupedByMeta(entity, groupBy),
+});
diff --git a/frontend/src/container/InfraMonitoringK8s/DaemonSets/table.module.scss b/frontend/src/container/InfraMonitoringK8s/DaemonSets/table.module.scss
new file mode 100644
index 0000000000..bc11f496a1
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/DaemonSets/table.module.scss
@@ -0,0 +1,11 @@
+.entityGroupHeader {
+ padding-left: var(--spacing-5);
+ gap: var(--spacing-5);
+ display: flex;
+ align-items: center;
+}
+
+.progressBar {
+ display: flex;
+ justify-content: start;
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/DaemonSets/utils.tsx b/frontend/src/container/InfraMonitoringK8s/DaemonSets/utils.tsx
deleted file mode 100644
index 2a7e18d3e1..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/DaemonSets/utils.tsx
+++ /dev/null
@@ -1,356 +0,0 @@
-import { Color } from '@signozhq/design-tokens';
-import { TableColumnType as ColumnType, Tag, Tooltip } from 'antd';
-import {
- K8sDaemonSetsData,
- K8sDaemonSetsListPayload,
-} from 'api/infraMonitoring/getK8sDaemonSetsList';
-import { Group } from 'lucide-react';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-
-import {
- EntityProgressBar,
- formatBytes,
- ValidateColumnValueWrapper,
-} from '../commonUtils';
-import { K8sCategory } from '../constants';
-import { IEntityColumn } from '../utils';
-
-export const defaultAddedColumns: IEntityColumn[] = [
- {
- label: 'DaemonSet Name',
- value: 'daemonsetName',
- id: 'daemonsetName',
- canRemove: false,
- },
- {
- label: 'Namespace Name',
- value: 'namespaceName',
- id: 'namespaceName',
- canRemove: false,
- },
- {
- label: 'Available',
- value: 'available_nodes',
- id: 'available_nodes',
- canRemove: false,
- },
- {
- label: 'Desired',
- value: 'desired_nodes',
- id: 'desired_nodes',
- canRemove: false,
- },
- {
- label: 'CPU Req Usage (%)',
- value: 'cpu_request',
- id: 'cpu_request',
- canRemove: false,
- },
- {
- label: 'CPU Limit Usage (%)',
- value: 'cpu_limit',
- id: 'cpu_limit',
- canRemove: false,
- },
- {
- label: 'CPU Usage (cores)',
- value: 'cpu',
- id: 'cpu',
- canRemove: false,
- },
- {
- label: 'Mem Req Usage (%)',
- value: 'memory_request',
- id: 'memory_request',
- canRemove: false,
- },
- {
- label: 'Mem Limit Usage (%)',
- value: 'memory_limit',
- id: 'memory_limit',
- canRemove: false,
- },
- {
- label: 'Mem Usage (WSS)',
- value: 'memory',
- id: 'memory',
- canRemove: false,
- },
-];
-
-export interface K8sDaemonSetsRowData {
- key: string;
- daemonsetUID: string;
- daemonsetName: React.ReactNode;
- cpu_request: React.ReactNode;
- cpu_limit: React.ReactNode;
- cpu: React.ReactNode;
- memory_request: React.ReactNode;
- memory_limit: React.ReactNode;
- memory: React.ReactNode;
- desired_nodes: React.ReactNode;
- available_nodes: React.ReactNode;
- namespaceName: React.ReactNode;
- groupedByMeta?: any;
-}
-
-const daemonSetGroupColumnConfig = {
- title: (
- <div className="column-header entity-group-header">
- <Group size={14} /> DAEMONSET GROUP
- </div>
- ),
- dataIndex: 'daemonSetGroup',
- key: 'daemonSetGroup',
- ellipsis: true,
- width: 150,
- align: 'left',
- sorter: false,
- className: 'column entity-group-header',
-};
-
-export const getK8sDaemonSetsListQuery = (): K8sDaemonSetsListPayload => ({
- filters: {
- items: [],
- op: 'and',
- },
- orderBy: { columnName: 'cpu', order: 'desc' },
-});
-
-const columnProgressBarClassName = 'column-progress-bar';
-
-const columnsConfig = [
- {
- title: (
- <div className="column-header-left daemonset-name-header">
- DaemonSet Name
- </div>
- ),
- dataIndex: 'daemonsetName',
- key: 'daemonsetName',
- ellipsis: true,
- width: 80,
- sorter: false,
- align: 'left',
- },
- {
- title: (
- <div className="column-header-left namespace-name-header">
- Namespace Name
- </div>
- ),
- dataIndex: 'namespaceName',
- key: 'namespaceName',
- ellipsis: true,
- width: 80,
- sorter: false,
- align: 'left',
- },
- {
- title: <div className="column-header small-col">Available</div>,
- dataIndex: 'available_nodes',
- key: 'available_nodes',
- ellipsis: true,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header small-col">Desired</div>,
- dataIndex: 'desired_nodes',
- key: 'desired_nodes',
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">CPU Req Usage (%)</div>,
- dataIndex: 'cpu_request',
- key: 'cpu_request',
- width: 180,
- ellipsis: true,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">CPU Limit Usage (%)</div>,
- dataIndex: 'cpu_limit',
- key: 'cpu_limit',
- width: 120,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header small-col">CPU Usage (cores)</div>,
- dataIndex: 'cpu',
- key: 'cpu',
- width: 80,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">Mem Req Usage (%)</div>,
- dataIndex: 'memory_request',
- key: 'memory_request',
- width: 120,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">Mem Limit Usage (%)</div>,
- dataIndex: 'memory_limit',
- key: 'memory_limit',
- width: 120,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">Mem Usage (WSS)</div>,
- dataIndex: 'memory',
- key: 'memory',
- width: 120,
- ellipsis: true,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
-];
-
-export const getK8sDaemonSetsListColumns = (
- groupBy: IBuilderQuery['groupBy'],
-): ColumnType<K8sDaemonSetsRowData>[] => {
- if (groupBy.length > 0) {
- const filteredColumns = [...columnsConfig].filter(
- (column) => column.key !== 'daemonsetName',
- );
- filteredColumns.unshift(daemonSetGroupColumnConfig);
- return filteredColumns as ColumnType<K8sDaemonSetsRowData>[];
- }
-
- return columnsConfig as ColumnType<K8sDaemonSetsRowData>[];
-};
-
-const dotToUnder: Record<string, keyof K8sDaemonSetsData['meta']> = {
- 'k8s.daemonset.name': 'k8s_daemonset_name',
- 'k8s.namespace.name': 'k8s_namespace_name',
- 'k8s.cluster.name': 'k8s_cluster_name',
-};
-
-const getGroupByEle = (
- daemonSet: K8sDaemonSetsData,
- groupBy: IBuilderQuery['groupBy'],
-): React.ReactNode => {
- const groupByValues: string[] = [];
-
- groupBy.forEach((group) => {
- const rawKey = group.key as string;
-
- // Choose mapped key if present, otherwise use rawKey
- const metaKey = (dotToUnder[rawKey] ?? rawKey) as keyof typeof daemonSet.meta;
- const value = daemonSet.meta[metaKey];
-
- groupByValues.push(value);
- });
-
- return (
- <div className="pod-group">
- {groupByValues.map((value) => (
- <Tag key={value} color={Color.BG_SLATE_400} className="pod-group-tag-item">
- {value === '' ? '<no-value>' : value}
- </Tag>
- ))}
- </div>
- );
-};
-
-export const formatDataForTable = (
- data: K8sDaemonSetsData[],
- groupBy: IBuilderQuery['groupBy'],
-): K8sDaemonSetsRowData[] =>
- data.map((daemonSet, index) => ({
- key: index.toString(),
- daemonsetUID: daemonSet.daemonSetName,
- daemonsetName: (
- <Tooltip title={daemonSet.meta.k8s_daemonset_name}>
- {daemonSet.meta.k8s_daemonset_name || ''}
- </Tooltip>
- ),
- namespaceName: (
- <Tooltip title={daemonSet.meta.k8s_namespace_name}>
- {daemonSet.meta.k8s_namespace_name || ''}
- </Tooltip>
- ),
- cpu_request: (
- <ValidateColumnValueWrapper
- value={daemonSet.cpuRequest}
- entity={K8sCategory.DAEMONSETS}
- attribute="CPU Request"
- >
- <div className="progress-container">
- <EntityProgressBar value={daemonSet.cpuRequest} type="request" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- cpu_limit: (
- <ValidateColumnValueWrapper
- value={daemonSet.cpuLimit}
- entity={K8sCategory.DAEMONSETS}
- attribute="CPU Limit"
- >
- <div className="progress-container">
- <EntityProgressBar value={daemonSet.cpuLimit} type="limit" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- cpu: (
- <ValidateColumnValueWrapper value={daemonSet.cpuUsage}>
- {daemonSet.cpuUsage}
- </ValidateColumnValueWrapper>
- ),
- memory_request: (
- <ValidateColumnValueWrapper
- value={daemonSet.memoryRequest}
- entity={K8sCategory.DAEMONSETS}
- attribute="Memory Request"
- >
- <div className="progress-container">
- <EntityProgressBar value={daemonSet.memoryRequest} type="request" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- memory_limit: (
- <ValidateColumnValueWrapper
- value={daemonSet.memoryLimit}
- entity={K8sCategory.DAEMONSETS}
- attribute="Memory Limit"
- >
- <div className="progress-container">
- <EntityProgressBar value={daemonSet.memoryLimit} type="limit" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- memory: (
- <ValidateColumnValueWrapper value={daemonSet.memoryUsage}>
- {formatBytes(daemonSet.memoryUsage)}
- </ValidateColumnValueWrapper>
- ),
- available_nodes: (
- <ValidateColumnValueWrapper value={daemonSet.availableNodes}>
- {daemonSet.availableNodes}
- </ValidateColumnValueWrapper>
- ),
- desired_nodes: (
- <ValidateColumnValueWrapper value={daemonSet.desiredNodes}>
- {daemonSet.desiredNodes}
- </ValidateColumnValueWrapper>
- ),
- daemonSetGroup: getGroupByEle(daemonSet, groupBy),
- meta: daemonSet.meta,
- ...daemonSet.meta,
- groupedByMeta: daemonSet.meta,
- }));
diff --git a/frontend/src/container/InfraMonitoringK8s/Deployments/DeploymentDetails/DeploymentDetails.interfaces.ts b/frontend/src/container/InfraMonitoringK8s/Deployments/DeploymentDetails/DeploymentDetails.interfaces.ts
deleted file mode 100644
index eb547aa343..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Deployments/DeploymentDetails/DeploymentDetails.interfaces.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { K8sDeploymentsData } from 'api/infraMonitoring/getK8sDeploymentsList';
-
-export type DeploymentDetailsProps = {
- deployment: K8sDeploymentsData | null;
- isModalTimeSelection: boolean;
- onClose: () => void;
-};
diff --git a/frontend/src/container/InfraMonitoringK8s/Deployments/DeploymentDetails/DeploymentDetails.tsx b/frontend/src/container/InfraMonitoringK8s/Deployments/DeploymentDetails/DeploymentDetails.tsx
deleted file mode 100644
index c59200c0ec..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Deployments/DeploymentDetails/DeploymentDetails.tsx
+++ /dev/null
@@ -1,671 +0,0 @@
-/* eslint-disable sonarjs/no-identical-functions */
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { Color, Spacing } from '@signozhq/design-tokens';
-import { Button, Divider, Drawer, Radio, Tooltip, Typography } from 'antd';
-import type { RadioChangeEvent } from 'antd/lib';
-import logEvent from 'api/common/logEvent';
-import { K8sDeploymentsData } from 'api/infraMonitoring/getK8sDeploymentsList';
-import { VIEW_TYPES, VIEWS } from 'components/HostMetricsDetail/constants';
-import { InfraMonitoringEvents } from 'constants/events';
-import { QueryParams } from 'constants/query';
-import {
- initialQueryBuilderFormValuesMap,
- initialQueryState,
-} from 'constants/queryBuilder';
-import ROUTES from 'constants/routes';
-import { filterDuplicateFilters } from 'container/InfraMonitoringK8s/commonUtils';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
-import { QUERY_KEYS } from 'container/InfraMonitoringK8s/EntityDetailsUtils/utils';
-import {
- useInfraMonitoringEventsFilters,
- useInfraMonitoringLogFilters,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from 'container/InfraMonitoringK8s/hooks';
-import {
- CustomTimeType,
- Time,
-} from 'container/TopNav/DateTimeSelectionV2/types';
-import { useIsDarkMode } from 'hooks/useDarkMode';
-import useUrlQuery from 'hooks/useUrlQuery';
-import GetMinMax from 'lib/getMinMax';
-import {
- BarChart2,
- ChevronsLeftRight,
- Compass,
- DraftingCompass,
- ScrollText,
- X,
-} from 'lucide-react';
-import { AppState } from 'store/reducers';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import {
- IBuilderQuery,
- TagFilterItem,
-} from 'types/api/queryBuilder/queryBuilderData';
-import {
- LogsAggregatorOperator,
- TracesAggregatorOperator,
-} from 'types/common/queryBuilder';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { v4 as uuidv4 } from 'uuid';
-
-import DeploymentEvents from '../../EntityDetailsUtils/EntityEvents';
-import DeploymentLogs from '../../EntityDetailsUtils/EntityLogs';
-import DeploymentMetrics from '../../EntityDetailsUtils/EntityMetrics';
-import DeploymentTraces from '../../EntityDetailsUtils/EntityTraces';
-import {
- deploymentWidgetInfo,
- getDeploymentMetricsQueryPayload,
-} from './constants';
-import { DeploymentDetailsProps } from './DeploymentDetails.interfaces';
-
-import '../../EntityDetailsUtils/entityDetails.styles.scss';
-
-function DeploymentDetails({
- deployment,
- onClose,
- isModalTimeSelection,
-}: DeploymentDetailsProps): JSX.Element {
- const { maxTime, minTime, selectedTime } = useSelector<
- AppState,
- GlobalReducer
- >((state) => state.globalTime);
-
- const startMs = useMemo(() => Math.floor(Number(minTime) / 1000000000), [
- minTime,
- ]);
- const endMs = useMemo(() => Math.floor(Number(maxTime) / 1000000000), [
- maxTime,
- ]);
-
- const urlQuery = useUrlQuery();
-
- const [modalTimeRange, setModalTimeRange] = useState(() => ({
- startTime: startMs,
- endTime: endMs,
- }));
-
- const lastSelectedInterval = useRef<Time | null>(null);
-
- const [selectedInterval, setSelectedInterval] = useState<Time>(
- lastSelectedInterval.current
- ? lastSelectedInterval.current
- : (selectedTime as Time),
- );
-
- const [selectedView, setSelectedView] = useInfraMonitoringView();
- const [logFiltersParam, setLogFiltersParam] = useInfraMonitoringLogFilters();
- const [
- tracesFiltersParam,
- setTracesFiltersParam,
- ] = useInfraMonitoringTracesFilters();
- const [
- eventsFiltersParam,
- setEventsFiltersParam,
- ] = useInfraMonitoringEventsFilters();
- const isDarkMode = useIsDarkMode();
-
- const initialFilters = useMemo(() => {
- const filters =
- selectedView === VIEW_TYPES.LOGS ? logFiltersParam : tracesFiltersParam;
- if (filters) {
- return filters;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_DEPLOYMENT_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s_deployment_name--string--resource--false',
- },
- op: '=',
- value: deployment?.meta.k8s_deployment_name || '',
- },
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_NAMESPACE_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s_deployment_name--string--resource--false',
- },
- op: '=',
- value: deployment?.meta.k8s_namespace_name || '',
- },
- ],
- };
- }, [
- deployment?.meta.k8s_deployment_name,
- deployment?.meta.k8s_namespace_name,
- selectedView,
- logFiltersParam,
- tracesFiltersParam,
- ]);
-
- const initialEventsFilters = useMemo(() => {
- if (eventsFiltersParam) {
- return eventsFiltersParam;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_KIND,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.kind--string--resource--false',
- },
- op: '=',
- value: 'Deployment',
- },
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.name--string--resource--false',
- },
- op: '=',
- value: deployment?.meta.k8s_deployment_name || '',
- },
- ],
- };
- }, [deployment?.meta.k8s_deployment_name, eventsFiltersParam]);
-
- const [logAndTracesFilters, setLogAndTracesFilters] = useState<
- IBuilderQuery['filters']
- >(initialFilters);
-
- const [eventsFilters, setEventsFilters] = useState<IBuilderQuery['filters']>(
- initialEventsFilters,
- );
-
- useEffect(() => {
- if (deployment) {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Deployment,
- });
- }
- }, [deployment]);
-
- useEffect(() => {
- setLogAndTracesFilters(initialFilters);
- setEventsFilters(initialEventsFilters);
- }, [initialFilters, initialEventsFilters]);
-
- useEffect(() => {
- const currentSelectedInterval = lastSelectedInterval.current || selectedTime;
- setSelectedInterval(currentSelectedInterval as Time);
-
- if (currentSelectedInterval !== 'custom') {
- const { maxTime, minTime } = GetMinMax(currentSelectedInterval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- }, [selectedTime, minTime, maxTime]);
-
- const handleTabChange = (e: RadioChangeEvent): void => {
- setSelectedView(e.target.value);
- setLogFiltersParam(null);
- setTracesFiltersParam(null);
- setEventsFiltersParam(null);
- logEvent(InfraMonitoringEvents.TabChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Deployment,
- view: e.target.value,
- });
- };
-
- const handleTimeChange = useCallback(
- (interval: Time | CustomTimeType, dateTimeRange?: [number, number]): void => {
- lastSelectedInterval.current = interval as Time;
- setSelectedInterval(interval as Time);
-
- if (interval === 'custom' && dateTimeRange) {
- setModalTimeRange({
- startTime: Math.floor(dateTimeRange[0] / 1000),
- endTime: Math.floor(dateTimeRange[1] / 1000),
- });
- } else {
- const { maxTime, minTime } = GetMinMax(interval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
-
- logEvent(InfraMonitoringEvents.TimeUpdated, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Deployment,
- interval,
- view: selectedView,
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeLogFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_DEPLOYMENT_NAME, QUERY_KEYS.K8S_NAMESPACE_NAME].includes(
- item.key?.key ?? '',
- ),
- );
- const paginationFilter = value?.items?.find(
- (item) => item.key?.key === 'id',
- );
- const newFilters = value?.items?.filter(
- (item) =>
- item.key?.key !== 'id' &&
- item.key?.key !== QUERY_KEYS.K8S_DEPLOYMENT_NAME,
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Deployment,
- view: InfraMonitoringEvents.LogsView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(newFilters || []),
- ...(paginationFilter ? [paginationFilter] : []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setLogFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeTracesFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_DEPLOYMENT_NAME, QUERY_KEYS.K8S_NAMESPACE_NAME].includes(
- item.key?.key ?? '',
- ),
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Deployment,
- view: InfraMonitoringEvents.TracesView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(value?.items?.filter(
- (item) => item.key?.key !== QUERY_KEYS.K8S_DEPLOYMENT_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setTracesFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeEventsFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setEventsFilters((prevFilters) => {
- const deploymentKindFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_KIND,
- );
- const deploymentNameFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_NAME,
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Deployment,
- view: InfraMonitoringEvents.EventsView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- deploymentKindFilter,
- deploymentNameFilter,
- ...(value?.items?.filter(
- (item) =>
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_KIND &&
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setEventsFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleExplorePagesRedirect = (): void => {
- if (selectedInterval !== 'custom') {
- urlQuery.set(QueryParams.relativeTime, selectedInterval);
- } else {
- urlQuery.delete(QueryParams.relativeTime);
- urlQuery.set(QueryParams.startTime, modalTimeRange.startTime.toString());
- urlQuery.set(QueryParams.endTime, modalTimeRange.endTime.toString());
- }
-
- logEvent(InfraMonitoringEvents.ExploreClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Deployment,
- view: selectedView,
- });
-
- if (selectedView === VIEW_TYPES.LOGS) {
- const filtersWithoutPagination = {
- ...logAndTracesFilters,
- items: logAndTracesFilters?.items?.filter((item) => item.key?.key !== 'id'),
- };
-
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.logs,
- aggregateOperator: LogsAggregatorOperator.NOOP,
- filters: filtersWithoutPagination,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.LOGS_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- } else if (selectedView === VIEW_TYPES.TRACES) {
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.traces,
- aggregateOperator: TracesAggregatorOperator.NOOP,
- filters: logAndTracesFilters,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.TRACES_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- }
- };
-
- const handleClose = (): void => {
- lastSelectedInterval.current = null;
- setSelectedInterval(selectedTime as Time);
-
- if (selectedTime !== 'custom') {
- const { maxTime, minTime } = GetMinMax(selectedTime);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- setSelectedView(VIEW_TYPES.METRICS);
- onClose();
- };
-
- return (
- <Drawer
- width="70%"
- title={
- <>
- <Divider type="vertical" />
- <Typography.Text className="title">
- {deployment?.meta.k8s_deployment_name}
- </Typography.Text>
- </>
- }
- placement="right"
- onClose={handleClose}
- open={!!deployment}
- style={{
- overscrollBehavior: 'contain',
- background: isDarkMode ? Color.BG_INK_400 : Color.BG_VANILLA_100,
- }}
- className="entity-detail-drawer"
- destroyOnClose
- closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
- >
- {deployment && (
- <>
- <div className="entity-detail-drawer__entity">
- <div className="entity-details-grid">
- <div className="labels-row">
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Deployment Name
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Cluster Name
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Namespace Name
- </Typography.Text>
- </div>
- <div className="values-row">
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={deployment.meta.k8s_deployment_name}>
- {deployment.meta.k8s_deployment_name}
- </Tooltip>
- </Typography.Text>
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={deployment.meta.k8s_cluster_name}>
- {deployment.meta.k8s_cluster_name}
- </Tooltip>
- </Typography.Text>
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={deployment.meta.k8s_namespace_name}>
- {deployment.meta.k8s_namespace_name}
- </Tooltip>
- </Typography.Text>
- </div>
- </div>
- </div>
-
- <div className="views-tabs-container">
- <Radio.Group
- className="views-tabs"
- onChange={handleTabChange}
- value={selectedView}
- >
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.METRICS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.METRICS}
- >
- <div className="view-title">
- <BarChart2 size={14} />
- Metrics
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.LOGS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.LOGS}
- >
- <div className="view-title">
- <ScrollText size={14} />
- Logs
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.TRACES ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.TRACES}
- >
- <div className="view-title">
- <DraftingCompass size={14} />
- Traces
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.EVENTS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.EVENTS}
- >
- <div className="view-title">
- <ChevronsLeftRight size={14} />
- Events
- </div>
- </Radio.Button>
- </Radio.Group>
-
- {(selectedView === VIEW_TYPES.LOGS ||
- selectedView === VIEW_TYPES.TRACES) && (
- <Button
- icon={<Compass size={18} />}
- className="compass-button"
- onClick={handleExplorePagesRedirect}
- />
- )}
- </div>
- {selectedView === VIEW_TYPES.METRICS && (
- <DeploymentMetrics<K8sDeploymentsData>
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- entity={deployment}
- entityWidgetInfo={deploymentWidgetInfo}
- getEntityQueryPayload={getDeploymentMetricsQueryPayload}
- category={K8sCategory.DEPLOYMENTS}
- queryKey="deploymentMetrics"
- />
- )}
- {selectedView === VIEW_TYPES.LOGS && (
- <DeploymentLogs
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeLogFilters={handleChangeLogFilters}
- logFilters={logAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKeyFilters={[
- QUERY_KEYS.K8S_DEPLOYMENT_NAME,
- QUERY_KEYS.K8S_NAMESPACE_NAME,
- ]}
- queryKey="deploymentLogs"
- category={K8sCategory.DEPLOYMENTS}
- />
- )}
- {selectedView === VIEW_TYPES.TRACES && (
- <DeploymentTraces
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeTracesFilters={handleChangeTracesFilters}
- tracesFilters={logAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKey="deploymentTraces"
- category={InfraMonitoringEvents.Deployment}
- queryKeyFilters={[
- QUERY_KEYS.K8S_DEPLOYMENT_NAME,
- QUERY_KEYS.K8S_NAMESPACE_NAME,
- ]}
- />
- )}
- {selectedView === VIEW_TYPES.EVENTS && (
- <DeploymentEvents
- timeRange={modalTimeRange}
- handleChangeEventFilters={handleChangeEventsFilters}
- filters={eventsFilters}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- category={K8sCategory.DEPLOYMENTS}
- queryKey="deploymentEvents"
- />
- )}
- </>
- )}
- </Drawer>
- );
-}
-
-export default DeploymentDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/Deployments/DeploymentDetails/index.ts b/frontend/src/container/InfraMonitoringK8s/Deployments/DeploymentDetails/index.ts
deleted file mode 100644
index 8fb076b645..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Deployments/DeploymentDetails/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import DeploymentDetails from './DeploymentDetails';
-
-export default DeploymentDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/Deployments/K8sDeploymentsList.styles.scss b/frontend/src/container/InfraMonitoringK8s/Deployments/K8sDeploymentsList.styles.scss
deleted file mode 100644
index e5c3027873..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Deployments/K8sDeploymentsList.styles.scss
+++ /dev/null
@@ -1,57 +0,0 @@
-.infra-monitoring-container {
- .deployments-list-table {
- .expanded-table-container {
- padding-left: 20px;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
- }
-}
-
-.ant-table-cell {
- &:has(.deployment-name-header) {
- min-width: 250px !important;
- max-width: 250px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.namespace-name-header) {
- min-width: 220px !important;
- max-width: 220px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.med-col) {
- min-width: 200px !important;
- max-width: 200px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.small-col) {
- min-width: 120px !important;
- max-width: 120px !important;
- }
-}
-
-.progress-container {
- display: flex !important;
- justify-content: start !important;
-}
-
-.expanded-deployments-list-table {
- .ant-table-cell {
- min-width: 180px !important;
- max-width: 180px !important;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
-}
diff --git a/frontend/src/container/InfraMonitoringK8s/Deployments/K8sDeploymentsList.tsx b/frontend/src/container/InfraMonitoringK8s/Deployments/K8sDeploymentsList.tsx
index bb09f35404..b474dcf88f 100644
--- a/frontend/src/container/InfraMonitoringK8s/Deployments/K8sDeploymentsList.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/Deployments/K8sDeploymentsList.tsx
@@ -1,724 +1,118 @@
-import React, { useCallback, useEffect, useMemo, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { LoadingOutlined } from '@ant-design/icons';
-import {
- Button,
- Spin,
- Table,
- TableColumnType as ColumnType,
- TablePaginationConfig,
- TableProps,
- Typography,
-} from 'antd';
-import type { SorterResult } from 'antd/es/table/interface';
-import logEvent from 'api/common/logEvent';
-import { K8sDeploymentsListPayload } from 'api/infraMonitoring/getK8sDeploymentsList';
-import classNames from 'classnames';
+import React, { useCallback } from 'react';
import { InfraMonitoringEvents } from 'constants/events';
import { FeatureKeys } from 'constants/features';
-import { useGetK8sDeploymentsList } from 'hooks/infraMonitoring/useGetK8sDeploymentsList';
-import { useGetAggregateKeys } from 'hooks/queryBuilder/useGetAggregateKeys';
-import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
-import { ChevronDown, ChevronRight } from 'lucide-react';
import { useAppContext } from 'providers/App/App';
-import { AppState } from 'store/reducers';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { buildAbsolutePath, isModifierKeyPressed } from 'utils/app';
-import { openInNewTab } from 'utils/navigation';
-
-import emptyStateUrl from '@/assets/Icons/emptyState.svg';
+import K8sBaseDetails, { K8sDetailsFilters } from '../Base/K8sBaseDetails';
+import { K8sBaseList } from '../Base/K8sBaseList';
+import { K8sBaseFilters } from '../Base/types';
+import { InfraMonitoringEntity } from '../constants';
+import { getK8sDeploymentsList, K8sDeploymentsData } from './api';
import {
- GetK8sEntityToAggregateAttribute,
- INFRA_MONITORING_K8S_PARAMS_KEYS,
- K8sCategory,
-} from '../constants';
-import {
- useInfraMonitoringCurrentPage,
- useInfraMonitoringDeploymentUID,
- useInfraMonitoringEventsFilters,
- useInfraMonitoringGroupBy,
- useInfraMonitoringLogFilters,
- useInfraMonitoringOrderBy,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from '../hooks';
-import K8sHeader from '../K8sHeader';
-import LoadingContainer from '../LoadingContainer';
-import { usePageSize } from '../utils';
-import DeploymentDetails from './DeploymentDetails';
+ deploymentWidgetInfo,
+ getDeploymentMetricsQueryPayload,
+ k8sDeploymentDetailsMetadataConfig,
+ k8sDeploymentGetEntityName,
+ k8sDeploymentGetSelectedItemFilters,
+ k8sDeploymentInitialEventsFilter,
+ k8sDeploymentInitialFilters,
+ k8sDeploymentInitialLogTracesFilter,
+} from './constants';
import {
- defaultAddedColumns,
- formatDataForTable,
- getK8sDeploymentsListColumns,
- getK8sDeploymentsListQuery,
- K8sDeploymentsRowData,
-} from './utils';
-
-import '../InfraMonitoringK8s.styles.scss';
-import './K8sDeploymentsList.styles.scss';
+ k8sDeploymentsColumns,
+ k8sDeploymentsColumnsConfig,
+ k8sDeploymentsRenderRowData,
+} from './table.config';
function K8sDeploymentsList({
- isFiltersVisible,
- handleFilterVisibilityChange,
- quickFiltersLastUpdated,
+ controlListPrefix,
}: {
- isFiltersVisible: boolean;
- handleFilterVisibilityChange: () => void;
- quickFiltersLastUpdated: number;
+ controlListPrefix?: React.ReactNode;
}): JSX.Element {
- const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
- (state) => state.globalTime,
- );
-
- const [currentPage, setCurrentPage] = useInfraMonitoringCurrentPage();
- const [filtersInitialised, setFiltersInitialised] = useState(false);
-
- const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
-
- const [orderBy, setOrderBy] = useInfraMonitoringOrderBy();
-
- const [
- selectedDeploymentUID,
- setselectedDeploymentUID,
- ] = useInfraMonitoringDeploymentUID();
-
- const { pageSize, setPageSize } = usePageSize(K8sCategory.DEPLOYMENTS);
-
- const [groupBy, setGroupBy] = useInfraMonitoringGroupBy();
-
- const [, setView] = useInfraMonitoringView();
- const [, setTracesFilters] = useInfraMonitoringTracesFilters();
- const [, setEventsFilters] = useInfraMonitoringEventsFilters();
- const [, setLogFilters] = useInfraMonitoringLogFilters();
-
- const [
- selectedRowData,
- setSelectedRowData,
- ] = useState<K8sDeploymentsRowData | null>(null);
-
- const [groupByOptions, setGroupByOptions] = useState<
- { value: string; label: string }[]
- >([]);
-
- const { currentQuery } = useQueryBuilder();
-
- const queryFilters = useMemo(
- () =>
- currentQuery?.builder?.queryData[0]?.filters || {
- items: [],
- op: 'and',
- },
- [currentQuery?.builder?.queryData],
- );
-
- // Reset pagination every time quick filters are changed
- useEffect(() => {
- if (quickFiltersLastUpdated !== -1) {
- setCurrentPage(1);
- }
- }, [quickFiltersLastUpdated, setCurrentPage]);
-
const { featureFlags } = useAppContext();
const dotMetricsEnabled =
featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
?.active || false;
- const createFiltersForSelectedRowData = (
- selectedRowData: K8sDeploymentsRowData,
- groupBy: IBuilderQuery['groupBy'],
- ): IBuilderQuery['filters'] => {
- const baseFilters: IBuilderQuery['filters'] = {
- items: [...queryFilters.items],
- op: 'and',
- };
-
- if (!selectedRowData) {
- return baseFilters;
- }
-
- const { groupedByMeta } = selectedRowData;
-
- for (const key of groupBy) {
- baseFilters.items.push({
- key: {
- key: key.key,
- type: null,
- },
- op: '=',
- value: groupedByMeta[key.key],
- id: key.key,
- });
- }
-
- return baseFilters;
- };
-
- const fetchGroupedByRowDataQuery = useMemo(() => {
- if (!selectedRowData) {
- return null;
- }
-
- const baseQuery = getK8sDeploymentsListQuery();
-
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- return {
- ...baseQuery,
- limit: 10,
- offset: 0,
- filters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [minTime, maxTime, orderBy, selectedRowData, groupBy]);
-
- const groupedByRowDataQueryKey = useMemo(() => {
- // be careful with what you serialize from selectedRowData
- // since it's react node, it could contain circular references
- const selectedRowDataKey = JSON.stringify(selectedRowData?.groupedByMeta);
- if (selectedDeploymentUID) {
- return [
- 'deploymentList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- ];
- }
- return [
- 'deploymentList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- String(minTime),
- String(maxTime),
- ];
- }, [
- queryFilters,
- orderBy,
- selectedDeploymentUID,
- minTime,
- maxTime,
- selectedRowData,
- ]);
-
- const {
- data: groupedByRowData,
- isFetching: isFetchingGroupedByRowData,
- isLoading: isLoadingGroupedByRowData,
- isError: isErrorGroupedByRowData,
- refetch: fetchGroupedByRowData,
- } = useGetK8sDeploymentsList(
- fetchGroupedByRowDataQuery as K8sDeploymentsListPayload,
- {
- queryKey: groupedByRowDataQueryKey,
- enabled: !!fetchGroupedByRowDataQuery && !!selectedRowData,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const {
- data: groupByFiltersData,
- isLoading: isLoadingGroupByFilters,
- } = useGetAggregateKeys(
- {
- dataSource: currentQuery.builder.queryData[0].dataSource,
- aggregateAttribute: GetK8sEntityToAggregateAttribute(
- K8sCategory.DEPLOYMENTS,
+ const fetchListData = useCallback(
+ async (filters: K8sBaseFilters, signal?: AbortSignal) => {
+ filters.orderBy ||= {
+ columnName: 'cpu',
+ order: 'desc',
+ };
+
+ const response = await getK8sDeploymentsList(
+ filters,
+ signal,
+ undefined,
dotMetricsEnabled,
- ),
- aggregateOperator: 'noop',
- searchText: '',
- tagType: '',
- },
- {
- queryKey: [currentQuery.builder.queryData[0].dataSource, 'noop'],
- },
- true,
- K8sCategory.NODES,
- );
-
- const query = useMemo(() => {
- const baseQuery = getK8sDeploymentsListQuery();
- const queryPayload = {
- ...baseQuery,
- limit: pageSize,
- offset: (currentPage - 1) * pageSize,
- filters: queryFilters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- if (groupBy.length > 0) {
- queryPayload.groupBy = groupBy;
- }
- return queryPayload;
- }, [pageSize, currentPage, queryFilters, minTime, maxTime, orderBy, groupBy]);
-
- const formattedGroupedByDeploymentsData = useMemo(
- () =>
- formatDataForTable(groupedByRowData?.payload?.data?.records || [], groupBy),
- [groupedByRowData, groupBy],
- );
-
- const queryKey = useMemo(() => {
- if (selectedDeploymentUID) {
- return [
- 'deploymentList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- ];
- }
- return [
- 'deploymentList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- String(minTime),
- String(maxTime),
- ];
- }, [
- selectedDeploymentUID,
- pageSize,
- currentPage,
- queryFilters,
- orderBy,
- groupBy,
- minTime,
- maxTime,
- ]);
-
- const { data, isFetching, isLoading, isError } = useGetK8sDeploymentsList(
- query as K8sDeploymentsListPayload,
- {
- queryKey,
- enabled: !!query,
- keepPreviousData: true,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const deploymentsData = useMemo(() => data?.payload?.data?.records || [], [
- data,
- ]);
- const totalCount = data?.payload?.data?.total || 0;
-
- const formattedDeploymentsData = useMemo(
- () => formatDataForTable(deploymentsData, groupBy),
- [deploymentsData, groupBy],
- );
-
- const nestedDeploymentsData = useMemo(() => {
- if (!selectedRowData || !groupedByRowData?.payload?.data.records) {
- return [];
- }
- return groupedByRowData?.payload?.data?.records || [];
- }, [groupedByRowData, selectedRowData]);
-
- const columns = useMemo(() => getK8sDeploymentsListColumns(groupBy), [
- groupBy,
- ]);
-
- const handleGroupByRowClick = (record: K8sDeploymentsRowData): void => {
- setSelectedRowData(record);
-
- if (expandedRowKeys.includes(record.key)) {
- setExpandedRowKeys(expandedRowKeys.filter((key) => key !== record.key));
- } else {
- setExpandedRowKeys([record.key]);
- }
- };
-
- useEffect(() => {
- if (selectedRowData) {
- fetchGroupedByRowData();
- }
- }, [selectedRowData, fetchGroupedByRowData]);
-
- const handleTableChange: TableProps<K8sDeploymentsRowData>['onChange'] = useCallback(
- (
- pagination: TablePaginationConfig,
- _filters: Record<string, (string | number | boolean)[] | null>,
- sorter:
- | SorterResult<K8sDeploymentsRowData>
- | SorterResult<K8sDeploymentsRowData>[],
- ): void => {
- if (pagination.current) {
- setCurrentPage(pagination.current);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Deployment,
- });
- }
-
- if ('field' in sorter && sorter.order) {
- setOrderBy({
- columnName: sorter.field as string,
- order: (sorter.order === 'ascend' ? 'asc' : 'desc') as 'asc' | 'desc',
- });
- } else {
- setOrderBy(null);
- }
- },
- [setCurrentPage, setOrderBy],
- );
-
- const { handleChangeQueryData } = useQueryOperations({
- index: 0,
- query: currentQuery.builder.queryData[0],
- entityVersion: '',
- });
-
- const handleFiltersChange = useCallback(
- (value: IBuilderQuery['filters']): void => {
- handleChangeQueryData('filters', value);
- if (filtersInitialised) {
- setCurrentPage(1);
- } else {
- setFiltersInitialised(true);
- }
+ );
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Deployment,
- });
- }
+ return {
+ data: response.payload?.data.records || [],
+ total: response.payload?.data.total || 0,
+ error: response.error,
+ rawData: response.payload?.data,
+ };
},
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Deployment,
- total: data?.payload?.data?.total,
- });
- }, [data?.payload?.data?.total]);
-
- const selectedDeploymentData = useMemo(() => {
- if (!selectedDeploymentUID) {
- return null;
- }
- if (groupBy.length > 0) {
- // If grouped by, return the deployment from the formatted grouped by deployments data
- return (
- nestedDeploymentsData.find(
- (deployment) => deployment.deploymentName === selectedDeploymentUID,
- ) || null
+ const fetchEntityData = useCallback(
+ async (
+ filters: K8sDetailsFilters,
+ signal?: AbortSignal,
+ ): Promise<{ data: K8sDeploymentsData | null; error?: string | null }> => {
+ const response = await getK8sDeploymentsList(
+ {
+ filters: filters.filters,
+ start: filters.start,
+ end: filters.end,
+ limit: 1,
+ offset: 0,
+ },
+ signal,
+ undefined,
+ dotMetricsEnabled,
);
- }
- // If not grouped by, return the deployment from the deployments data
- return (
- deploymentsData.find(
- (deployment) => deployment.deploymentName === selectedDeploymentUID,
- ) || null
- );
- }, [
- selectedDeploymentUID,
- groupBy.length,
- deploymentsData,
- nestedDeploymentsData,
- ]);
-
- const openDeploymentInNewTab = (record: K8sDeploymentsRowData): void => {
- const newParams = new URLSearchParams(document.location.search);
- newParams.set(
- INFRA_MONITORING_K8S_PARAMS_KEYS.DEPLOYMENT_UID,
- record.deploymentUID,
- );
- openInNewTab(
- buildAbsolutePath({
- relativePath: '',
- urlQueryString: newParams.toString(),
- }),
- );
- };
-
- const handleRowClick = (
- record: K8sDeploymentsRowData,
- event?: React.MouseEvent,
- ): void => {
- if (event && isModifierKeyPressed(event)) {
- openDeploymentInNewTab(record);
- return;
- }
- if (groupBy.length === 0) {
- setSelectedRowData(null);
- setselectedDeploymentUID(record.deploymentUID);
- } else {
- handleGroupByRowClick(record);
- }
-
- logEvent(InfraMonitoringEvents.ItemClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Deployment,
- });
- };
-
- const nestedColumns = useMemo(() => getK8sDeploymentsListColumns([]), []);
-
- const isGroupedByAttribute = groupBy.length > 0;
- const handleExpandedRowViewAllClick = (): void => {
- if (!selectedRowData) {
- return;
- }
+ const records = response.payload?.data.records || [];
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- handleFiltersChange(filters);
-
- setCurrentPage(1);
- setSelectedRowData(null);
- setGroupBy([]);
- setOrderBy(null);
- };
-
- const expandedRowRender = (): JSX.Element => (
- <div className="expanded-table-container">
- {isErrorGroupedByRowData && (
- <Typography>{groupedByRowData?.error || 'Something went wrong'}</Typography>
- )}
- {isFetchingGroupedByRowData || isLoadingGroupedByRowData ? (
- <LoadingContainer />
- ) : (
- <div className="expanded-table">
- <Table
- columns={nestedColumns as ColumnType<K8sDeploymentsRowData>[]}
- dataSource={formattedGroupedByDeploymentsData}
- pagination={false}
- scroll={{ x: true }}
- tableLayout="fixed"
- size="small"
- loading={{
- spinning: isFetchingGroupedByRowData || isLoadingGroupedByRowData,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- showHeader={false}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => {
- if (event && isModifierKeyPressed(event)) {
- openDeploymentInNewTab(record);
- return;
- }
- setselectedDeploymentUID(record.deploymentUID);
- },
- className: 'expanded-clickable-row',
- })}
- />
-
- {groupedByRowData?.payload?.data?.total &&
- groupedByRowData?.payload?.data?.total > 10 ? (
- <div className="expanded-table-footer">
- <Button
- type="default"
- size="small"
- className="periscope-btn secondary"
- onClick={handleExpandedRowViewAllClick}
- >
- View All
- </Button>
- </div>
- ) : null}
- </div>
- )}
- </div>
- );
-
- const expandRowIconRenderer = ({
- expanded,
- onExpand,
- record,
- }: {
- expanded: boolean;
- onExpand: (
- record: K8sDeploymentsRowData,
- e: React.MouseEvent<HTMLButtonElement>,
- ) => void;
- record: K8sDeploymentsRowData;
- }): JSX.Element | null => {
- if (!isGroupedByAttribute) {
- return null;
- }
-
- return expanded ? (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronDown size={14} />
- </Button>
- ) : (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronRight size={14} />
- </Button>
- );
- };
-
- const handleCloseDeploymentDetail = (): void => {
- setselectedDeploymentUID(null);
- setView(null);
- setTracesFilters(null);
- setEventsFilters(null);
- setLogFilters(null);
- };
-
- const handleGroupByChange = useCallback(
- (value: IBuilderQuery['groupBy']) => {
- const groupBy = [];
-
- for (let index = 0; index < value.length; index++) {
- const element = (value[index] as unknown) as string;
-
- const key = groupByFiltersData?.payload?.attributeKeys?.find(
- (key) => key.key === element,
- );
-
- if (key) {
- groupBy.push(key);
- }
- }
-
- // Reset pagination on switching to groupBy
- setCurrentPage(1);
- setGroupBy(groupBy);
- setExpandedRowKeys([]);
-
- logEvent(InfraMonitoringEvents.GroupByChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Deployment,
- });
+ return {
+ data: records.length > 0 ? records[0] : null,
+ error: response.error,
+ };
},
- [groupByFiltersData, setCurrentPage, setGroupBy],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- if (groupByFiltersData?.payload) {
- setGroupByOptions(
- groupByFiltersData?.payload?.attributeKeys?.map((filter) => ({
- value: filter.key,
- label: filter.key,
- })) || [],
- );
- }
- }, [groupByFiltersData]);
-
- const onPaginationChange = (page: number, pageSize: number): void => {
- setCurrentPage(page);
- setPageSize(pageSize);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Deployment,
- });
- };
-
- const showTableLoadingState =
- (isFetching || isLoading) && formattedDeploymentsData.length === 0;
-
return (
- <div className="k8s-list">
- <K8sHeader
- isFiltersVisible={isFiltersVisible}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- defaultAddedColumns={defaultAddedColumns}
- handleFiltersChange={handleFiltersChange}
- groupByOptions={groupByOptions}
- isLoadingGroupByFilters={isLoadingGroupByFilters}
- handleGroupByChange={handleGroupByChange}
- selectedGroupBy={groupBy}
- entity={K8sCategory.NODES}
- showAutoRefresh={!selectedDeploymentData}
- />
- {isError && <Typography>{data?.error || 'Something went wrong'}</Typography>}
-
- <Table
- className={classNames('k8s-list-table', 'deployments-list-table', {
- 'expanded-deployments-list-table': isGroupedByAttribute,
- })}
- dataSource={showTableLoadingState ? [] : formattedDeploymentsData}
- columns={columns}
- pagination={{
- current: currentPage,
- pageSize,
- total: totalCount,
- showSizeChanger: true,
- hideOnSinglePage: false,
- onChange: onPaginationChange,
- }}
- scroll={{ x: true }}
- loading={{
- spinning: showTableLoadingState,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- locale={{
- emptyText: showTableLoadingState ? null : (
- <div className="no-filtered-hosts-message-container">
- <div className="no-filtered-hosts-message-content">
- <img
- src={emptyStateUrl}
- alt="thinking-emoji"
- className="empty-state-svg"
- />
-
- <Typography.Text className="no-filtered-hosts-message">
- This query had no results. Edit your query and try again!
- </Typography.Text>
- </div>
- </div>
- ),
- }}
- tableLayout="fixed"
- onChange={handleTableChange}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => handleRowClick(record, event),
- className: 'clickable-row',
- })}
- expandable={{
- expandedRowRender: isGroupedByAttribute ? expandedRowRender : undefined,
- expandIcon: expandRowIconRenderer,
- expandedRowKeys,
- }}
+ <>
+ <K8sBaseList<K8sDeploymentsData>
+ controlListPrefix={controlListPrefix}
+ entity={InfraMonitoringEntity.DEPLOYMENTS}
+ tableColumnsDefinitions={k8sDeploymentsColumns}
+ tableColumns={k8sDeploymentsColumnsConfig}
+ fetchListData={fetchListData}
+ renderRowData={k8sDeploymentsRenderRowData}
+ eventCategory={InfraMonitoringEvents.Deployment}
/>
- <DeploymentDetails
- deployment={selectedDeploymentData}
- isModalTimeSelection
- onClose={handleCloseDeploymentDetail}
+ <K8sBaseDetails<K8sDeploymentsData>
+ category={InfraMonitoringEntity.DEPLOYMENTS}
+ eventCategory={InfraMonitoringEvents.Deployment}
+ getSelectedItemFilters={k8sDeploymentGetSelectedItemFilters}
+ fetchEntityData={fetchEntityData}
+ getEntityName={k8sDeploymentGetEntityName}
+ getInitialLogTracesFilters={k8sDeploymentInitialLogTracesFilter}
+ getInitialEventsFilters={k8sDeploymentInitialEventsFilter}
+ primaryFilterKeys={k8sDeploymentInitialFilters}
+ metadataConfig={k8sDeploymentDetailsMetadataConfig}
+ entityWidgetInfo={deploymentWidgetInfo}
+ getEntityQueryPayload={getDeploymentMetricsQueryPayload}
+ queryKeyPrefix="deployment"
/>
- </div>
+ </>
);
}
diff --git a/frontend/src/api/infraMonitoring/getK8sDeploymentsList.ts b/frontend/src/container/InfraMonitoringK8s/Deployments/api.ts
similarity index 72%
rename from frontend/src/api/infraMonitoring/getK8sDeploymentsList.ts
rename to frontend/src/container/InfraMonitoringK8s/Deployments/api.ts
index 4dd19b3dd4..b171a5ced6 100644
--- a/frontend/src/api/infraMonitoring/getK8sDeploymentsList.ts
+++ b/frontend/src/container/InfraMonitoringK8s/Deployments/api.ts
@@ -1,11 +1,12 @@
import axios from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
+import { UnderscoreToDotMap } from 'api/utils';
import { AxiosError } from 'axios';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
-import { UnderscoreToDotMap } from '../utils';
+import { K8sBaseFilters } from '../Base/types';
export interface K8sDeploymentsListPayload {
filters: TagFilter;
@@ -48,6 +49,7 @@ export interface K8sDeploymentsListResponse {
};
}
+// TODO(H4ad): Erase this whole file when migrating to openapi
export const deploymentsMetaMap = [
{ dot: 'k8s.cluster.name', under: 'k8s_cluster_name' },
{ dot: 'k8s.deployment.name', under: 'k8s_deployment_name' },
@@ -68,44 +70,43 @@ export function mapDeploymentsMeta(
}
export const getK8sDeploymentsList = async (
- props: K8sDeploymentsListPayload,
+ props: K8sBaseFilters,
signal?: AbortSignal,
headers?: Record<string, string>,
dotMetricsEnabled = false,
): Promise<SuccessResponse<K8sDeploymentsListResponse> | ErrorResponse> => {
try {
- const requestProps =
- dotMetricsEnabled && Array.isArray(props.filters?.items)
- ? {
- ...props,
- filters: {
- ...props.filters,
- items: props.filters.items.reduce<typeof props.filters.items>(
- (acc, item) => {
- if (item.value === undefined) {
- return acc;
- }
- if (
- item.key &&
- typeof item.key === 'object' &&
- 'key' in item.key &&
- typeof item.key.key === 'string'
- ) {
- const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
- acc.push({
- ...item,
- key: { ...item.key, key: mappedKey },
- });
- } else {
- acc.push(item);
- }
+ const requestProps = dotMetricsEnabled
+ ? {
+ ...props,
+ filters: {
+ ...props.filters,
+ items: props.filters.items.reduce<typeof props.filters.items>(
+ (acc, item) => {
+ if (item.value === undefined) {
return acc;
- },
- [] as typeof props.filters.items,
- ),
- },
- }
- : props;
+ }
+ if (
+ item.key &&
+ typeof item.key === 'object' &&
+ 'key' in item.key &&
+ typeof item.key.key === 'string'
+ ) {
+ const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
+ acc.push({
+ ...item,
+ key: { ...item.key, key: mappedKey },
+ });
+ } else {
+ acc.push(item);
+ }
+ return acc;
+ },
+ [] as typeof props.filters.items,
+ ),
+ },
+ }
+ : props;
const response = await axios.post('/deployments/list', requestProps, {
signal,
@@ -113,7 +114,6 @@ export const getK8sDeploymentsList = async (
});
const payload: K8sDeploymentsListResponse = response.data;
- // single-line mapping
payload.data.records = payload.data.records.map((record) => ({
...record,
meta: mapDeploymentsMeta(record.meta as Record<string, unknown>),
diff --git a/frontend/src/container/InfraMonitoringK8s/Deployments/DeploymentDetails/constants.ts b/frontend/src/container/InfraMonitoringK8s/Deployments/constants.ts
similarity index 88%
rename from frontend/src/container/InfraMonitoringK8s/Deployments/DeploymentDetails/constants.ts
rename to frontend/src/container/InfraMonitoringK8s/Deployments/constants.ts
index 5435c48e1a..445b2ba6bc 100644
--- a/frontend/src/container/InfraMonitoringK8s/Deployments/DeploymentDetails/constants.ts
+++ b/frontend/src/container/InfraMonitoringK8s/Deployments/constants.ts
@@ -1,11 +1,75 @@
-import { K8sDeploymentsData } from 'api/infraMonitoring/getK8sDeploymentsList';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { v4 } from 'uuid';
+import {
+ createFilterItem,
+ K8sDetailsMetadataConfig,
+} from '../Base/K8sBaseDetails';
+import { QUERY_KEYS } from '../EntityDetailsUtils/utils';
+import { K8sDeploymentsData } from './api';
+
+export const k8sDeploymentGetSelectedItemFilters = (
+ selectedItemId: string,
+): TagFilter => ({
+ op: 'AND',
+ items: [
+ {
+ id: 'k8s_deployment_name',
+ key: {
+ key: 'k8s_deployment_name',
+ type: null,
+ },
+ op: '=',
+ value: selectedItemId,
+ },
+ ],
+});
+
+export const k8sDeploymentDetailsMetadataConfig: K8sDetailsMetadataConfig<K8sDeploymentsData>[] = [
+ {
+ label: 'Deployment Name',
+ getValue: (p): string => p.meta.k8s_deployment_name,
+ },
+ {
+ label: 'Cluster Name',
+ getValue: (p): string => p.meta.k8s_cluster_name,
+ },
+ {
+ label: 'Namespace Name',
+ getValue: (p): string => p.meta.k8s_namespace_name,
+ },
+];
+
+export const k8sDeploymentInitialFilters = [
+ QUERY_KEYS.K8S_DEPLOYMENT_NAME,
+ QUERY_KEYS.K8S_NAMESPACE_NAME,
+];
+
+export const k8sDeploymentInitialEventsFilter = (
+ item: K8sDeploymentsData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_KIND, 'Deployment'),
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_NAME, item.meta.k8s_deployment_name),
+];
+
+export const k8sDeploymentInitialLogTracesFilter = (
+ item: K8sDeploymentsData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(
+ QUERY_KEYS.K8S_DEPLOYMENT_NAME,
+ item.meta.k8s_deployment_name,
+ ),
+ createFilterItem(QUERY_KEYS.K8S_NAMESPACE_NAME, item.meta.k8s_namespace_name),
+];
+
+export const k8sDeploymentGetEntityName = (item: K8sDeploymentsData): string =>
+ item.meta.k8s_deployment_name;
+
export const deploymentWidgetInfo = [
{
title: 'CPU usage, request, limits',
diff --git a/frontend/src/container/InfraMonitoringK8s/Deployments/table.config.tsx b/frontend/src/container/InfraMonitoringK8s/Deployments/table.config.tsx
new file mode 100644
index 0000000000..9e76a8231a
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Deployments/table.config.tsx
@@ -0,0 +1,269 @@
+import { TableColumnType as ColumnType, Tooltip } from 'antd';
+import { Group } from 'lucide-react';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+
+import { K8sRenderedRowData } from '../Base/types';
+import { IEntityColumn } from '../Base/useInfraMonitoringTableColumnsStore';
+import { getGroupByEl, getGroupedByMeta, getRowKey } from '../Base/utils';
+import {
+ EntityProgressBar,
+ formatBytes,
+ ValidateColumnValueWrapper,
+} from '../commonUtils';
+import { K8sDeploymentsData } from './api';
+
+import styles from './table.module.scss';
+
+export const k8sDeploymentsColumns: IEntityColumn[] = [
+ {
+ label: 'Deployment Group',
+ value: 'deploymentGroup',
+ id: 'deploymentGroup',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-collapse',
+ },
+ {
+ label: 'Deployment Name',
+ value: 'deploymentName',
+ id: 'deploymentName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-expand',
+ },
+ {
+ label: 'Namespace Name',
+ value: 'namespaceName',
+ id: 'namespaceName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Available',
+ value: 'available_pods',
+ id: 'available_pods',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Desired',
+ value: 'desired_pods',
+ id: 'desired_pods',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Req Usage (%)',
+ value: 'cpu_request',
+ id: 'cpu_request',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Limit Usage (%)',
+ value: 'cpu_limit',
+ id: 'cpu_limit',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Usage (cores)',
+ value: 'cpu',
+ id: 'cpu',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Req Usage (%)',
+ value: 'memory_request',
+ id: 'memory_request',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Limit Usage (%)',
+ value: 'memory_limit',
+ id: 'memory_limit',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Usage (WSS)',
+ value: 'memory',
+ id: 'memory',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+];
+
+export const k8sDeploymentsColumnsConfig: ColumnType<K8sRenderedRowData>[] = [
+ {
+ title: (
+ <div className={styles.entityGroupHeader}>
+ <Group size={14} /> DEPLOYMENT GROUP
+ </div>
+ ),
+ dataIndex: 'deploymentGroup',
+ key: 'deploymentGroup',
+ ellipsis: true,
+ width: 150,
+ align: 'left',
+ sorter: false,
+ },
+ {
+ title: <div>Deployment Name</div>,
+ dataIndex: 'deploymentName',
+ key: 'deploymentName',
+ ellipsis: true,
+ width: 150,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>Namespace Name</div>,
+ dataIndex: 'namespaceName',
+ key: 'namespaceName',
+ ellipsis: true,
+ width: 150,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>Available</div>,
+ dataIndex: 'available_pods',
+ key: 'available_pods',
+ width: 100,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>Desired</div>,
+ dataIndex: 'desired_pods',
+ key: 'desired_pods',
+ width: 80,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Req Usage (%)</div>,
+ dataIndex: 'cpu_request',
+ key: 'cpu_request',
+ width: 170,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Limit Usage (%)</div>,
+ dataIndex: 'cpu_limit',
+ key: 'cpu_limit',
+ width: 170,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Usage (cores)</div>,
+ dataIndex: 'cpu',
+ key: 'cpu',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Req Usage (%)</div>,
+ dataIndex: 'memory_request',
+ key: 'memory_request',
+ width: 170,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Limit Usage (%)</div>,
+ dataIndex: 'memory_limit',
+ key: 'memory_limit',
+ width: 170,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Usage (WSS)</div>,
+ dataIndex: 'memory',
+ key: 'memory',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+];
+
+export const k8sDeploymentsRenderRowData = (
+ deployment: K8sDeploymentsData,
+ groupBy: BaseAutocompleteData[],
+): K8sRenderedRowData => ({
+ key: getRowKey(deployment, () => deployment.meta.k8s_deployment_name, groupBy),
+ itemKey: deployment.meta.k8s_deployment_name,
+ deploymentName: (
+ <Tooltip title={deployment.meta.k8s_deployment_name}>
+ {deployment.meta.k8s_deployment_name || ''}
+ </Tooltip>
+ ),
+ namespaceName: deployment.meta.k8s_namespace_name,
+ available_pods: (
+ <ValidateColumnValueWrapper value={deployment.availablePods}>
+ {deployment.availablePods}
+ </ValidateColumnValueWrapper>
+ ),
+ desired_pods: (
+ <ValidateColumnValueWrapper value={deployment.desiredPods}>
+ {deployment.desiredPods}
+ </ValidateColumnValueWrapper>
+ ),
+ cpu: (
+ <ValidateColumnValueWrapper value={deployment.cpuUsage}>
+ {deployment.cpuUsage}
+ </ValidateColumnValueWrapper>
+ ),
+ cpu_request: (
+ <ValidateColumnValueWrapper value={deployment.cpuRequest}>
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={deployment.cpuRequest} type="request" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ cpu_limit: (
+ <ValidateColumnValueWrapper value={deployment.cpuLimit}>
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={deployment.cpuLimit} type="limit" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ memory: (
+ <ValidateColumnValueWrapper value={deployment.memoryUsage}>
+ {formatBytes(deployment.memoryUsage)}
+ </ValidateColumnValueWrapper>
+ ),
+ memory_request: (
+ <ValidateColumnValueWrapper value={deployment.memoryRequest}>
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={deployment.memoryRequest} type="request" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ memory_limit: (
+ <ValidateColumnValueWrapper value={deployment.memoryLimit}>
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={deployment.memoryLimit} type="limit" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ deploymentGroup: getGroupByEl(deployment, groupBy),
+ ...deployment.meta,
+ groupedByMeta: getGroupedByMeta(deployment, groupBy),
+});
diff --git a/frontend/src/container/InfraMonitoringK8s/Deployments/table.module.scss b/frontend/src/container/InfraMonitoringK8s/Deployments/table.module.scss
new file mode 100644
index 0000000000..bc11f496a1
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Deployments/table.module.scss
@@ -0,0 +1,11 @@
+.entityGroupHeader {
+ padding-left: var(--spacing-5);
+ gap: var(--spacing-5);
+ display: flex;
+ align-items: center;
+}
+
+.progressBar {
+ display: flex;
+ justify-content: start;
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Deployments/utils.tsx b/frontend/src/container/InfraMonitoringK8s/Deployments/utils.tsx
deleted file mode 100644
index 947a88008e..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Deployments/utils.tsx
+++ /dev/null
@@ -1,333 +0,0 @@
-import { Color } from '@signozhq/design-tokens';
-import { TableColumnType as ColumnType, Tag, Tooltip } from 'antd';
-import {
- K8sDeploymentsData,
- K8sDeploymentsListPayload,
-} from 'api/infraMonitoring/getK8sDeploymentsList';
-import { Group } from 'lucide-react';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-
-import {
- EntityProgressBar,
- formatBytes,
- ValidateColumnValueWrapper,
-} from '../commonUtils';
-import { IEntityColumn } from '../utils';
-
-export const defaultAddedColumns: IEntityColumn[] = [
- {
- label: 'Deployment Name',
- value: 'deploymentName',
- id: 'deploymentName',
- canRemove: false,
- },
- {
- label: 'Namespace Name',
- value: 'namespaceName',
- id: 'namespaceName',
- canRemove: false,
- },
- {
- label: 'Available',
- value: 'available_pods',
- id: 'available_pods',
- canRemove: false,
- },
- {
- label: 'Desired',
- value: 'desired_pods',
- id: 'desired_pods',
- canRemove: false,
- },
- {
- label: 'CPU Request Utilization (% of limit)',
- value: 'cpu_request',
- id: 'cpu_request',
- canRemove: false,
- },
- {
- label: 'CPU Limit Utilization (% of request)',
- value: 'cpu_limit',
- id: 'cpu_limit',
- canRemove: false,
- },
- {
- label: 'CPU Utilization (cores)',
- value: 'cpu',
- id: 'cpu',
- canRemove: false,
- },
- {
- label: 'Memory Request Utilization (% of limit)',
- value: 'memory_request',
- id: 'memory_request',
- canRemove: false,
- },
- {
- label: 'Memory Limit Utilization (% of request)',
- value: 'memory_limit',
- id: 'memory_limit',
- canRemove: false,
- },
- {
- label: 'Memory Utilization (bytes)',
- value: 'memory',
- id: 'memory',
- canRemove: false,
- },
-];
-
-export interface K8sDeploymentsRowData {
- key: string;
- deploymentUID: string;
- deploymentName: React.ReactNode;
- available_pods: React.ReactNode;
- desired_pods: React.ReactNode;
- cpu_request: React.ReactNode;
- cpu_limit: React.ReactNode;
- cpu: React.ReactNode;
- memory_request: React.ReactNode;
- memory_limit: React.ReactNode;
- memory: React.ReactNode;
- restarts: React.ReactNode;
- clusterName: string;
- namespaceName: string;
- groupedByMeta?: any;
-}
-
-const deploymentGroupColumnConfig = {
- title: (
- <div className="column-header entity-group-header">
- <Group size={14} /> DEPLOYMENT GROUP
- </div>
- ),
- dataIndex: 'deploymentGroup',
- key: 'deploymentGroup',
- ellipsis: true,
- width: 150,
- align: 'left',
- sorter: false,
- className: 'column entity-group-header',
-};
-
-export const getK8sDeploymentsListQuery = (): K8sDeploymentsListPayload => ({
- filters: {
- items: [],
- op: 'and',
- },
- orderBy: { columnName: 'cpu', order: 'desc' },
-});
-
-const columnsConfig = [
- {
- title: (
- <div className="column-header-left deployment-name-header">
- Deployment Name
- </div>
- ),
- dataIndex: 'deploymentName',
- key: 'deploymentName',
- ellipsis: true,
- width: 150,
- sorter: false,
- align: 'left',
- },
- {
- title: (
- <div className="column-header-left namespace-name-header">
- Namespace Name
- </div>
- ),
- dataIndex: 'namespaceName',
- key: 'namespaceName',
- ellipsis: true,
- width: 150,
- sorter: false,
- align: 'left',
- },
- {
- title: <div className="column-header-left small-col">Available</div>,
- dataIndex: 'available_pods',
- key: 'available_pods',
- width: 100,
- sorter: false,
- align: 'left',
- },
- {
- title: <div className="column-header-left small-col">Desired</div>,
- dataIndex: 'desired_pods',
- key: 'desired_pods',
- width: 80,
- sorter: false,
- align: 'left',
- },
- {
- title: <div className="column-header-left med-col">CPU Req Usage (%)</div>,
- dataIndex: 'cpu_request',
- key: 'cpu_request',
- width: 80,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header-left med-col">CPU Limit Usage (%)</div>,
- dataIndex: 'cpu_limit',
- key: 'cpu_limit',
- width: 50,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header- small-col">CPU Usage (cores)</div>,
- dataIndex: 'cpu',
- key: 'cpu',
- width: 80,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header-left med-col">Mem Req Usage (%)</div>,
- dataIndex: 'memory_request',
- key: 'memory_request',
- width: 50,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header-left med-col">Mem Limit Usage (%)</div>,
- dataIndex: 'memory_limit',
- key: 'memory_limit',
- width: 80,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header-left small-col">Mem Usage (WSS)</div>,
- dataIndex: 'memory',
- key: 'memory',
- width: 120,
- sorter: true,
- align: 'left',
- },
-];
-
-export const getK8sDeploymentsListColumns = (
- groupBy: IBuilderQuery['groupBy'],
-): ColumnType<K8sDeploymentsRowData>[] => {
- if (groupBy.length > 0) {
- const filteredColumns = [...columnsConfig].filter(
- (column) => column.key !== 'deploymentName',
- );
- filteredColumns.unshift(deploymentGroupColumnConfig);
- return filteredColumns as ColumnType<K8sDeploymentsRowData>[];
- }
-
- return columnsConfig as ColumnType<K8sDeploymentsRowData>[];
-};
-
-const dotToUnder: Record<string, keyof K8sDeploymentsData['meta']> = {
- 'k8s.deployment.name': 'k8s_deployment_name',
- 'k8s.namespace.name': 'k8s_namespace_name',
- 'k8s.cluster.name': 'k8s_cluster_name',
-};
-
-const getGroupByEle = (
- deployment: K8sDeploymentsData,
- groupBy: IBuilderQuery['groupBy'],
-): React.ReactNode => {
- const groupByValues: string[] = [];
-
- groupBy.forEach((group) => {
- const rawKey = group.key as string;
-
- // Choose mapped key if present, otherwise use rawKey
- const metaKey = (dotToUnder[rawKey] ??
- rawKey) as keyof typeof deployment.meta;
- const value = deployment.meta[metaKey];
-
- groupByValues.push(value);
- });
-
- return (
- <div className="pod-group">
- {groupByValues.map((value) => (
- <Tag key={value} color={Color.BG_SLATE_400} className="pod-group-tag-item">
- {value === '' ? '<no-value>' : value}
- </Tag>
- ))}
- </div>
- );
-};
-
-export const formatDataForTable = (
- data: K8sDeploymentsData[],
- groupBy: IBuilderQuery['groupBy'],
-): K8sDeploymentsRowData[] =>
- data.map((deployment, index) => ({
- key: index.toString(),
- deploymentUID: deployment.meta.k8s_deployment_name,
- deploymentName: (
- <Tooltip title={deployment.meta.k8s_deployment_name}>
- {deployment.meta.k8s_deployment_name}
- </Tooltip>
- ),
- available_pods: (
- <ValidateColumnValueWrapper value={deployment.availablePods}>
- {deployment.availablePods}
- </ValidateColumnValueWrapper>
- ),
- desired_pods: (
- <ValidateColumnValueWrapper value={deployment.desiredPods}>
- {deployment.desiredPods}
- </ValidateColumnValueWrapper>
- ),
- restarts: (
- <ValidateColumnValueWrapper value={deployment.restarts}>
- {deployment.restarts}
- </ValidateColumnValueWrapper>
- ),
- cpu: (
- <ValidateColumnValueWrapper value={deployment.cpuUsage}>
- {deployment.cpuUsage}
- </ValidateColumnValueWrapper>
- ),
- cpu_request: (
- <ValidateColumnValueWrapper value={deployment.cpuRequest}>
- <div className="progress-container">
- <EntityProgressBar value={deployment.cpuRequest} type="request" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- cpu_limit: (
- <ValidateColumnValueWrapper value={deployment.cpuLimit}>
- <div className="progress-container">
- <EntityProgressBar value={deployment.cpuLimit} type="limit" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- memory: (
- <ValidateColumnValueWrapper value={deployment.memoryUsage}>
- {formatBytes(deployment.memoryUsage)}
- </ValidateColumnValueWrapper>
- ),
- memory_request: (
- <ValidateColumnValueWrapper value={deployment.memoryRequest}>
- <div className="progress-container">
- <EntityProgressBar value={deployment.memoryRequest} type="request" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- memory_limit: (
- <ValidateColumnValueWrapper value={deployment.memoryLimit}>
- <div className="progress-container">
- <EntityProgressBar value={deployment.memoryLimit} type="limit" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- clusterName: deployment.meta.k8s_cluster_name,
- namespaceName: deployment.meta.k8s_namespace_name,
- deploymentGroup: getGroupByEle(deployment, groupBy),
- meta: deployment.meta,
- ...deployment.meta,
- groupedByMeta: deployment.meta,
- }));
diff --git a/frontend/src/components/HostMetricsDetail/Containers/Containers.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityContainers.tsx
similarity index 81%
rename from frontend/src/components/HostMetricsDetail/Containers/Containers.tsx
rename to frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityContainers.tsx
index 17dac73475..e577c6aaf4 100644
--- a/frontend/src/components/HostMetricsDetail/Containers/Containers.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityContainers.tsx
@@ -1,16 +1,15 @@
import { useTranslation } from 'react-i18next';
import { Space, Typography } from 'antd';
+import WaitlistFragment from 'components/HostMetricsDetail/WaitlistFragment/WaitlistFragment';
import broomUrl from '@/assets/Icons/broom.svg';
import infraContainersUrl from '@/assets/Icons/infraContainers.svg';
-import WaitlistFragment from '../WaitlistFragment/WaitlistFragment';
-
-import './Containers.styles.scss';
+import 'components/HostMetricsDetail/Containers/Containers.styles.scss';
const { Text } = Typography;
-function Containers(): JSX.Element {
+function EntityContainers(): JSX.Element {
const { t } = useTranslation(['infraMonitoring']);
return (
@@ -44,4 +43,4 @@ function Containers(): JSX.Element {
);
}
-export default Containers;
+export default EntityContainers;
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents/EntityEvents.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents/EntityEvents.tsx
index 66657ac89f..dffadb1de1 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents/EntityEvents.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents/EntityEvents.tsx
@@ -2,10 +2,10 @@ import { useEffect, useMemo, useState } from 'react';
import { useQuery } from 'react-query';
import { Color } from '@signozhq/design-tokens';
import { Button, Table, TableColumnsType } from 'antd';
-import { VIEWS } from 'components/HostMetricsDetail/constants';
import { DEFAULT_ENTITY_VERSION } from 'constants/app';
import { EventContents } from 'container/InfraMonitoringK8s/commonUtils';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
+import { VIEWS } from 'container/InfraMonitoringK8s/constants';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
import LoadingContainer from 'container/InfraMonitoringK8s/LoadingContainer';
import { INITIAL_PAGE_SIZE } from 'container/LogsContextList/configs';
import LogsError from 'container/LogsError/LogsError';
@@ -67,7 +67,7 @@ interface IEntityEventsProps {
dateTimeRange?: [number, number],
) => void;
selectedInterval: Time;
- category: K8sCategory;
+ category: InfraMonitoringEntity;
queryKey: string;
}
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents/__tests__/EntityEvents.test.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents/__tests__/EntityEvents.test.tsx
index cdc8c67fae..ccc793c7aa 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents/__tests__/EntityEvents.test.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents/__tests__/EntityEvents.test.tsx
@@ -1,7 +1,7 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { initialQueriesMap } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
import { Time } from 'container/TopNav/DateTimeSelectionV2/types';
import * as useQueryBuilderHooks from 'hooks/queryBuilder/useQueryBuilder';
import * as appContextHooks from 'providers/App/App';
@@ -106,7 +106,7 @@ const mockFilters: IBuilderQuery['filters'] = {
const isModalTimeSelection = false;
const mockHandleTimeChange = jest.fn();
const selectedInterval: Time = '1m';
-const category = K8sCategory.PODS;
+const category = InfraMonitoringEntity.PODS;
const queryKey = 'pod-events';
const mockEventsData = {
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogs.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogs.tsx
index dd15ca113b..8a1ca6865b 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogs.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogs.tsx
@@ -6,7 +6,7 @@ import LogDetail from 'components/LogDetail';
import RawLogView from 'components/Logs/RawLogView';
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
import { DEFAULT_ENTITY_VERSION } from 'constants/app';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
import LogsError from 'container/LogsError/LogsError';
import { LogsLoading } from 'container/LogsLoading/LogsLoading';
import { FontSize } from 'container/OptionsMenu/types';
@@ -31,7 +31,7 @@ interface Props {
};
filters: IBuilderQuery['filters'];
queryKey: string;
- category: K8sCategory;
+ category: InfraMonitoringEntity;
queryKeyFilters: Array<string>;
}
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogsDetailedView.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogsDetailedView.tsx
index 63a4aefea1..f7fa6bff04 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogsDetailedView.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogsDetailedView.tsx
@@ -1,6 +1,6 @@
import { useMemo } from 'react';
-import { VIEWS } from 'components/HostMetricsDetail/constants';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
+import { VIEWS } from 'container/InfraMonitoringK8s/constants';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
import QueryBuilderSearch from 'container/QueryBuilder/filters/QueryBuilderSearch';
import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
import {
@@ -30,7 +30,7 @@ interface Props {
logFilters: IBuilderQuery['filters'];
selectedInterval: Time;
queryKey: string;
- category: K8sCategory;
+ category: InfraMonitoringEntity;
queryKeyFilters: Array<string>;
}
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/__tests__/EntityLogs.test.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/__tests__/EntityLogs.test.tsx
index 619090465f..7ae169add6 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/__tests__/EntityLogs.test.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/__tests__/EntityLogs.test.tsx
@@ -1,6 +1,6 @@
import { VirtuosoMockContext } from 'react-virtuoso';
import { ENVIRONMENT } from 'constants/env';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
import { verifyFiltersAndOrderBy } from 'container/LogsExplorerViews/tests/LogsExplorerPagination.test';
import { logsPaginationQueryRangeSuccessResponse } from 'mocks-server/__mockdata__/logs_query_range';
import { server } from 'mocks-server/server';
@@ -94,7 +94,7 @@ describe('EntityLogs', () => {
timeRange={{ startTime: 1, endTime: 2 }}
filters={{ items: [], op: 'AND' }}
queryKey="test"
- category={K8sCategory.PODS}
+ category={InfraMonitoringEntity.PODS}
queryKeyFilters={[]}
/>
</VirtuosoMockContext.Provider>,
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityMetrics/EntityMetrics.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityMetrics/EntityMetrics.tsx
index 23acfb3cff..9cf67024aa 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityMetrics/EntityMetrics.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityMetrics/EntityMetrics.tsx
@@ -9,7 +9,7 @@ import {
getMetricsTableData,
MetricsTable,
} from 'container/InfraMonitoringK8s/commonUtils';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
import {
CustomTimeType,
@@ -57,7 +57,7 @@ interface EntityMetricsProps<T> {
dotMetricsEnabled: boolean,
) => GetQueryResultsProps[];
queryKey: string;
- category: K8sCategory;
+ category: InfraMonitoringEntity;
}
function EntityMetrics<T>({
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityMetrics/__tests__/EntityMetrics.test.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityMetrics/__tests__/EntityMetrics.test.tsx
index 06dc8e7081..0cdafcf380 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityMetrics/__tests__/EntityMetrics.test.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityMetrics/__tests__/EntityMetrics.test.tsx
@@ -1,5 +1,5 @@
import { render, screen } from '@testing-library/react';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
import { Time } from 'container/TopNav/DateTimeSelectionV2/types';
import * as appContextHooks from 'providers/App/App';
import { LicenseEvent } from 'types/api/licensesV3/getActive';
@@ -280,7 +280,7 @@ const renderEntityMetrics = (overrides = {}): any => {
entityWidgetInfo: mockEntityWidgetInfo,
getEntityQueryPayload: mockGetEntityQueryPayload,
queryKey: 'test-query-key',
- category: K8sCategory.PODS,
+ category: InfraMonitoringEntity.PODS,
...overrides,
};
diff --git a/frontend/src/components/HostMetricsDetail/Processes/Processes.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityProcesses.tsx
similarity index 81%
rename from frontend/src/components/HostMetricsDetail/Processes/Processes.tsx
rename to frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityProcesses.tsx
index a3f4abdd3b..17ddfa5f7e 100644
--- a/frontend/src/components/HostMetricsDetail/Processes/Processes.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityProcesses.tsx
@@ -1,16 +1,15 @@
import { useTranslation } from 'react-i18next';
import { Space, Typography } from 'antd';
+import WaitlistFragment from 'components/HostMetricsDetail/WaitlistFragment/WaitlistFragment';
import broomUrl from '@/assets/Icons/broom.svg';
import infraContainersUrl from '@/assets/Icons/infraContainers.svg';
-import WaitlistFragment from '../WaitlistFragment/WaitlistFragment';
-
-import './Processes.styles.scss';
+import 'components/HostMetricsDetail/Processes/Processes.styles.scss';
const { Text } = Typography;
-function Processes(): JSX.Element {
+function EntityProcesses(): JSX.Element {
const { t } = useTranslation(['infraMonitoring']);
return (
@@ -43,4 +42,4 @@ function Processes(): JSX.Element {
);
}
-export default Processes;
+export default EntityProcesses;
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityTraces/EntityTraces.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityTraces/EntityTraces.tsx
index a6eedc5ad2..5c300b543b 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityTraces/EntityTraces.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityTraces/EntityTraces.tsx
@@ -1,13 +1,12 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useQuery } from 'react-query';
import logEvent from 'api/common/logEvent';
-import { VIEWS } from 'components/HostMetricsDetail/constants';
-import { getListColumns } from 'components/HostMetricsDetail/HostMetricTraces/utils';
import { ResizeTable } from 'components/ResizeTable';
import { DEFAULT_ENTITY_VERSION } from 'constants/app';
import { InfraMonitoringEvents } from 'constants/events';
import { QueryParams } from 'constants/query';
import EmptyLogsSearch from 'container/EmptyLogsSearch/EmptyLogsSearch';
+import { VIEWS } from 'container/InfraMonitoringK8s/constants';
import NoLogs from 'container/NoLogs/NoLogs';
import QueryBuilderSearch from 'container/QueryBuilder/filters/QueryBuilderSearch';
import { ErrorText } from 'container/TimeSeriesView/styles';
@@ -31,6 +30,7 @@ import {
getEntityTracesQueryPayload,
selectedEntityTracesColumns,
} from '../utils';
+import { getTraceListColumns } from './traceListColumns';
import './entityTraces.styles.scss';
@@ -134,7 +134,7 @@ function EntityTraces({
enabled: !!queryPayload,
});
- const traceListColumns = getListColumns(selectedEntityTracesColumns);
+ const traceListColumns = getTraceListColumns(selectedEntityTracesColumns);
useEffect(() => {
if (data?.payload?.data?.newResult?.data?.result) {
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityTraces/__tests__/EntityTraces.test.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityTraces/__tests__/EntityTraces.test.tsx
index ca04d5eadf..c5ec494c61 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityTraces/__tests__/EntityTraces.test.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityTraces/__tests__/EntityTraces.test.tsx
@@ -1,6 +1,6 @@
import { render, screen } from '@testing-library/react';
import { initialQueriesMap } from 'constants/queryBuilder';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
import { Time } from 'container/TopNav/DateTimeSelectionV2/types';
import * as useQueryBuilderHooks from 'hooks/queryBuilder/useQueryBuilder';
import * as appContextHooks from 'providers/App/App';
@@ -112,7 +112,7 @@ const mockTracesFilters: IBuilderQuery['filters'] = {
const isModalTimeSelection = false;
const mockHandleTimeChange = jest.fn();
const selectedInterval: Time = '5m';
-const category = K8sCategory.PODS;
+const category = InfraMonitoringEntity.PODS;
const queryKey = 'pod-traces';
const queryKeyFilters = ['service.name'];
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricTraces/utils.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityTraces/traceListColumns.tsx
similarity index 98%
rename from frontend/src/components/HostMetricsDetail/HostMetricTraces/utils.tsx
rename to frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityTraces/traceListColumns.tsx
index cfa651602b..3a54eefde4 100644
--- a/frontend/src/components/HostMetricsDetail/HostMetricTraces/utils.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityTraces/traceListColumns.tsx
@@ -18,7 +18,7 @@ const keyToLabelMap: Record<string, string> = {
responseStatusCode: 'Status Code',
};
-export const getListColumns = (
+export const getTraceListColumns = (
selectedColumns: BaseAutocompleteData[],
): ColumnsType<RowData> => {
const columns: ColumnsType<RowData> =
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/utils.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/utils.tsx
index 15fb18c5eb..b73beb491f 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/utils.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/utils.tsx
@@ -16,7 +16,7 @@ import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { nanoToMilli } from 'utils/timeUtils';
import { v4 as uuidv4 } from 'uuid';
-import { K8sCategory } from '../constants';
+import { InfraMonitoringEntity } from '../constants';
export const QUERY_KEYS = {
K8S_OBJECT_KIND: 'k8s.object.kind',
@@ -29,6 +29,7 @@ export const QUERY_KEYS = {
K8S_STATEFUL_SET_NAME: 'k8s.statefulset.name',
K8S_JOB_NAME: 'k8s.job.name',
K8S_DAEMON_SET_NAME: 'k8s.daemonset.name',
+ K8S_PERSISTENT_VOLUME_CLAIM_NAME: 'k8s.persistentvolumeclaim.name',
};
/**
@@ -96,7 +97,7 @@ export function EntityDetailsEmptyContainer({
category,
}: {
view: 'logs' | 'traces' | 'events';
- category: K8sCategory;
+ category: InfraMonitoringEntity;
}): React.ReactElement {
const label = category.slice(0, category.length);
diff --git a/frontend/src/container/InfraMonitoringK8s/InfraMonitoringK8s.module.scss b/frontend/src/container/InfraMonitoringK8s/InfraMonitoringK8s.module.scss
new file mode 100644
index 0000000000..3b64cb3e04
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/InfraMonitoringK8s.module.scss
@@ -0,0 +1,162 @@
+.infraMonitoringContainer {
+ display: flex;
+ height: 100%;
+ flex-direction: column;
+}
+
+.infraContentRow {
+ display: flex;
+ flex-direction: row;
+ height: calc(100vh - 45px);
+ width: 100%;
+ position: relative;
+ overflow-y: auto;
+
+ :global(.periscope-btn) {
+ &.ghost:not(:disabled) {
+ border: none;
+ background: transparent;
+
+ &:hover {
+ background: transparent;
+ color: var(--bg-robin-500) !important;
+ font-weight: 500;
+ }
+ }
+ }
+
+ &::-webkit-scrollbar {
+ width: 0.1rem;
+ height: 0.1rem;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: var(--accent-primary);
+ }
+
+ &::-webkit-scrollbar-thumb:hover {
+ background: colox-mix(var(--accent-primary), var(--bg-vanilla-100), 20%);
+ }
+}
+
+.quickFiltersContainer {
+ width: 280px;
+ min-width: 280px;
+ border-right: 1px solid var(--l1-border);
+ overflow-y: auto;
+
+ &::-webkit-scrollbar {
+ width: 0.1rem;
+ height: 0.1rem;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: var(--accent-primary);
+ }
+
+ &::-webkit-scrollbar-thumb:hover {
+ background: colox-mix(var(--accent-primary), var(--bg-vanilla-100), 20%);
+ }
+
+ :global(.ant-collapse-header) {
+ border-bottom: 1px solid var(--l1-border);
+ padding: 12px 8px;
+ }
+
+ :global(.ant-collapse-content-box) {
+ padding: 0 !important;
+ padding-block: 0 !important;
+
+ :global(.quick-filters .checkbox-filter) {
+ padding-left: 18px;
+ }
+ }
+
+ :global(.quick-filters) {
+ overflow-y: auto;
+ overflow-x: hidden;
+
+ &::-webkit-scrollbar {
+ width: 0.1rem;
+ height: 0.1rem;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: var(--accent-primary);
+ }
+
+ &::-webkit-scrollbar-thumb:hover {
+ background: colox-mix(var(--accent-primary), var(--bg-vanilla-100), 20%);
+ }
+ }
+}
+
+.quickFiltersContainerHeader {
+ padding: 8px;
+ border-bottom: 1px solid var(--l1-border);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+
+.quickFiltersCategoryLabel {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+}
+
+.quickFiltersCategoryLabelIcon {
+ margin-right: 8px;
+}
+
+.quickFiltersCategoryLabelContainer {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+}
+
+.listContainer {
+ flex: 1;
+ min-width: 0;
+ max-width: 100%;
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+
+ > * {
+ min-width: 0;
+ max-width: 100%;
+ box-sizing: border-box;
+ }
+
+ > :global(.ant-table-wrapper) {
+ width: 100%;
+ max-width: 100%;
+
+ :global(.ant-spin-container) {
+ display: flex !important;
+ flex-direction: column;
+ }
+
+ :global(.ant-table),
+ :global(.ant-table-container) {
+ max-width: 100%;
+ }
+ }
+}
+
+.listContainerFiltersVisible {
+ max-width: calc(100% - 280px);
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/InfraMonitoringK8s.styles.scss b/frontend/src/container/InfraMonitoringK8s/InfraMonitoringK8s.styles.scss
deleted file mode 100644
index cf26913e69..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/InfraMonitoringK8s.styles.scss
+++ /dev/null
@@ -1,892 +0,0 @@
-.k8s-container {
- display: flex;
- flex-direction: row;
- height: calc(100vh - 45px);
- width: 100%;
-
- .k8s-quick-filters-container {
- width: 280px;
- min-width: 280px;
- border-right: 1px solid var(--l1-border);
- overflow-y: auto;
-
- .k8s-quick-filters-container-header {
- padding: 8px;
- border-bottom: 1px solid var(--l1-border);
-
- display: flex;
- align-items: center;
- justify-content: space-between;
- }
-
- &::-webkit-scrollbar {
- width: 0.1rem;
- height: 0.1rem;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background: var(--l2-background);
- }
-
- &::-webkit-scrollbar-thumb:hover {
- background: var(--l3-background);
- }
-
- .ant-collapse-header {
- border-bottom: 1px solid var(--l1-border);
- padding: 12px 8px;
- }
-
- .ant-collapse-content-box {
- padding: 0px;
- padding-block: 0px !important;
-
- .quick-filters {
- .checkbox-filter {
- padding-left: 18px;
- }
- }
- }
-
- .quick-filters {
- overflow-y: auto;
- overflow-x: hidden;
-
- &::-webkit-scrollbar {
- width: 0.1rem;
- height: 0.1rem;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background: var(--l3-background);
- }
-
- &::-webkit-scrollbar-thumb:hover {
- background: var(--l3-background);
- }
- }
-
- .k8s-quick-filters-category-label {
- display: flex;
- align-items: center;
- gap: 4px;
-
- .k8s-quick-filters-category-label-icon {
- margin-right: 8px;
- }
-
- .k8s-quick-filters-category-label-container {
- display: flex;
- align-items: center;
- gap: 4px;
- }
- }
- }
-
- .k8s-list-container {
- flex: 1;
-
- max-width: 100%;
-
- &.k8s-list-container-filters-visible {
- max-width: calc(100% - 280px);
- }
- }
-
- .periscope-btn {
- &.ghost:not(:disabled) {
- border: none;
- background: transparent;
-
- &:hover {
- background: transparent;
- color: var(--accent-primary) !important;
- font-weight: 500;
- }
- }
- }
-
- .column-header {
- display: flex;
- align-items: center;
- gap: 16px;
- font-size: 11px;
-
- &.pod-group-header {
- padding-left: 12px;
- }
- }
-}
-
-.infra-monitoring-container {
- display: flex;
- height: 100%;
- flex-direction: column;
-
- .infra-monitoring-header {
- display: flex;
- justify-content: space-between;
- width: 100%;
- margin-bottom: 16px;
- }
-
- .k8s-list {
- .column {
- min-width: 180px;
- max-width: 180px;
-
- font-size: 12px !important;
- }
-
- .column-pod-name {
- min-width: 200px;
- max-width: 200px;
- }
-
- .column-pod-group {
- min-width: 200px;
- max-width: 200px;
- }
-
- .column-progress-bar {
- min-width: 180px;
- max-width: 180px;
- }
-
- .column-dummy {
- min-width: 32px;
- max-width: 32px;
- }
-
- .pod-group {
- display: flex;
- align-items: center;
- gap: 4px;
- flex-wrap: wrap;
-
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- .pod-group-tag-item {
- border-radius: 2px;
- font-size: 12px;
- font-weight: 400;
- background: var(--l1-border);
- color: var(--l2-foreground);
-
- max-width: 100%;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- .pod-name {
- width: 100%;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- .ant-table-container {
- .ant-table-row-expand-icon-cell {
- padding: 0px;
- }
-
- .ant-table-content {
- &::-webkit-scrollbar {
- width: 0.1rem;
- height: 0.1rem;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background: var(--primary-background);
- }
-
- &::-webkit-scrollbar-thumb:hover {
- background: var(--bg-robin-400);
- }
- }
- }
- }
-
- .k8s-list-controls {
- padding: 8px;
-
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: 8px;
-
- .ant-select-selector {
- border-radius: 2px;
- border: 1px solid var(--l1-border) !important;
- background-color: var(--l3-background) !important;
-
- input {
- font-size: 12px;
- }
-
- .ant-tag .ant-typography {
- font-size: 12px;
- }
- }
-
- .k8s-list-controls-left {
- flex: 1;
- display: flex;
- align-items: center;
- flex-wrap: wrap;
- gap: 8px;
-
- .k8s-qb-search-container {
- flex: 1;
- min-width: 240px;
- max-width: 60%;
- }
-
- .k8s-attribute-search-container {
- flex: 1;
- min-width: 240px;
- max-width: 40%;
- display: flex;
- align-items: center;
-
- .group-by-label {
- min-width: max-content;
- font-size: 13px;
- font-style: normal;
- font-weight: 400;
- line-height: 18px; /* 128.571% */
- letter-spacing: -0.07px;
-
- border-radius: 2px 0px 0px 2px;
- border: 1px solid var(--l1-border);
- border-right: none;
- border-top-right-radius: 0px;
- border-bottom-right-radius: 0px;
-
- display: flex;
- height: 32px;
- padding: 6px 6px 6px 8px;
- justify-content: center;
- align-items: center;
- gap: 4px;
- }
-
- .group-by-select {
- .ant-select-selector {
- border-left: none;
- border-top-left-radius: 0px;
- border-bottom-left-radius: 0px;
- }
- }
- }
- }
-
- .k8s-list-controls-right {
- min-width: 240px;
-
- display: flex;
- align-items: center;
- gap: 4px;
- }
-
- .periscope-btn {
- padding: 4px 8px;
-
- &.ghost:not(:disabled) {
- border: none;
- background: transparent;
- }
- }
- }
-
- .progress-container {
- display: flex;
- align-items: center;
- justify-content: center;
- }
-
- .entity-progress-bar {
- display: flex;
- align-items: center;
- }
-
- .progress-bar {
- flex: 1;
- margin-right: 8px;
- margin-bottom: 0px;
- min-width: 100px;
- }
-
- .clickable-row {
- cursor: pointer;
- }
-
- .k8s-list-table {
- .ant-table {
- .ant-table-thead > tr > th {
- padding: 12px;
- font-weight: 500;
- font-size: 12px;
- line-height: 18px;
-
- background: var(--l1-background);
- border-bottom: none;
-
- color: var(--muted-foreground);
- font-family: Inter;
- font-size: 11px;
- font-style: normal;
- font-weight: 600;
- line-height: 18px; /* 163.636% */
- letter-spacing: 0.44px;
- text-transform: uppercase;
-
- &::before {
- background-color: transparent;
- }
- }
-
- .ant-table-thead > tr > th:has(.hostname-column-header) {
- background: var(--l2-background);
- }
-
- .ant-table-cell {
- padding: 12px;
- font-size: 13px;
- line-height: 20px;
- color: var(--l1-foreground);
- background: var(--l1-background);
- border-bottom: none;
- }
-
- .ant-table-cell:has(.hostname-column-value) {
- background: var(--l2-background);
- }
-
- .hostname-column-value {
- color: var(--l1-foreground);
- font-family: 'Geist Mono';
- font-style: normal;
- font-weight: 600;
- line-height: 20px; /* 142.857% */
- letter-spacing: -0.07px;
- }
-
- .status-cell {
- .active-tag {
- color: var(--bg-forest-500);
- padding: 4px 8px;
- border-radius: 4px;
- font-size: 12px;
- font-weight: 500;
- }
- }
-
- .progress-container {
- .ant-progress-bg {
- height: 8px !important;
- border-radius: 4px;
- }
- }
-
- .ant-table-tbody > tr:hover > td {
- background: color-mix(in srgb, var(--l1-foreground) 4%, transparent);
- }
-
- .ant-table-cell:first-child {
- text-align: justify;
- }
-
- .ant-table-cell:nth-child(2) {
- padding-left: 16px;
- padding-right: 16px;
- }
-
- .ant-table-cell:nth-child(n + 3) {
- padding-right: 24px;
- }
- .column-header-right {
- text-align: right;
- }
- .ant-table-tbody > tr > td {
- border-bottom: none;
- }
-
- .ant-table-thead
- > tr
- > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not([colspan])::before {
- background-color: transparent;
- }
-
- .ant-empty-normal {
- visibility: hidden;
- }
- }
-
- .ant-pagination {
- position: fixed;
- bottom: 0;
- width: calc(100% - 54px);
- background: var(--l1-background);
- padding: 16px;
- margin: 0;
-
- // this is to offset chat support icon till we improve the design
- padding-right: 72px;
-
- .ant-pagination-item {
- border-radius: 4px;
-
- &-active {
- background: var(--primary-background);
- border-color: var(--bg-robin-500);
-
- a {
- color: var(--l1-foreground) !important;
- }
- }
- }
- }
-
- .ant-table-expanded-row {
- &:hover {
- background: var(--l1-background);
- }
-
- .ant-table-cell {
- background: var(--l1-background) !important;
- }
-
- .ant-table .ant-table-thead > tr > th {
- padding: 4px 16px !important;
- }
- }
-
- .expanded-table-container {
- border: 1px solid var(--l2-background);
- overflow-x: auto;
- padding-left: 48px;
-
- &::-webkit-scrollbar {
- width: 0.1rem;
- height: 0.1rem;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background: var(--l2-background);
- }
-
- &::-webkit-scrollbar-thumb:hover {
- background: var(--l3-background);
- }
-
- .ant-table-expanded-row {
- background: var(--l1-background);
-
- &:hover {
- background: var(--l1-background);
- }
-
- .ant-table-cell {
- background: var(--l1-background);
- }
- }
-
- .expanded-table-footer {
- display: flex;
- justify-content: flex-start;
- gap: 8px;
- padding: 8px;
- padding-left: 42px;
- margin-top: 8px;
-
- .periscope-btn {
- font-size: 10px;
-
- display: flex;
- align-items: center;
- gap: 4px;
- }
-
- .view-all-text {
- font-size: 10px;
- color: var(--l2-foreground);
- }
- }
- }
- }
-
- .k8s-list-container-filters-visible {
- .k8s-list-table {
- .ant-pagination {
- width: calc(100% - 340px);
- }
- }
- }
-}
-
-.infra-monitoring-tags {
- width: fit-content;
-
- font-family: Inter;
- font-size: 11px;
- font-style: normal;
- font-weight: 500;
- line-height: 18px; /* 163.636% */
- letter-spacing: 0.44px;
- text-transform: uppercase;
-
- border-radius: 50px;
- padding: 2px 8px;
-
- &.active {
- color: var(--bg-forest-500);
- border: 1px solid color-mix(in srgb, var(--bg-forest-500) 20%, transparent);
- background: color-mix(in srgb, var(--bg-forest-500) 10%, transparent);
- }
-
- &.inactive {
- color: var(--l3-foreground);
- border: 1px solid color-mix(in srgb, var(--bg-slate-50) 20%, transparent);
- background: color-mix(in srgb, var(--bg-slate-50) 10%, transparent);
- }
-}
-
-.k8s-list-loading-state {
- padding: 8px;
- display: flex;
- flex-direction: column;
- gap: 2px;
-
- .k8s-list-loading-state-item {
- height: 48px;
- width: 100%;
- }
-}
-
-.no-filtered-hosts-message-container {
- height: 30vh;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
-
- .no-filtered-hosts-message-content {
- display: flex;
- flex-direction: column;
- align-items: flex-start;
- justify-content: center;
-
- width: fit-content;
- padding: 24px;
- }
-
- .no-filtered-hosts-message {
- margin-top: 8px;
- }
-}
-
-.hosts-empty-state-container {
- padding: 16px;
- height: 40vh;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
-
- .hosts-empty-state-container-content {
- padding: 16px;
- display: flex;
- flex-direction: column;
- align-items: flex-start;
- justify-content: center;
-
- width: fit-content;
-
- .no-hosts-message {
- margin-bottom: 16px;
-
- .no-hosts-message-title {
- margin-top: 8px;
- margin-bottom: 4px;
- }
- }
- }
-}
-
-.lightMode {
- .infra-monitoring-container {
- .ant-table-thead > tr > th {
- background: var(--l1-background);
- color: var(--l1-foreground);
- }
-
- .ant-table-cell {
- color: var(--l1-foreground);
- }
- .k8s-list-controls {
- border-top: 1px solid var(--l1-border);
- border-bottom: 1px solid var(--l1-border);
-
- .ant-select-selector {
- border-color: var(--l1-border) !important;
- background-color: var(--l1-background) !important;
- color: var(--l2-foreground);
- }
- }
- }
-
- .k8s-list-table {
- .ant-table {
- .ant-table-thead > tr > th {
- background: var(--l1-background);
- color: var(--l2-foreground);
- }
-
- .ant-table-thead > tr > th:has(.hostname-column-header) {
- background: var(--l1-background);
- }
-
- .ant-table-cell {
- background: var(--l1-background);
- color: var(--l1-foreground);
- }
-
- .ant-table-cell:has(.hostname-column-value) {
- background: var(--l1-background);
- }
-
- .hostname-column-value {
- color: var(--l1-foreground);
- }
-
- .ant-table-tbody > tr:hover > td {
- background: rgba(0, 0, 0, 0.04);
- }
- }
-
- .ant-pagination {
- background: var(--l1-background);
-
- .ant-pagination-item {
- &-active {
- background: var(--primary-background);
- border-color: var(--bg-robin-500);
-
- a {
- color: var(--l1-background) !important;
- }
- }
- }
- }
- }
-}
-
-.infra-monitoring-container {
- .ant-table-cell {
- min-width: 140px !important;
- max-width: 140px !important;
- }
-
- .ant-table-cell {
- &:has(.pod-name-header) {
- min-width: 250px !important;
- max-width: 250px !important;
- }
- }
-
- .ant-table-cell {
- &:has(.med-col) {
- min-width: 180px !important;
- max-width: 180px !important;
- }
- }
-
- .expanded-k8s-list-table {
- .ant-table-cell {
- min-width: 180px !important;
- max-width: 180px !important;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
-}
-
-.event-content-container {
- .ant-table {
- background: var(--l2-background);
-
- .ant-table-row:hover {
- .ant-table-cell {
- .value-field {
- .action-btn {
- display: flex;
- position: absolute;
- top: 50%;
- right: 16px;
- transform: translateY(-50%);
- gap: 4px;
- }
- }
- }
- }
-
- .ant-table-cell {
- border: 1px solid var(--l1-border);
- }
-
- .attribute-name {
- .ant-btn {
- &:hover {
- background-color: none !important;
- }
- }
- }
-
- .attribute-pin {
- cursor: pointer;
-
- padding: 0;
- vertical-align: middle;
- text-align: center;
-
- .log-attribute-pin {
- padding: 8px;
-
- display: flex;
- justify-content: center;
- align-items: center;
-
- .pin-attribute-icon {
- border: none;
-
- &.pinned svg {
- fill: var(--accent-primary);
- }
- }
- }
- }
-
- .value-field-container {
- background: color-mix(in srgb, var(--l1-border) 40%, transparent);
-
- .value-field {
- font-family: 'Geist Mono';
-
- position: relative;
- }
-
- .action-btn {
- display: none;
- width: max-content;
- position: absolute;
- // padding: 0 16px;
- right: 0;
-
- .filter-btn {
- display: flex;
- align-items: center;
- border: none;
- box-shadow: none;
- border-radius: 2px;
- background: var(--l1-border);
- padding: 2px 3px;
- gap: 3px;
- height: 18px;
- width: 20px;
- }
- }
- }
- }
-}
-
-.lightMode {
- .infra-monitoring-container {
- .k8s-list-table {
- .ant-table-expanded-row {
- &:hover {
- background: var(--l1-background) !important;
- }
-
- .ant-table-cell {
- background: var(--l1-background) !important;
- }
-
- .ant-table .ant-table-thead > tr > th {
- padding: 4px 16px !important;
- }
- }
- }
- }
-
- .event-content-container {
- .ant-table {
- background: var(--l1-background);
- }
-
- .ant-table-cell {
- border: 1px solid var(--l1-border);
- }
-
- .value-field-container {
- background: var(--l3-background);
-
- &.attribute-pin {
- background: var(--l1-background);
- }
-
- .action-btn {
- .filter-btn {
- background: var(--l3-background);
- }
- }
- }
- }
-
- .entity-group-header {
- .ant-tag {
- background-color: var(--l3-background) !important;
- color: var(--muted-foreground) !important;
- }
- }
-}
-
-.entity-group-header {
- width: 300px !important;
-}
-
-.ant-table-content {
- margin-bottom: 60px !important;
-}
-
-.expanded-clickable-row {
- cursor: pointer;
-}
diff --git a/frontend/src/container/InfraMonitoringK8s/InfraMonitoringK8s.tsx b/frontend/src/container/InfraMonitoringK8s/InfraMonitoringK8s.tsx
index a08c0a4877..a0e8636dd7 100644
--- a/frontend/src/container/InfraMonitoringK8s/InfraMonitoringK8s.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/InfraMonitoringK8s.tsx
@@ -1,7 +1,7 @@
-import { useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { VerticalAlignTopOutlined } from '@ant-design/icons';
import * as Sentry from '@sentry/react';
-import type { CollapseProps } from 'antd';
+import { Button, CollapseProps } from 'antd';
import { Collapse, Tooltip, Typography } from 'antd';
import logEvent from 'api/common/logEvent';
import QuickFilters from 'components/QuickFilters/QuickFilters';
@@ -16,6 +16,7 @@ import {
Computer,
Container,
FilePenLine,
+ Filter,
Group,
HardDrive,
Workflow,
@@ -53,23 +54,21 @@ import K8sPodLists from './Pods/K8sPodLists';
import K8sStatefulSetsList from './StatefulSets/K8sStatefulSetsList';
import K8sVolumesList from './Volumes/K8sVolumesList';
-import './InfraMonitoringK8s.styles.scss';
+import styles from './InfraMonitoringK8s.module.scss';
export default function InfraMonitoringK8s(): JSX.Element {
const [showFilters, setShowFilters] = useState(true);
const [selectedCategory, setSelectedCategory] = useInfraMonitoringCategory();
- const [, setFilters] = useInfraMonitoringFilters();
+ const [urlFilters, setUrlFilters] = useInfraMonitoringFilters();
const [, setGroupBy] = useInfraMonitoringGroupBy();
const [, setOrderBy] = useInfraMonitoringOrderBy();
- const [quickFiltersLastUpdated, setQuickFiltersLastUpdated] = useState(-1);
-
const { currentQuery } = useQueryBuilder();
- const handleFilterVisibilityChange = (): void => {
- setShowFilters(!showFilters);
- };
+ const handleFilterVisibilityChange = useCallback((): void => {
+ setShowFilters((show) => !show);
+ }, []);
const { handleChangeQueryData } = useQueryOperations({
index: 0,
@@ -77,6 +76,22 @@ export default function InfraMonitoringK8s(): JSX.Element {
entityVersion: '',
});
+ // Track previous urlFilters to only sync when the value actually changes
+ // (not when handleChangeQueryData changes due to query updates)
+ const prevUrlFiltersRef = useRef<string | null>(null);
+
+ useEffect(() => {
+ const currentFiltersJson = urlFilters ? JSON.stringify(urlFilters) : null;
+
+ // Only sync if urlFilters value has actually changed
+ if (prevUrlFiltersRef.current !== currentFiltersJson) {
+ prevUrlFiltersRef.current = currentFiltersJson;
+ // Sync filters to query builder, using empty filter when urlFilters is null
+ handleChangeQueryData('filters', urlFilters || { items: [], op: 'and' });
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [urlFilters]); // handleChangeQueryData intentionally omitted - we call the current version but don't re-run when it changes
+
const { featureFlags } = useAppContext();
const dotMetricsEnabled =
featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
@@ -85,9 +100,9 @@ export default function InfraMonitoringK8s(): JSX.Element {
const handleFilterChange = (query: Query): void => {
// update the current query with the new filters
// in infra monitoring k8s, we are using only one query, hence updating the 0th index of queryData
- handleChangeQueryData('filters', query.builder.queryData[0].filters);
- setQuickFiltersLastUpdated(Date.now());
- setFilters(JSON.stringify(query.builder.queryData[0].filters));
+ const filters = query.builder.queryData[0].filters;
+ // The useEffect will sync filters to query builder, avoiding double state updates
+ setUrlFilters(filters || null);
logEvent(InfraMonitoringEvents.FilterApplied, {
entity: InfraMonitoringEvents.K8sEntity,
@@ -97,15 +112,23 @@ export default function InfraMonitoringK8s(): JSX.Element {
});
};
+ const renderCategoryLabel = (
+ icon: JSX.Element,
+ label: string,
+ ): JSX.Element => (
+ <div className={styles.quickFiltersCategoryLabel}>
+ <div className={styles.quickFiltersCategoryLabelContainer}>
+ {icon}
+ <Typography.Text>{label}</Typography.Text>
+ </div>
+ </div>
+ );
+
const items: CollapseProps['items'] = [
{
- label: (
- <div className="k8s-quick-filters-category-label">
- <div className="k8s-quick-filters-category-label-container">
- <Container size={14} className="k8s-quick-filters-category-label-icon" />
- <Typography.Text>Pods</Typography.Text>
- </div>
- </div>
+ label: renderCategoryLabel(
+ <Container size={14} className={styles.quickFiltersCategoryLabelIcon} />,
+ 'Pods',
),
key: K8sCategories.PODS,
showArrow: false,
@@ -119,13 +142,9 @@ export default function InfraMonitoringK8s(): JSX.Element {
),
},
{
- label: (
- <div className="k8s-quick-filters-category-label">
- <div className="k8s-quick-filters-category-label-container">
- <Workflow size={14} className="k8s-quick-filters-category-label-icon" />
- <Typography.Text>Nodes</Typography.Text>
- </div>
- </div>
+ label: renderCategoryLabel(
+ <Workflow size={14} className={styles.quickFiltersCategoryLabelIcon} />,
+ 'Nodes',
),
key: K8sCategories.NODES,
showArrow: false,
@@ -139,16 +158,9 @@ export default function InfraMonitoringK8s(): JSX.Element {
),
},
{
- label: (
- <div className="k8s-quick-filters-category-label">
- <div className="k8s-quick-filters-category-label-container">
- <FilePenLine
- size={14}
- className="k8s-quick-filters-category-label-icon"
- />
- <Typography.Text>Namespaces</Typography.Text>
- </div>
- </div>
+ label: renderCategoryLabel(
+ <FilePenLine size={14} className={styles.quickFiltersCategoryLabelIcon} />,
+ 'Namespaces',
),
key: K8sCategories.NAMESPACES,
showArrow: false,
@@ -162,13 +174,9 @@ export default function InfraMonitoringK8s(): JSX.Element {
),
},
{
- label: (
- <div className="k8s-quick-filters-category-label">
- <div className="k8s-quick-filters-category-label-container">
- <Boxes size={14} className="k8s-quick-filters-category-label-icon" />
- <Typography.Text>Clusters</Typography.Text>
- </div>
- </div>
+ label: renderCategoryLabel(
+ <Boxes size={14} className={styles.quickFiltersCategoryLabelIcon} />,
+ 'Clusters',
),
key: K8sCategories.CLUSTERS,
showArrow: false,
@@ -182,13 +190,9 @@ export default function InfraMonitoringK8s(): JSX.Element {
),
},
{
- label: (
- <div className="k8s-quick-filters-category-label">
- <div className="k8s-quick-filters-category-label-container">
- <Computer size={14} className="k8s-quick-filters-category-label-icon" />
- <Typography.Text>Deployments</Typography.Text>
- </div>
- </div>
+ label: renderCategoryLabel(
+ <Computer size={14} className={styles.quickFiltersCategoryLabelIcon} />,
+ 'Deployments',
),
key: K8sCategories.DEPLOYMENTS,
showArrow: false,
@@ -202,13 +206,9 @@ export default function InfraMonitoringK8s(): JSX.Element {
),
},
{
- label: (
- <div className="k8s-quick-filters-category-label">
- <div className="k8s-quick-filters-category-label-container">
- <Bolt size={14} className="k8s-quick-filters-category-label-icon" />
- <Typography.Text>Jobs</Typography.Text>
- </div>
- </div>
+ label: renderCategoryLabel(
+ <Bolt size={14} className={styles.quickFiltersCategoryLabelIcon} />,
+ 'Jobs',
),
key: K8sCategories.JOBS,
showArrow: false,
@@ -222,13 +222,9 @@ export default function InfraMonitoringK8s(): JSX.Element {
),
},
{
- label: (
- <div className="k8s-quick-filters-category-label">
- <div className="k8s-quick-filters-category-label-container">
- <Group size={14} className="k8s-quick-filters-category-label-icon" />
- <Typography.Text>DaemonSets</Typography.Text>
- </div>
- </div>
+ label: renderCategoryLabel(
+ <Group size={14} className={styles.quickFiltersCategoryLabelIcon} />,
+ 'DaemonSets',
),
key: K8sCategories.DAEMONSETS,
showArrow: false,
@@ -242,16 +238,9 @@ export default function InfraMonitoringK8s(): JSX.Element {
),
},
{
- label: (
- <div className="k8s-quick-filters-category-label">
- <div className="k8s-quick-filters-category-label-container">
- <ArrowUpDown
- size={14}
- className="k8s-quick-filters-category-label-icon"
- />
- <Typography.Text>StatefulSets</Typography.Text>
- </div>
- </div>
+ label: renderCategoryLabel(
+ <ArrowUpDown size={14} className={styles.quickFiltersCategoryLabelIcon} />,
+ 'StatefulSets',
),
key: K8sCategories.STATEFULSETS,
showArrow: false,
@@ -265,13 +254,9 @@ export default function InfraMonitoringK8s(): JSX.Element {
),
},
{
- label: (
- <div className="k8s-quick-filters-category-label">
- <div className="k8s-quick-filters-category-label-container">
- <HardDrive size={14} className="k8s-quick-filters-category-label-icon" />
- <Typography.Text>Volumes</Typography.Text>
- </div>
- </div>
+ label: renderCategoryLabel(
+ <HardDrive size={14} className={styles.quickFiltersCategoryLabelIcon} />,
+ 'Volumes',
),
key: K8sCategories.VOLUMES,
showArrow: false,
@@ -314,20 +299,39 @@ export default function InfraMonitoringK8s(): JSX.Element {
if (Array.isArray(key) && key.length > 0) {
setSelectedCategory(key[0] as string);
// Reset filters
- setFilters(null);
+ setUrlFilters(null);
setOrderBy(null);
setGroupBy(null);
handleChangeQueryData('filters', { items: [], op: 'and' });
}
};
+ const showFiltersComp = useMemo(() => {
+ return (
+ <>
+ {!showFilters && (
+ <div>
+ <Button
+ className="periscope-btn ghost"
+ type="text"
+ size="small"
+ onClick={handleFilterVisibilityChange}
+ >
+ <Filter size={14} />
+ </Button>
+ </div>
+ )}
+ </>
+ );
+ }, [handleFilterVisibilityChange, showFilters]);
+
return (
<Sentry.ErrorBoundary fallback={<ErrorBoundaryFallback />}>
- <div className="infra-monitoring-container">
- <div className="k8s-container">
+ <div className={styles.infraMonitoringContainer}>
+ <div className={styles.infraContentRow}>
{showFilters && (
- <div className="k8s-quick-filters-container">
- <div className="k8s-quick-filters-container-header">
+ <div className={styles.quickFiltersContainer}>
+ <div className={styles.quickFiltersContainerHeader}>
<Typography.Text>Filters</Typography.Text>
<Tooltip title="Collapse Filters">
@@ -350,80 +354,44 @@ export default function InfraMonitoringK8s(): JSX.Element {
)}
<div
- className={`k8s-list-container ${
- showFilters ? 'k8s-list-container-filters-visible' : ''
+ className={`${styles.listContainer} ${
+ showFilters ? styles.listContainerFiltersVisible : ''
}`}
>
{selectedCategory === K8sCategories.PODS && (
- <K8sPodLists
- isFiltersVisible={showFilters}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- quickFiltersLastUpdated={quickFiltersLastUpdated}
- />
+ <K8sPodLists controlListPrefix={showFiltersComp} />
)}
{selectedCategory === K8sCategories.NODES && (
- <K8sNodesList
- isFiltersVisible={showFilters}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- quickFiltersLastUpdated={quickFiltersLastUpdated}
- />
+ <K8sNodesList controlListPrefix={showFiltersComp} />
)}
{selectedCategory === K8sCategories.CLUSTERS && (
- <K8sClustersList
- isFiltersVisible={showFilters}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- quickFiltersLastUpdated={quickFiltersLastUpdated}
- />
+ <K8sClustersList controlListPrefix={showFiltersComp} />
)}
{selectedCategory === K8sCategories.DEPLOYMENTS && (
- <K8sDeploymentsList
- isFiltersVisible={showFilters}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- quickFiltersLastUpdated={quickFiltersLastUpdated}
- />
+ <K8sDeploymentsList controlListPrefix={showFiltersComp} />
)}
{selectedCategory === K8sCategories.NAMESPACES && (
- <K8sNamespacesList
- isFiltersVisible={showFilters}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- quickFiltersLastUpdated={quickFiltersLastUpdated}
- />
+ <K8sNamespacesList controlListPrefix={showFiltersComp} />
)}
{selectedCategory === K8sCategories.STATEFULSETS && (
- <K8sStatefulSetsList
- isFiltersVisible={showFilters}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- quickFiltersLastUpdated={quickFiltersLastUpdated}
- />
+ <K8sStatefulSetsList controlListPrefix={showFiltersComp} />
)}
{selectedCategory === K8sCategories.JOBS && (
- <K8sJobsList
- isFiltersVisible={showFilters}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- quickFiltersLastUpdated={quickFiltersLastUpdated}
- />
+ <K8sJobsList controlListPrefix={showFiltersComp} />
)}
{selectedCategory === K8sCategories.DAEMONSETS && (
- <K8sDaemonSetsList
- isFiltersVisible={showFilters}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- quickFiltersLastUpdated={quickFiltersLastUpdated}
- />
+ <K8sDaemonSetsList controlListPrefix={showFiltersComp} />
)}
{selectedCategory === K8sCategories.VOLUMES && (
- <K8sVolumesList
- isFiltersVisible={showFilters}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- quickFiltersLastUpdated={quickFiltersLastUpdated}
- />
+ <K8sVolumesList controlListPrefix={showFiltersComp} />
)}
</div>
</div>
diff --git a/frontend/src/container/InfraMonitoringK8s/Jobs/JobDetails/JobDetails.interfaces.ts b/frontend/src/container/InfraMonitoringK8s/Jobs/JobDetails/JobDetails.interfaces.ts
deleted file mode 100644
index c86821258f..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Jobs/JobDetails/JobDetails.interfaces.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { K8sJobsData } from 'api/infraMonitoring/getK8sJobsList';
-
-export type JobDetailsProps = {
- job: K8sJobsData | null;
- isModalTimeSelection: boolean;
- onClose: () => void;
-};
diff --git a/frontend/src/container/InfraMonitoringK8s/Jobs/JobDetails/JobDetails.tsx b/frontend/src/container/InfraMonitoringK8s/Jobs/JobDetails/JobDetails.tsx
deleted file mode 100644
index cf44a0c5b0..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Jobs/JobDetails/JobDetails.tsx
+++ /dev/null
@@ -1,654 +0,0 @@
-/* eslint-disable sonarjs/no-identical-functions */
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { Color, Spacing } from '@signozhq/design-tokens';
-import { Button, Divider, Drawer, Radio, Tooltip, Typography } from 'antd';
-import type { RadioChangeEvent } from 'antd/lib';
-import logEvent from 'api/common/logEvent';
-import { VIEW_TYPES, VIEWS } from 'components/HostMetricsDetail/constants';
-import { InfraMonitoringEvents } from 'constants/events';
-import { QueryParams } from 'constants/query';
-import {
- initialQueryBuilderFormValuesMap,
- initialQueryState,
-} from 'constants/queryBuilder';
-import ROUTES from 'constants/routes';
-import { filterDuplicateFilters } from 'container/InfraMonitoringK8s/commonUtils';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
-import {
- useInfraMonitoringEventsFilters,
- useInfraMonitoringLogFilters,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from 'container/InfraMonitoringK8s/hooks';
-import {
- CustomTimeType,
- Time,
-} from 'container/TopNav/DateTimeSelectionV2/types';
-import { useIsDarkMode } from 'hooks/useDarkMode';
-import useUrlQuery from 'hooks/useUrlQuery';
-import GetMinMax from 'lib/getMinMax';
-import {
- BarChart2,
- ChevronsLeftRight,
- Compass,
- DraftingCompass,
- ScrollText,
- X,
-} from 'lucide-react';
-import { AppState } from 'store/reducers';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import {
- IBuilderQuery,
- TagFilterItem,
-} from 'types/api/queryBuilder/queryBuilderData';
-import {
- LogsAggregatorOperator,
- TracesAggregatorOperator,
-} from 'types/common/queryBuilder';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { v4 as uuidv4 } from 'uuid';
-
-import JobEvents from '../../EntityDetailsUtils/EntityEvents';
-import JobLogs from '../../EntityDetailsUtils/EntityLogs';
-import JobMetrics from '../../EntityDetailsUtils/EntityMetrics';
-import JobTraces from '../../EntityDetailsUtils/EntityTraces';
-import { QUERY_KEYS } from '../../EntityDetailsUtils/utils';
-import { getJobMetricsQueryPayload, jobWidgetInfo } from './constants';
-import { JobDetailsProps } from './JobDetails.interfaces';
-
-import '../../EntityDetailsUtils/entityDetails.styles.scss';
-
-function JobDetails({
- job,
- onClose,
- isModalTimeSelection,
-}: JobDetailsProps): JSX.Element {
- const { maxTime, minTime, selectedTime } = useSelector<
- AppState,
- GlobalReducer
- >((state) => state.globalTime);
-
- const startMs = useMemo(() => Math.floor(Number(minTime) / 1000000000), [
- minTime,
- ]);
- const endMs = useMemo(() => Math.floor(Number(maxTime) / 1000000000), [
- maxTime,
- ]);
-
- const urlQuery = useUrlQuery();
-
- const [modalTimeRange, setModalTimeRange] = useState(() => ({
- startTime: startMs,
- endTime: endMs,
- }));
-
- const lastSelectedInterval = useRef<Time | null>(null);
-
- const [selectedInterval, setSelectedInterval] = useState<Time>(
- lastSelectedInterval.current
- ? lastSelectedInterval.current
- : (selectedTime as Time),
- );
-
- const [selectedView, setSelectedView] = useInfraMonitoringView();
- const [logFiltersParam, setLogFiltersParam] = useInfraMonitoringLogFilters();
- const [
- tracesFiltersParam,
- setTracesFiltersParam,
- ] = useInfraMonitoringTracesFilters();
- const [
- eventsFiltersParam,
- setEventsFiltersParam,
- ] = useInfraMonitoringEventsFilters();
- const isDarkMode = useIsDarkMode();
-
- const initialFilters = useMemo(() => {
- const filters =
- selectedView === VIEW_TYPES.LOGS ? logFiltersParam : tracesFiltersParam;
- if (filters) {
- return filters;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_JOB_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s_job_name--string--resource--false',
- },
- op: '=',
- value: job?.meta.k8s_job_name || '',
- },
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_NAMESPACE_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s_job_name--string--resource--false',
- },
- op: '=',
- value: job?.meta.k8s_namespace_name || '',
- },
- ],
- };
- }, [
- job?.meta.k8s_job_name,
- job?.meta.k8s_namespace_name,
- selectedView,
- logFiltersParam,
- tracesFiltersParam,
- ]);
-
- const initialEventsFilters = useMemo(() => {
- if (eventsFiltersParam) {
- return eventsFiltersParam;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_KIND,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.kind--string--resource--false',
- },
- op: '=',
- value: 'Job',
- },
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.name--string--resource--false',
- },
- op: '=',
- value: job?.meta.k8s_job_name || '',
- },
- ],
- };
- }, [job?.meta.k8s_job_name, eventsFiltersParam]);
-
- const [logAndTracesFilters, setLogAndTracesFilters] = useState<
- IBuilderQuery['filters']
- >(initialFilters);
-
- const [eventsFilters, setEventsFilters] = useState<IBuilderQuery['filters']>(
- initialEventsFilters,
- );
-
- useEffect(() => {
- if (job) {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Job,
- });
- }
- }, [job]);
-
- useEffect(() => {
- setLogAndTracesFilters(initialFilters);
- setEventsFilters(initialEventsFilters);
- }, [initialFilters, initialEventsFilters]);
-
- useEffect(() => {
- const currentSelectedInterval = lastSelectedInterval.current || selectedTime;
- setSelectedInterval(currentSelectedInterval as Time);
-
- if (currentSelectedInterval !== 'custom') {
- const { maxTime, minTime } = GetMinMax(currentSelectedInterval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- }, [selectedTime, minTime, maxTime]);
-
- const handleTabChange = (e: RadioChangeEvent): void => {
- setSelectedView(e.target.value);
- setLogFiltersParam(null);
- setTracesFiltersParam(null);
- setEventsFiltersParam(null);
- logEvent(InfraMonitoringEvents.TabChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Job,
- view: e.target.value,
- });
- };
-
- const handleTimeChange = useCallback(
- (interval: Time | CustomTimeType, dateTimeRange?: [number, number]): void => {
- lastSelectedInterval.current = interval as Time;
- setSelectedInterval(interval as Time);
-
- if (interval === 'custom' && dateTimeRange) {
- setModalTimeRange({
- startTime: Math.floor(dateTimeRange[0] / 1000),
- endTime: Math.floor(dateTimeRange[1] / 1000),
- });
- } else {
- const { maxTime, minTime } = GetMinMax(interval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
-
- logEvent(InfraMonitoringEvents.TimeUpdated, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Job,
- interval,
- view: selectedView,
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeLogFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_JOB_NAME, QUERY_KEYS.K8S_NAMESPACE_NAME].includes(
- item.key?.key ?? '',
- ),
- );
- const paginationFilter = value?.items?.find(
- (item) => item.key?.key === 'id',
- );
- const newFilters = value?.items?.filter(
- (item) =>
- item.key?.key !== 'id' && item.key?.key !== QUERY_KEYS.K8S_JOB_NAME,
- );
-
- if (newFilters && newFilters?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Job,
- view: 'logs',
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(newFilters || []),
- ...(paginationFilter ? [paginationFilter] : []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setLogFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeTracesFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_JOB_NAME, QUERY_KEYS.K8S_NAMESPACE_NAME].includes(
- item.key?.key ?? '',
- ),
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Job,
- view: 'traces',
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(value?.items?.filter(
- (item) => item.key?.key !== QUERY_KEYS.K8S_JOB_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setTracesFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeEventsFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setEventsFilters((prevFilters) => {
- const jobKindFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_KIND,
- );
- const jobNameFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_NAME,
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Job,
- view: 'events',
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: [
- jobKindFilter,
- jobNameFilter,
- ...(value?.items?.filter(
- (item) =>
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_KIND &&
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- };
-
- setEventsFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleExplorePagesRedirect = (): void => {
- if (selectedInterval !== 'custom') {
- urlQuery.set(QueryParams.relativeTime, selectedInterval);
- } else {
- urlQuery.delete(QueryParams.relativeTime);
- urlQuery.set(QueryParams.startTime, modalTimeRange.startTime.toString());
- urlQuery.set(QueryParams.endTime, modalTimeRange.endTime.toString());
- }
-
- logEvent(InfraMonitoringEvents.ExploreClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Job,
- view: selectedView,
- });
-
- if (selectedView === VIEW_TYPES.LOGS) {
- const filtersWithoutPagination = {
- ...logAndTracesFilters,
- items:
- logAndTracesFilters?.items?.filter((item) => item.key?.key !== 'id') || [],
- };
-
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.logs,
- aggregateOperator: LogsAggregatorOperator.NOOP,
- filters: filtersWithoutPagination,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.LOGS_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- } else if (selectedView === VIEW_TYPES.TRACES) {
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.traces,
- aggregateOperator: TracesAggregatorOperator.NOOP,
- filters: logAndTracesFilters,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.TRACES_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- }
- };
-
- const handleClose = (): void => {
- lastSelectedInterval.current = null;
- setSelectedInterval(selectedTime as Time);
-
- if (selectedTime !== 'custom') {
- const { maxTime, minTime } = GetMinMax(selectedTime);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- setSelectedView(VIEW_TYPES.METRICS);
- onClose();
- };
-
- return (
- <Drawer
- width="70%"
- title={
- <>
- <Divider type="vertical" />
- <Typography.Text className="title">
- {job?.meta.k8s_job_name}
- </Typography.Text>
- </>
- }
- placement="right"
- onClose={handleClose}
- open={!!job}
- style={{
- overscrollBehavior: 'contain',
- background: isDarkMode ? Color.BG_INK_400 : Color.BG_VANILLA_100,
- }}
- className="entity-detail-drawer"
- destroyOnClose
- closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
- >
- {job && (
- <>
- <div className="entity-detail-drawer__entity">
- <div className="entity-details-grid">
- <div className="labels-row">
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Job Name
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Namespace Name
- </Typography.Text>
- </div>
- <div className="values-row">
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={job.meta.k8s_job_name}>
- {job.meta.k8s_job_name}
- </Tooltip>
- </Typography.Text>
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={job.meta.k8s_namespace_name}>
- {job.meta.k8s_namespace_name}
- </Tooltip>
- </Typography.Text>
- </div>
- </div>
- </div>
-
- <div className="views-tabs-container">
- <Radio.Group
- className="views-tabs"
- onChange={handleTabChange}
- value={selectedView}
- >
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.METRICS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.METRICS}
- >
- <div className="view-title">
- <BarChart2 size={14} />
- Metrics
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.LOGS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.LOGS}
- >
- <div className="view-title">
- <ScrollText size={14} />
- Logs
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.TRACES ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.TRACES}
- >
- <div className="view-title">
- <DraftingCompass size={14} />
- Traces
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.EVENTS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.EVENTS}
- >
- <div className="view-title">
- <ChevronsLeftRight size={14} />
- Events
- </div>
- </Radio.Button>
- </Radio.Group>
-
- {(selectedView === VIEW_TYPES.LOGS ||
- selectedView === VIEW_TYPES.TRACES) && (
- <Button
- icon={<Compass size={18} />}
- className="compass-button"
- onClick={handleExplorePagesRedirect}
- />
- )}
- </div>
- {selectedView === VIEW_TYPES.METRICS && (
- <JobMetrics
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- entity={job}
- category={K8sCategory.JOBS}
- queryKey="jobMetrics"
- entityWidgetInfo={jobWidgetInfo}
- getEntityQueryPayload={getJobMetricsQueryPayload}
- />
- )}
- {selectedView === VIEW_TYPES.LOGS && (
- <JobLogs
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeLogFilters={handleChangeLogFilters}
- logFilters={logAndTracesFilters}
- selectedInterval={selectedInterval}
- category={K8sCategory.JOBS}
- queryKey="jobLogs"
- queryKeyFilters={[
- QUERY_KEYS.K8S_JOB_NAME,
- QUERY_KEYS.K8S_NAMESPACE_NAME,
- ]}
- />
- )}
- {selectedView === VIEW_TYPES.TRACES && (
- <JobTraces
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeTracesFilters={handleChangeTracesFilters}
- tracesFilters={logAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKey="jobTraces"
- category={InfraMonitoringEvents.Job}
- queryKeyFilters={[
- QUERY_KEYS.K8S_JOB_NAME,
- QUERY_KEYS.K8S_NAMESPACE_NAME,
- ]}
- />
- )}
- {selectedView === VIEW_TYPES.EVENTS && (
- <JobEvents
- timeRange={modalTimeRange}
- handleChangeEventFilters={handleChangeEventsFilters}
- filters={eventsFilters}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- category={K8sCategory.JOBS}
- queryKey="jobEvents"
- />
- )}
- </>
- )}
- </Drawer>
- );
-}
-
-export default JobDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/Jobs/JobDetails/index.ts b/frontend/src/container/InfraMonitoringK8s/Jobs/JobDetails/index.ts
deleted file mode 100644
index 0ddd657f88..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Jobs/JobDetails/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import JobDetails from './JobDetails';
-
-export default JobDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/Jobs/K8sJobsList.styles.scss b/frontend/src/container/InfraMonitoringK8s/Jobs/K8sJobsList.styles.scss
deleted file mode 100644
index f419db915c..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Jobs/K8sJobsList.styles.scss
+++ /dev/null
@@ -1,62 +0,0 @@
-.infra-monitoring-container {
- .jobs-list-table {
- .expanded-table-container {
- padding-left: 40px;
- }
-
- .ant-table-cell.column-progress-bar {
- min-width: 180px;
- max-width: 180px;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
-
- .progress-container {
- display: flex;
- justify-content: start;
- }
- }
-}
-
-.ant-table-cell {
- &:has(.job-name-header) {
- min-width: 250px !important;
- max-width: 250px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.namespace-name-header) {
- min-width: 220px !important;
- max-width: 220px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.med-col) {
- min-width: 200px !important;
- max-width: 200px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.small-col) {
- min-width: 120px !important;
- max-width: 120px !important;
- }
-}
-
-.expanded-jobs-list-table {
- .ant-table-cell {
- min-width: 200px !important;
- max-width: 200px !important;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
-}
diff --git a/frontend/src/container/InfraMonitoringK8s/Jobs/K8sJobsList.tsx b/frontend/src/container/InfraMonitoringK8s/Jobs/K8sJobsList.tsx
index b4ecb9a8c6..8e6c73f84d 100644
--- a/frontend/src/container/InfraMonitoringK8s/Jobs/K8sJobsList.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/Jobs/K8sJobsList.tsx
@@ -1,685 +1,118 @@
-import React, { useCallback, useEffect, useMemo, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { LoadingOutlined } from '@ant-design/icons';
-import {
- Button,
- Spin,
- Table,
- TableColumnType as ColumnType,
- TablePaginationConfig,
- TableProps,
- Typography,
-} from 'antd';
-import type { SorterResult } from 'antd/es/table/interface';
-import logEvent from 'api/common/logEvent';
-import { K8sJobsListPayload } from 'api/infraMonitoring/getK8sJobsList';
-import classNames from 'classnames';
+import React, { useCallback } from 'react';
import { InfraMonitoringEvents } from 'constants/events';
import { FeatureKeys } from 'constants/features';
-import { useGetK8sJobsList } from 'hooks/infraMonitoring/useGetK8sJobsList';
-import { useGetAggregateKeys } from 'hooks/queryBuilder/useGetAggregateKeys';
-import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
-import { ChevronDown, ChevronRight } from 'lucide-react';
import { useAppContext } from 'providers/App/App';
-import { AppState } from 'store/reducers';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { buildAbsolutePath, isModifierKeyPressed } from 'utils/app';
-import { openInNewTab } from 'utils/navigation';
-
-import emptyStateUrl from '@/assets/Icons/emptyState.svg';
+import K8sBaseDetails, { K8sDetailsFilters } from '../Base/K8sBaseDetails';
+import { K8sBaseList } from '../Base/K8sBaseList';
+import { K8sBaseFilters } from '../Base/types';
+import { InfraMonitoringEntity } from '../constants';
+import { getK8sJobsList, K8sJobsData } from './api';
import {
- GetK8sEntityToAggregateAttribute,
- INFRA_MONITORING_K8S_PARAMS_KEYS,
- K8sCategory,
-} from '../constants';
-import {
- useInfraMonitoringCurrentPage,
- useInfraMonitoringEventsFilters,
- useInfraMonitoringGroupBy,
- useInfraMonitoringJobUID,
- useInfraMonitoringLogFilters,
- useInfraMonitoringOrderBy,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from '../hooks';
-import K8sHeader from '../K8sHeader';
-import LoadingContainer from '../LoadingContainer';
-import { usePageSize } from '../utils';
-import JobDetails from './JobDetails';
+ getJobMetricsQueryPayload,
+ jobWidgetInfo,
+ k8sJobDetailsMetadataConfig,
+ k8sJobGetEntityName,
+ k8sJobGetSelectedItemFilters,
+ k8sJobInitialEventsFilter,
+ k8sJobInitialFilters,
+ k8sJobInitialLogTracesFilter,
+} from './constants';
import {
- defaultAddedColumns,
- formatDataForTable,
- getK8sJobsListColumns,
- getK8sJobsListQuery,
- K8sJobsRowData,
-} from './utils';
-
-import '../InfraMonitoringK8s.styles.scss';
-import './K8sJobsList.styles.scss';
+ k8sJobsColumns,
+ k8sJobsColumnsConfig,
+ k8sJobsRenderRowData,
+} from './table.config';
function K8sJobsList({
- isFiltersVisible,
- handleFilterVisibilityChange,
- quickFiltersLastUpdated,
+ controlListPrefix,
}: {
- isFiltersVisible: boolean;
- handleFilterVisibilityChange: () => void;
- quickFiltersLastUpdated: number;
+ controlListPrefix?: React.ReactNode;
}): JSX.Element {
- const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
- (state) => state.globalTime,
- );
-
- const [currentPage, setCurrentPage] = useInfraMonitoringCurrentPage();
- const [filtersInitialised, setFiltersInitialised] = useState(false);
-
- const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
-
- const [orderBy, setOrderBy] = useInfraMonitoringOrderBy();
-
- const [selectedJobUID, setselectedJobUID] = useInfraMonitoringJobUID();
-
- const { pageSize, setPageSize } = usePageSize(K8sCategory.JOBS);
-
- const [groupBy, setGroupBy] = useInfraMonitoringGroupBy();
-
- const [, setView] = useInfraMonitoringView();
- const [, setTracesFilters] = useInfraMonitoringTracesFilters();
- const [, setEventsFilters] = useInfraMonitoringEventsFilters();
- const [, setLogFilters] = useInfraMonitoringLogFilters();
-
- const [selectedRowData, setSelectedRowData] = useState<K8sJobsRowData | null>(
- null,
- );
-
- const [groupByOptions, setGroupByOptions] = useState<
- { value: string; label: string }[]
- >([]);
-
- const { currentQuery } = useQueryBuilder();
-
- const queryFilters = useMemo(
- () =>
- currentQuery?.builder?.queryData[0]?.filters || {
- items: [],
- op: 'and',
- },
- [currentQuery?.builder?.queryData],
- );
-
- // Reset pagination every time quick filters are changed
- useEffect(() => {
- if (quickFiltersLastUpdated !== -1) {
- setCurrentPage(1);
- }
- }, [quickFiltersLastUpdated, setCurrentPage]);
-
const { featureFlags } = useAppContext();
const dotMetricsEnabled =
featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
?.active || false;
- const createFiltersForSelectedRowData = (
- selectedRowData: K8sJobsRowData,
- groupBy: IBuilderQuery['groupBy'],
- ): IBuilderQuery['filters'] => {
- const baseFilters: IBuilderQuery['filters'] = {
- items: [...queryFilters.items],
- op: 'and',
- };
-
- if (!selectedRowData) {
- return baseFilters;
- }
-
- const { groupedByMeta } = selectedRowData;
-
- for (const key of groupBy) {
- baseFilters.items.push({
- key: {
- key: key.key,
- type: null,
- },
- op: '=',
- value: groupedByMeta[key.key],
- id: key.key,
- });
- }
-
- return baseFilters;
- };
-
- const fetchGroupedByRowDataQuery = useMemo(() => {
- if (!selectedRowData) {
- return null;
- }
-
- const baseQuery = getK8sJobsListQuery();
-
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- return {
- ...baseQuery,
- limit: 10,
- offset: 0,
- filters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [minTime, maxTime, orderBy, selectedRowData, groupBy]);
-
- const groupedByRowDataQueryKey = useMemo(() => {
- // be careful with what you serialize from selectedRowData
- // since it's react node, it could contain circular references
- const selectedRowDataKey = JSON.stringify(selectedRowData?.groupedByMeta);
- if (selectedJobUID) {
- return [
- 'jobList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- ];
- }
- return [
- 'jobList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- String(minTime),
- String(maxTime),
- ];
- }, [queryFilters, orderBy, selectedJobUID, minTime, maxTime, selectedRowData]);
-
- const {
- data: groupedByRowData,
- isFetching: isFetchingGroupedByRowData,
- isLoading: isLoadingGroupedByRowData,
- isError: isErrorGroupedByRowData,
- refetch: fetchGroupedByRowData,
- } = useGetK8sJobsList(
- fetchGroupedByRowDataQuery as K8sJobsListPayload,
- {
- queryKey: groupedByRowDataQueryKey,
- enabled: !!fetchGroupedByRowDataQuery && !!selectedRowData,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const {
- data: groupByFiltersData,
- isLoading: isLoadingGroupByFilters,
- } = useGetAggregateKeys(
- {
- dataSource: currentQuery.builder.queryData[0].dataSource,
- aggregateAttribute: GetK8sEntityToAggregateAttribute(
- K8sCategory.JOBS,
+ const fetchListData = useCallback(
+ async (filters: K8sBaseFilters, signal?: AbortSignal) => {
+ filters.orderBy ||= {
+ columnName: 'cpu',
+ order: 'desc',
+ };
+
+ const response = await getK8sJobsList(
+ filters,
+ signal,
+ undefined,
dotMetricsEnabled,
- ),
- aggregateOperator: 'noop',
- searchText: '',
- tagType: '',
- },
- {
- queryKey: [currentQuery.builder.queryData[0].dataSource, 'noop'],
- },
- true,
- K8sCategory.JOBS,
- );
-
- const query = useMemo(() => {
- const baseQuery = getK8sJobsListQuery();
- const queryPayload = {
- ...baseQuery,
- limit: pageSize,
- offset: (currentPage - 1) * pageSize,
- filters: queryFilters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- if (groupBy.length > 0) {
- queryPayload.groupBy = groupBy;
- }
- return queryPayload;
- }, [pageSize, currentPage, queryFilters, minTime, maxTime, orderBy, groupBy]);
-
- const formattedGroupedByJobsData = useMemo(
- () =>
- formatDataForTable(groupedByRowData?.payload?.data?.records || [], groupBy),
- [groupedByRowData, groupBy],
- );
-
- const nestedJobsData = useMemo(() => {
- if (!selectedRowData || !groupedByRowData?.payload?.data.records) {
- return [];
- }
- return groupedByRowData?.payload?.data?.records || [];
- }, [groupedByRowData, selectedRowData]);
-
- const queryKey = useMemo(() => {
- if (selectedJobUID) {
- return [
- 'jobList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- ];
- }
- return [
- 'jobList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- String(minTime),
- String(maxTime),
- ];
- }, [
- selectedJobUID,
- pageSize,
- currentPage,
- queryFilters,
- orderBy,
- groupBy,
- minTime,
- maxTime,
- ]);
-
- const { data, isFetching, isLoading, isError } = useGetK8sJobsList(
- query as K8sJobsListPayload,
- {
- queryKey,
- enabled: !!query,
- keepPreviousData: true,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const jobsData = useMemo(() => data?.payload?.data?.records || [], [data]);
- const totalCount = data?.payload?.data?.total || 0;
-
- const formattedJobsData = useMemo(
- () => formatDataForTable(jobsData, groupBy),
- [jobsData, groupBy],
- );
-
- const columns = useMemo(() => getK8sJobsListColumns(groupBy), [groupBy]);
-
- const handleGroupByRowClick = (record: K8sJobsRowData): void => {
- setSelectedRowData(record);
-
- if (expandedRowKeys.includes(record.key)) {
- setExpandedRowKeys(expandedRowKeys.filter((key) => key !== record.key));
- } else {
- setExpandedRowKeys([record.key]);
- }
- };
-
- useEffect(() => {
- if (selectedRowData) {
- fetchGroupedByRowData();
- }
- }, [selectedRowData, fetchGroupedByRowData]);
-
- const handleTableChange: TableProps<K8sJobsRowData>['onChange'] = useCallback(
- (
- pagination: TablePaginationConfig,
- _filters: Record<string, (string | number | boolean)[] | null>,
- sorter: SorterResult<K8sJobsRowData> | SorterResult<K8sJobsRowData>[],
- ): void => {
- if (pagination.current) {
- setCurrentPage(pagination.current);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Job,
- });
- }
-
- if ('field' in sorter && sorter.order) {
- setOrderBy({
- columnName: sorter.field as string,
- order: (sorter.order === 'ascend' ? 'asc' : 'desc') as 'asc' | 'desc',
- });
- } else {
- setOrderBy(null);
- }
- },
- [setCurrentPage, setOrderBy],
- );
-
- const { handleChangeQueryData } = useQueryOperations({
- index: 0,
- query: currentQuery.builder.queryData[0],
- entityVersion: '',
- });
-
- const handleFiltersChange = useCallback(
- (value: IBuilderQuery['filters']): void => {
- handleChangeQueryData('filters', value);
- if (filtersInitialised) {
- setCurrentPage(1);
- } else {
- setFiltersInitialised(true);
- }
+ );
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Job,
- });
- }
+ return {
+ data: response.payload?.data.records || [],
+ total: response.payload?.data.total || 0,
+ error: response.error,
+ rawData: response.payload?.data,
+ };
},
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- useEffect(() => {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Job,
- total: data?.payload?.data?.total,
- });
- }, [data?.payload?.data?.total]);
-
- const selectedJobData = useMemo(() => {
- if (groupBy.length > 0) {
- // If grouped by, return the job from the formatted grouped by data
- return nestedJobsData.find((job) => job.jobName === selectedJobUID) || null;
- }
- // If not grouped by, return the job from the jobs data
- return jobsData.find((job) => job.jobName === selectedJobUID) || null;
- }, [selectedJobUID, groupBy.length, jobsData, nestedJobsData]);
-
- const openJobInNewTab = (record: K8sJobsRowData): void => {
- const newParams = new URLSearchParams(document.location.search);
- newParams.set(INFRA_MONITORING_K8S_PARAMS_KEYS.JOB_UID, record.jobUID);
- openInNewTab(
- buildAbsolutePath({
- relativePath: '',
- urlQueryString: newParams.toString(),
- }),
- );
- };
-
- const handleRowClick = (
- record: K8sJobsRowData,
- event: React.MouseEvent,
- ): void => {
- if (event && isModifierKeyPressed(event)) {
- openJobInNewTab(record);
- return;
- }
- if (groupBy.length === 0) {
- setSelectedRowData(null);
- setselectedJobUID(record.jobUID);
- } else {
- handleGroupByRowClick(record);
- }
-
- logEvent(InfraMonitoringEvents.ItemClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Job,
- });
- };
-
- const nestedColumns = useMemo(() => getK8sJobsListColumns([]), []);
-
- const isGroupedByAttribute = groupBy.length > 0;
-
- const handleExpandedRowViewAllClick = (): void => {
- if (!selectedRowData) {
- return;
- }
-
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- handleFiltersChange(filters);
-
- setCurrentPage(1);
- setSelectedRowData(null);
- setGroupBy([]);
- setOrderBy(null);
- };
-
- const expandedRowRender = (): JSX.Element => (
- <div className="expanded-table-container">
- {isErrorGroupedByRowData && (
- <Typography>{groupedByRowData?.error || 'Something went wrong'}</Typography>
- )}
- {isFetchingGroupedByRowData || isLoadingGroupedByRowData ? (
- <LoadingContainer />
- ) : (
- <div className="expanded-table">
- <Table
- columns={nestedColumns as ColumnType<K8sJobsRowData>[]}
- dataSource={formattedGroupedByJobsData}
- pagination={false}
- scroll={{ x: true }}
- tableLayout="fixed"
- size="small"
- loading={{
- spinning: isFetchingGroupedByRowData || isLoadingGroupedByRowData,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- showHeader={false}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => {
- if (event && isModifierKeyPressed(event)) {
- openJobInNewTab(record);
- return;
- }
- setselectedJobUID(record.jobUID);
- },
- className: 'expanded-clickable-row',
- })}
- />
-
- {groupedByRowData?.payload?.data?.total &&
- groupedByRowData?.payload?.data?.total > 10 ? (
- <div className="expanded-table-footer">
- <Button
- type="default"
- size="small"
- className="periscope-btn secondary"
- onClick={handleExpandedRowViewAllClick}
- >
- View All
- </Button>
- </div>
- ) : null}
- </div>
- )}
- </div>
+ [dotMetricsEnabled],
);
- const expandRowIconRenderer = ({
- expanded,
- onExpand,
- record,
- }: {
- expanded: boolean;
- onExpand: (
- record: K8sJobsRowData,
- e: React.MouseEvent<HTMLButtonElement>,
- ) => void;
- record: K8sJobsRowData;
- }): JSX.Element | null => {
- if (!isGroupedByAttribute) {
- return null;
- }
-
- return expanded ? (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronDown size={14} />
- </Button>
- ) : (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronRight size={14} />
- </Button>
- );
- };
-
- const handleCloseJobDetail = (): void => {
- setselectedJobUID(null);
- setView(null);
- setTracesFilters(null);
- setEventsFilters(null);
- setLogFilters(null);
- };
-
- const handleGroupByChange = useCallback(
- (value: IBuilderQuery['groupBy']) => {
- const groupBy = [];
-
- for (let index = 0; index < value.length; index++) {
- const element = (value[index] as unknown) as string;
-
- const key = groupByFiltersData?.payload?.attributeKeys?.find(
- (key) => key.key === element,
- );
-
- if (key) {
- groupBy.push(key);
- }
- }
+ const fetchEntityData = useCallback(
+ async (
+ filters: K8sDetailsFilters,
+ signal?: AbortSignal,
+ ): Promise<{ data: K8sJobsData | null; error?: string | null }> => {
+ const response = await getK8sJobsList(
+ {
+ filters: filters.filters,
+ start: filters.start,
+ end: filters.end,
+ limit: 1,
+ offset: 0,
+ },
+ signal,
+ undefined,
+ dotMetricsEnabled,
+ );
- setCurrentPage(1);
- setGroupBy(groupBy);
- setExpandedRowKeys([]);
+ const records = response.payload?.data.records || [];
- logEvent(InfraMonitoringEvents.GroupByChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Job,
- });
+ return {
+ data: records.length > 0 ? records[0] : null,
+ error: response.error,
+ };
},
- [groupByFiltersData, setCurrentPage, setGroupBy],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- if (groupByFiltersData?.payload) {
- setGroupByOptions(
- groupByFiltersData?.payload?.attributeKeys?.map((filter) => ({
- value: filter.key,
- label: filter.key,
- })) || [],
- );
- }
- }, [groupByFiltersData]);
-
- const onPaginationChange = (page: number, pageSize: number): void => {
- setCurrentPage(page);
- setPageSize(pageSize);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Job,
- });
- };
-
return (
- <div className="k8s-list">
- <K8sHeader
- isFiltersVisible={isFiltersVisible}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- defaultAddedColumns={defaultAddedColumns}
- handleFiltersChange={handleFiltersChange}
- groupByOptions={groupByOptions}
- isLoadingGroupByFilters={isLoadingGroupByFilters}
- handleGroupByChange={handleGroupByChange}
- selectedGroupBy={groupBy}
- entity={K8sCategory.JOBS}
- showAutoRefresh={!selectedJobData}
- />
- {isError && <Typography>{data?.error || 'Something went wrong'}</Typography>}
-
- <Table
- className={classNames('k8s-list-table', 'jobs-list-table', {
- 'expanded-jobs-list-table': isGroupedByAttribute,
- })}
- dataSource={isFetching || isLoading ? [] : formattedJobsData}
- columns={columns}
- pagination={{
- current: currentPage,
- pageSize,
- total: totalCount,
- showSizeChanger: true,
- hideOnSinglePage: false,
- onChange: onPaginationChange,
- }}
- scroll={{ x: true }}
- loading={{
- spinning: isFetching || isLoading,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- locale={{
- emptyText:
- isFetching || isLoading ? null : (
- <div className="no-filtered-hosts-message-container">
- <div className="no-filtered-hosts-message-content">
- <img
- src={emptyStateUrl}
- alt="thinking-emoji"
- className="empty-state-svg"
- />
-
- <Typography.Text className="no-filtered-hosts-message">
- This query had no results. Edit your query and try again!
- </Typography.Text>
- </div>
- </div>
- ),
- }}
- tableLayout="fixed"
- onChange={handleTableChange}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => handleRowClick(record, event),
- className: 'clickable-row',
- })}
- expandable={{
- expandedRowRender: isGroupedByAttribute ? expandedRowRender : undefined,
- expandIcon: expandRowIconRenderer,
- expandedRowKeys,
- }}
+ <>
+ <K8sBaseList<K8sJobsData>
+ controlListPrefix={controlListPrefix}
+ entity={InfraMonitoringEntity.JOBS}
+ tableColumnsDefinitions={k8sJobsColumns}
+ tableColumns={k8sJobsColumnsConfig}
+ fetchListData={fetchListData}
+ renderRowData={k8sJobsRenderRowData}
+ eventCategory={InfraMonitoringEvents.Job}
/>
- <JobDetails
- job={selectedJobData}
- isModalTimeSelection
- onClose={handleCloseJobDetail}
+ <K8sBaseDetails<K8sJobsData>
+ category={InfraMonitoringEntity.JOBS}
+ eventCategory={InfraMonitoringEvents.Job}
+ getSelectedItemFilters={k8sJobGetSelectedItemFilters}
+ fetchEntityData={fetchEntityData}
+ getEntityName={k8sJobGetEntityName}
+ getInitialLogTracesFilters={k8sJobInitialLogTracesFilter}
+ getInitialEventsFilters={k8sJobInitialEventsFilter}
+ primaryFilterKeys={k8sJobInitialFilters}
+ metadataConfig={k8sJobDetailsMetadataConfig}
+ entityWidgetInfo={jobWidgetInfo}
+ getEntityQueryPayload={getJobMetricsQueryPayload}
+ queryKeyPrefix="job"
/>
- </div>
+ </>
);
}
diff --git a/frontend/src/api/infraMonitoring/getK8sJobsList.ts b/frontend/src/container/InfraMonitoringK8s/Jobs/api.ts
similarity index 61%
rename from frontend/src/api/infraMonitoring/getK8sJobsList.ts
rename to frontend/src/container/InfraMonitoringK8s/Jobs/api.ts
index 592ee8df3f..03f4bae529 100644
--- a/frontend/src/api/infraMonitoring/getK8sJobsList.ts
+++ b/frontend/src/container/InfraMonitoringK8s/Jobs/api.ts
@@ -1,22 +1,10 @@
import axios from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
+import { UnderscoreToDotMap } from 'api/utils';
import { AxiosError } from 'axios';
import { ErrorResponse, SuccessResponse } from 'types/api';
-import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
-import { UnderscoreToDotMap } from '../utils';
-
-export interface K8sJobsListPayload {
- filters: TagFilter;
- groupBy?: BaseAutocompleteData[];
- offset?: number;
- limit?: number;
- orderBy?: {
- columnName: string;
- order: 'asc' | 'desc';
- };
-}
+import { K8sBaseFilters } from '../Base/types';
export interface K8sJobsData {
jobName: string;
@@ -50,6 +38,7 @@ export interface K8sJobsListResponse {
};
}
+// TODO(H4ad): Erase this whole file when migrating to openapi
export const jobsMetaMap = [
{ dot: 'k8s.cluster.name', under: 'k8s_cluster_name' },
{ dot: 'k8s.job.name', under: 'k8s_job_name' },
@@ -68,44 +57,43 @@ export function mapJobsMeta(raw: Record<string, unknown>): K8sJobsData['meta'] {
}
export const getK8sJobsList = async (
- props: K8sJobsListPayload,
+ props: K8sBaseFilters,
signal?: AbortSignal,
headers?: Record<string, string>,
dotMetricsEnabled = false,
): Promise<SuccessResponse<K8sJobsListResponse> | ErrorResponse> => {
try {
- const requestProps =
- dotMetricsEnabled && Array.isArray(props.filters?.items)
- ? {
- ...props,
- filters: {
- ...props.filters,
- items: props.filters.items.reduce<typeof props.filters.items>(
- (acc, item) => {
- if (item.value === undefined) {
- return acc;
- }
- if (
- item.key &&
- typeof item.key === 'object' &&
- 'key' in item.key &&
- typeof item.key.key === 'string'
- ) {
- const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
- acc.push({
- ...item,
- key: { ...item.key, key: mappedKey },
- });
- } else {
- acc.push(item);
- }
+ const requestProps = dotMetricsEnabled
+ ? {
+ ...props,
+ filters: {
+ ...props.filters,
+ items: props.filters?.items.reduce<typeof props.filters.items>(
+ (acc, item) => {
+ if (item.value === undefined) {
return acc;
- },
- [] as typeof props.filters.items,
- ),
- },
- }
- : props;
+ }
+ if (
+ item.key &&
+ typeof item.key === 'object' &&
+ 'key' in item.key &&
+ typeof item.key.key === 'string'
+ ) {
+ const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
+ acc.push({
+ ...item,
+ key: { ...item.key, key: mappedKey },
+ });
+ } else {
+ acc.push(item);
+ }
+ return acc;
+ },
+ [] as typeof props.filters.items,
+ ),
+ },
+ }
+ : props;
const response = await axios.post('/jobs/list', requestProps, {
signal,
@@ -113,7 +101,6 @@ export const getK8sJobsList = async (
});
const payload: K8sJobsListResponse = response.data;
- // one-liner meta mapping
payload.data.records = payload.data.records.map((record) => ({
...record,
meta: mapJobsMeta(record.meta as Record<string, unknown>),
diff --git a/frontend/src/container/InfraMonitoringK8s/Jobs/JobDetails/constants.ts b/frontend/src/container/InfraMonitoringK8s/Jobs/constants.ts
similarity index 85%
rename from frontend/src/container/InfraMonitoringK8s/Jobs/JobDetails/constants.ts
rename to frontend/src/container/InfraMonitoringK8s/Jobs/constants.ts
index 390124a6b6..4c07b10dc3 100644
--- a/frontend/src/container/InfraMonitoringK8s/Jobs/JobDetails/constants.ts
+++ b/frontend/src/container/InfraMonitoringK8s/Jobs/constants.ts
@@ -1,11 +1,72 @@
-import { K8sJobsData } from 'api/infraMonitoring/getK8sJobsList';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { v4 } from 'uuid';
+import {
+ createFilterItem,
+ K8sDetailsMetadataConfig,
+} from '../Base/K8sBaseDetails';
+import { QUERY_KEYS } from '../EntityDetailsUtils/utils';
+import { K8sJobsData } from './api';
+
+export const k8sJobGetSelectedItemFilters = (
+ selectedItemId: string,
+): TagFilter => ({
+ op: 'AND',
+ items: [
+ {
+ id: 'k8s_job_name',
+ key: {
+ key: 'k8s_job_name',
+ type: null,
+ },
+ op: '=',
+ value: selectedItemId,
+ },
+ ],
+});
+
+export const k8sJobDetailsMetadataConfig: K8sDetailsMetadataConfig<K8sJobsData>[] = [
+ {
+ label: 'Job Name',
+ getValue: (p): string => p.meta.k8s_job_name,
+ },
+ {
+ label: 'Cluster Name',
+ getValue: (p): string => p.meta.k8s_cluster_name,
+ },
+ {
+ label: 'Namespace Name',
+ getValue: (p): string => p.meta.k8s_namespace_name,
+ },
+];
+
+export const k8sJobInitialFilters = [
+ QUERY_KEYS.K8S_JOB_NAME,
+ QUERY_KEYS.K8S_NAMESPACE_NAME,
+];
+
+export const k8sJobInitialEventsFilter = (
+ item: K8sJobsData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_KIND, 'Job'),
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_NAME, item.meta.k8s_job_name),
+];
+
+export const k8sJobInitialLogTracesFilter = (
+ item: K8sJobsData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(QUERY_KEYS.K8S_JOB_NAME, item.meta.k8s_job_name),
+ createFilterItem(QUERY_KEYS.K8S_NAMESPACE_NAME, item.meta.k8s_namespace_name),
+];
+
+export const k8sJobGetEntityName = (item: K8sJobsData): string =>
+ item.meta.k8s_job_name;
+
export const jobWidgetInfo = [
{
title: 'CPU usage',
diff --git a/frontend/src/container/InfraMonitoringK8s/Jobs/table.config.tsx b/frontend/src/container/InfraMonitoringK8s/Jobs/table.config.tsx
new file mode 100644
index 0000000000..612b4594c3
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Jobs/table.config.tsx
@@ -0,0 +1,330 @@
+import { TableColumnType as ColumnType, Tooltip } from 'antd';
+import { Group } from 'lucide-react';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+
+import { K8sRenderedRowData } from '../Base/types';
+import { IEntityColumn } from '../Base/useInfraMonitoringTableColumnsStore';
+import { getGroupByEl, getGroupedByMeta, getRowKey } from '../Base/utils';
+import {
+ EntityProgressBar,
+ formatBytes,
+ ValidateColumnValueWrapper,
+} from '../commonUtils';
+import { InfraMonitoringEntity } from '../constants';
+import { K8sJobsData } from './api';
+
+import styles from './table.module.scss';
+
+export const k8sJobsColumns: IEntityColumn[] = [
+ {
+ label: 'Job Group',
+ value: 'jobGroup',
+ id: 'jobGroup',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-collapse',
+ },
+ {
+ label: 'Job Name',
+ value: 'jobName',
+ id: 'jobName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-expand',
+ },
+ {
+ label: 'Namespace Name',
+ value: 'namespaceName',
+ id: 'namespaceName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Successful',
+ value: 'successful_pods',
+ id: 'successful_pods',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Failed',
+ value: 'failed_pods',
+ id: 'failed_pods',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Desired Successful',
+ value: 'desired_successful_pods',
+ id: 'desired_successful_pods',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Active',
+ value: 'active_pods',
+ id: 'active_pods',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Req Usage (%)',
+ value: 'cpu_request',
+ id: 'cpu_request',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Limit Usage (%)',
+ value: 'cpu_limit',
+ id: 'cpu_limit',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Usage (cores)',
+ value: 'cpu',
+ id: 'cpu',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Req Usage (%)',
+ value: 'memory_request',
+ id: 'memory_request',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Limit Usage (%)',
+ value: 'memory_limit',
+ id: 'memory_limit',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Usage (WSS)',
+ value: 'memory',
+ id: 'memory',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+];
+
+export const k8sJobsColumnsConfig: ColumnType<K8sRenderedRowData>[] = [
+ {
+ title: (
+ <div className={styles.entityGroupHeader}>
+ <Group size={14} /> JOB GROUP
+ </div>
+ ),
+ dataIndex: 'jobGroup',
+ key: 'jobGroup',
+ ellipsis: true,
+ width: 150,
+ align: 'left',
+ sorter: false,
+ },
+ {
+ title: <div>Job Name</div>,
+ dataIndex: 'jobName',
+ key: 'jobName',
+ ellipsis: true,
+ width: 80,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>Namespace Name</div>,
+ dataIndex: 'namespaceName',
+ key: 'namespaceName',
+ ellipsis: true,
+ width: 80,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>Successful</div>,
+ dataIndex: 'successful_pods',
+ key: 'successful_pods',
+ ellipsis: true,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Failed</div>,
+ dataIndex: 'failed_pods',
+ key: 'failed_pods',
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Desired Successful</div>,
+ dataIndex: 'desired_successful_pods',
+ key: 'desired_successful_pods',
+ ellipsis: true,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Active</div>,
+ dataIndex: 'active_pods',
+ key: 'active_pods',
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Req Usage (%)</div>,
+ dataIndex: 'cpu_request',
+ key: 'cpu_request',
+ width: 180,
+ ellipsis: true,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Limit Usage (%)</div>,
+ dataIndex: 'cpu_limit',
+ key: 'cpu_limit',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Usage (cores)</div>,
+ dataIndex: 'cpu',
+ key: 'cpu',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Req Usage (%)</div>,
+ dataIndex: 'memory_request',
+ key: 'memory_request',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Limit Usage (%)</div>,
+ dataIndex: 'memory_limit',
+ key: 'memory_limit',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Usage (WSS)</div>,
+ dataIndex: 'memory',
+ key: 'memory',
+ width: 120,
+ ellipsis: true,
+ sorter: true,
+ align: 'left',
+ },
+];
+
+export const k8sJobsRenderRowData = (
+ job: K8sJobsData,
+ groupBy: BaseAutocompleteData[],
+): K8sRenderedRowData => ({
+ key: getRowKey(job, () => job.jobName || job.meta.k8s_job_name || '', groupBy),
+ itemKey: job.meta.k8s_job_name,
+ jobName: (
+ <Tooltip title={job.meta.k8s_job_name}>{job.meta.k8s_job_name || ''}</Tooltip>
+ ),
+ namespaceName: (
+ <Tooltip title={job.meta.k8s_namespace_name}>
+ {job.meta.k8s_namespace_name || ''}
+ </Tooltip>
+ ),
+ cpu_request: (
+ <ValidateColumnValueWrapper
+ value={job.cpuRequest}
+ entity={InfraMonitoringEntity.JOBS}
+ attribute="CPU Request"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={job.cpuRequest} type="request" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ cpu_limit: (
+ <ValidateColumnValueWrapper
+ value={job.cpuLimit}
+ entity={InfraMonitoringEntity.JOBS}
+ attribute="CPU Limit"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={job.cpuLimit} type="limit" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ cpu: (
+ <ValidateColumnValueWrapper value={job.cpuUsage}>
+ {job.cpuUsage}
+ </ValidateColumnValueWrapper>
+ ),
+ memory_request: (
+ <ValidateColumnValueWrapper
+ value={job.memoryRequest}
+ entity={InfraMonitoringEntity.JOBS}
+ attribute="Memory Request"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={job.memoryRequest} type="request" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ memory_limit: (
+ <ValidateColumnValueWrapper
+ value={job.memoryLimit}
+ entity={InfraMonitoringEntity.JOBS}
+ attribute="Memory Limit"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={job.memoryLimit} type="limit" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ memory: (
+ <ValidateColumnValueWrapper value={job.memoryUsage}>
+ {formatBytes(job.memoryUsage)}
+ </ValidateColumnValueWrapper>
+ ),
+ successful_pods: (
+ <ValidateColumnValueWrapper value={job.successfulPods}>
+ {job.successfulPods}
+ </ValidateColumnValueWrapper>
+ ),
+ desired_successful_pods: (
+ <ValidateColumnValueWrapper value={job.desiredSuccessfulPods}>
+ {job.desiredSuccessfulPods}
+ </ValidateColumnValueWrapper>
+ ),
+ failed_pods: (
+ <ValidateColumnValueWrapper value={job.failedPods}>
+ {job.failedPods}
+ </ValidateColumnValueWrapper>
+ ),
+ active_pods: (
+ <ValidateColumnValueWrapper value={job.activePods}>
+ {job.activePods}
+ </ValidateColumnValueWrapper>
+ ),
+ jobGroup: getGroupByEl(job, groupBy),
+ ...job.meta,
+ groupedByMeta: getGroupedByMeta(job, groupBy),
+});
diff --git a/frontend/src/container/InfraMonitoringK8s/Jobs/table.module.scss b/frontend/src/container/InfraMonitoringK8s/Jobs/table.module.scss
new file mode 100644
index 0000000000..bc11f496a1
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Jobs/table.module.scss
@@ -0,0 +1,11 @@
+.entityGroupHeader {
+ padding-left: var(--spacing-5);
+ gap: var(--spacing-5);
+ display: flex;
+ align-items: center;
+}
+
+.progressBar {
+ display: flex;
+ justify-content: start;
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Jobs/utils.tsx b/frontend/src/container/InfraMonitoringK8s/Jobs/utils.tsx
deleted file mode 100644
index d33795573b..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Jobs/utils.tsx
+++ /dev/null
@@ -1,393 +0,0 @@
-import { Color } from '@signozhq/design-tokens';
-import { TableColumnType as ColumnType, Tag, Tooltip } from 'antd';
-import {
- K8sJobsData,
- K8sJobsListPayload,
-} from 'api/infraMonitoring/getK8sJobsList';
-import { Group } from 'lucide-react';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-
-import {
- EntityProgressBar,
- formatBytes,
- ValidateColumnValueWrapper,
-} from '../commonUtils';
-import { K8sCategory } from '../constants';
-import { IEntityColumn } from '../utils';
-
-export const defaultAddedColumns: IEntityColumn[] = [
- {
- label: 'Job Name',
- value: 'jobName',
- id: 'jobName',
- canRemove: false,
- },
- {
- label: 'Namespace Name',
- value: 'namespaceName',
- id: 'namespaceName',
- canRemove: false,
- },
- {
- label: 'Successful',
- value: 'successful_pods',
- id: 'successful_pods',
- canRemove: false,
- },
- {
- label: 'Failed',
- value: 'failed_pods',
- id: 'failed_pods',
- canRemove: false,
- },
- {
- label: 'Desired Successful',
- value: 'desired_successful_pods',
- id: 'desired_successful_pods',
- canRemove: false,
- },
- {
- label: 'Active',
- value: 'active_pods',
- id: 'active_pods',
- canRemove: false,
- },
- {
- label: 'CPU Req Usage (%)',
- value: 'cpu_request',
- id: 'cpu_request',
- canRemove: false,
- },
- {
- label: 'CPU Limit Usage (%)',
- value: 'cpu_limit',
- id: 'cpu_limit',
- canRemove: false,
- },
- {
- label: 'CPU Usage (cores)',
- value: 'cpu',
- id: 'cpu',
- canRemove: false,
- },
- {
- label: 'Mem Req Usage (%)',
- value: 'memory_request',
- id: 'memory_request',
- canRemove: false,
- },
- {
- label: 'Mem Limit Usage (%)',
- value: 'memory_limit',
- id: 'memory_limit',
- canRemove: false,
- },
- {
- label: 'Mem Usage (WSS)',
- value: 'memory',
- id: 'memory',
- canRemove: false,
- },
-];
-
-export interface K8sJobsRowData {
- key: string;
- jobUID: string;
- jobName: React.ReactNode;
- namespaceName: React.ReactNode;
- successful_pods: React.ReactNode;
- failed_pods: React.ReactNode;
- active_pods: React.ReactNode;
- desired_successful_pods: React.ReactNode;
- cpu_request: React.ReactNode;
- cpu_limit: React.ReactNode;
- cpu: React.ReactNode;
- memory_request: React.ReactNode;
- memory_limit: React.ReactNode;
- memory: React.ReactNode;
- groupedByMeta?: any;
-}
-
-const jobGroupColumnConfig = {
- title: (
- <div className="column-header entity-group-header">
- <Group size={14} /> JOB GROUP
- </div>
- ),
- dataIndex: 'jobGroup',
- key: 'jobGroup',
- ellipsis: true,
- width: 150,
- align: 'left',
- sorter: false,
- className: 'column entity-group-header',
-};
-
-export const getK8sJobsListQuery = (): K8sJobsListPayload => ({
- filters: {
- items: [],
- op: 'and',
- },
- orderBy: { columnName: 'cpu', order: 'desc' },
-});
-
-const columnProgressBarClassName = 'column-progress-bar';
-
-const columnsConfig = [
- {
- title: <div className="column-header-left job-name-header">Job Name</div>,
- dataIndex: 'jobName',
- key: 'jobName',
- ellipsis: true,
- width: 80,
- sorter: false,
- align: 'left',
- },
- {
- title: (
- <div className="column-header-left namespace-name-header">
- Namespace Name
- </div>
- ),
- dataIndex: 'namespaceName',
- key: 'namespaceName',
- ellipsis: true,
- width: 80,
- sorter: false,
- align: 'left',
- },
- {
- title: <div className="column-header small-col">Successful</div>,
- dataIndex: 'successful_pods',
- key: 'successful_pods',
- ellipsis: true,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header small-col">Failed</div>,
- dataIndex: 'failed_pods',
- key: 'failed_pods',
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header small-col">Desired Successful</div>,
- dataIndex: 'desired_successful_pods',
- key: 'desired_successful_pods',
- ellipsis: true,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header small-col">Active</div>,
- dataIndex: 'active_pods',
- key: 'active_pods',
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">CPU Req Usage (%)</div>,
- dataIndex: 'cpu_request',
- key: 'cpu_request',
- width: 180,
- ellipsis: true,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">CPU Limit Usage (%)</div>,
- dataIndex: 'cpu_limit',
- key: 'cpu_limit',
- width: 120,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header small-col">CPU Usage (cores)</div>,
- dataIndex: 'cpu',
- key: 'cpu',
- width: 80,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">Mem Req Usage (%)</div>,
- dataIndex: 'memory_request',
- key: 'memory_request',
- width: 120,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">Mem Limit Usage (%)</div>,
- dataIndex: 'memory_limit',
- key: 'memory_limit',
- width: 120,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header small-col">Mem Usage (WSS)</div>,
- dataIndex: 'memory',
- key: 'memory',
- width: 120,
- ellipsis: true,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
-];
-
-export const getK8sJobsListColumns = (
- groupBy: IBuilderQuery['groupBy'],
-): ColumnType<K8sJobsRowData>[] => {
- if (groupBy.length > 0) {
- const filteredColumns = [...columnsConfig].filter(
- (column) => column.key !== 'jobName',
- );
- filteredColumns.unshift(jobGroupColumnConfig);
- return filteredColumns as ColumnType<K8sJobsRowData>[];
- }
-
- return columnsConfig as ColumnType<K8sJobsRowData>[];
-};
-
-const dotToUnder: Record<string, keyof K8sJobsData['meta']> = {
- 'k8s.job.name': 'k8s_job_name',
- 'k8s.namespace.name': 'k8s_namespace_name',
- 'k8s.cluster.name': 'k8s_cluster_name',
-};
-
-const getGroupByEle = (
- job: K8sJobsData,
- groupBy: IBuilderQuery['groupBy'],
-): React.ReactNode => {
- const groupByValues: string[] = [];
-
- groupBy.forEach((group) => {
- const rawKey = group.key as string;
-
- // Choose mapped key if present, otherwise use rawKey
- const metaKey = (dotToUnder[rawKey] ?? rawKey) as keyof typeof job.meta;
- const value = job.meta[metaKey];
-
- groupByValues.push(value);
- });
-
- return (
- <div className="pod-group">
- {groupByValues.map((value) => (
- <Tag key={value} color={Color.BG_SLATE_400} className="pod-group-tag-item">
- {value === '' ? '<no-value>' : value}
- </Tag>
- ))}
- </div>
- );
-};
-
-export const formatDataForTable = (
- data: K8sJobsData[],
- groupBy: IBuilderQuery['groupBy'],
-): K8sJobsRowData[] =>
- data.map((job, index) => ({
- key: index.toString(),
- jobUID: job.jobName,
- jobName: (
- <Tooltip title={job.meta.k8s_job_name}>
- {job.meta.k8s_job_name || ''}
- </Tooltip>
- ),
- namespaceName: (
- <Tooltip title={job.meta.k8s_namespace_name}>
- {job.meta.k8s_namespace_name || ''}
- </Tooltip>
- ),
- cpu_request: (
- <ValidateColumnValueWrapper
- value={job.cpuRequest}
- entity={K8sCategory.JOBS}
- attribute="CPU Request"
- >
- <div className="progress-container">
- <EntityProgressBar value={job.cpuRequest} type="request" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- cpu_limit: (
- <ValidateColumnValueWrapper
- value={job.cpuLimit}
- entity={K8sCategory.JOBS}
- attribute="CPU Limit"
- >
- <div className="progress-container">
- <EntityProgressBar value={job.cpuLimit} type="limit" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- cpu: (
- <ValidateColumnValueWrapper value={job.cpuUsage}>
- {job.cpuUsage}
- </ValidateColumnValueWrapper>
- ),
- memory_request: (
- <ValidateColumnValueWrapper
- value={job.memoryRequest}
- entity={K8sCategory.JOBS}
- attribute="Memory Request"
- >
- <div className="progress-container">
- <EntityProgressBar value={job.memoryRequest} type="request" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- memory_limit: (
- <ValidateColumnValueWrapper
- value={job.memoryLimit}
- entity={K8sCategory.JOBS}
- attribute="Memory Limit"
- >
- <div className="progress-container">
- <EntityProgressBar value={job.memoryLimit} type="limit" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- memory: (
- <ValidateColumnValueWrapper value={job.memoryUsage}>
- {formatBytes(job.memoryUsage)}
- </ValidateColumnValueWrapper>
- ),
- successful_pods: (
- <ValidateColumnValueWrapper value={job.successfulPods}>
- {job.successfulPods}
- </ValidateColumnValueWrapper>
- ),
- desired_successful_pods: (
- <ValidateColumnValueWrapper value={job.desiredSuccessfulPods}>
- {job.desiredSuccessfulPods}
- </ValidateColumnValueWrapper>
- ),
- failed_pods: (
- <ValidateColumnValueWrapper value={job.failedPods}>
- {job.failedPods}
- </ValidateColumnValueWrapper>
- ),
- active_pods: (
- <ValidateColumnValueWrapper value={job.activePods}>
- {job.activePods}
- </ValidateColumnValueWrapper>
- ),
- jobGroup: getGroupByEle(job, groupBy),
- meta: job.meta,
- ...job.meta,
- groupedByMeta: job.meta,
- }));
diff --git a/frontend/src/container/InfraMonitoringK8s/K8sEmptyOrIncorrectMetrics.tsx b/frontend/src/container/InfraMonitoringK8s/K8sEmptyOrIncorrectMetrics.tsx
index 67a7f4e3c8..e69de29bb2 100644
--- a/frontend/src/container/InfraMonitoringK8s/K8sEmptyOrIncorrectMetrics.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/K8sEmptyOrIncorrectMetrics.tsx
@@ -1,34 +0,0 @@
-import { Typography } from 'antd';
-
-import eyesEmojiUrl from '@/assets/Images/eyesEmoji.svg';
-
-export default function HostsEmptyOrIncorrectMetrics({
- noData,
- incorrectData,
-}: {
- noData: boolean;
- incorrectData: boolean;
-}): JSX.Element {
- return (
- <div className="hosts-empty-state-container">
- <div className="hosts-empty-state-container-content">
- <img className="eyes-emoji" src={eyesEmojiUrl} alt="eyes emoji" />
-
- {noData && (
- <div className="no-hosts-message">
- <Typography.Title level={5} className="no-hosts-message-title">
- No data received yet.
- </Typography.Title>
- </div>
- )}
-
- {incorrectData && (
- <Typography.Text className="incorrect-metrics-message">
- To see data, upgrade to the latest version of SigNoz k8s-infra chart.
- Please contact support if you need help.
- </Typography.Text>
- )}
- </div>
- </div>
- );
-}
diff --git a/frontend/src/container/InfraMonitoringK8s/K8sFiltersSidePanel/K8sFiltersSidePanel.styles.scss b/frontend/src/container/InfraMonitoringK8s/K8sFiltersSidePanel/K8sFiltersSidePanel.styles.scss
deleted file mode 100644
index 8607360c2e..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/K8sFiltersSidePanel/K8sFiltersSidePanel.styles.scss
+++ /dev/null
@@ -1,114 +0,0 @@
-.k8s-filters-side-panel-container {
- position: absolute;
- width: 100%;
- height: 100vh;
- background-color: rgba(0, 0, 0, 0.2);
- top: 0;
- left: 0;
- z-index: 10;
-}
-
-.k8s-filters-side-panel {
- border-radius: 4px;
- border: 1px solid var(--l1-border);
- background: var(--l2-background);
- box-shadow: -4px 10px 16px 2px rgba(0, 0, 0, 0.2);
-
- height: 88vh;
-
- position: absolute;
- width: 320px;
- right: 4px;
- top: 48px;
- z-index: 2;
-
- .k8s-filters-side-panel-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 8px;
- height: 40px;
-
- .k8s-filters-side-panel-header-title {
- display: flex;
- align-items: center;
- gap: 8px;
- }
- }
-
- .k8s-filters-side-panel-body {
- height: calc(100% - 40px);
-
- .k8s-filters-side-panel-body-header {
- border: 1px solid var(--l3-background);
- border-left: none;
- border-right: none;
-
- .ant-input {
- height: 40px;
- }
- }
-
- .k8s-filters-side-panel-body-content {
- display: flex;
- flex-direction: column;
-
- .added-columns,
- .available-columns {
- padding: 8px;
-
- .filter-columns-title {
- color: var(--muted-foreground);
- font-family: Inter;
- font-size: 11px;
- font-style: normal;
- font-weight: 500;
- line-height: 18px; /* 163.636% */
- letter-spacing: 0.88px;
- text-transform: uppercase;
-
- padding: 8px 12px;
- margin-bottom: 8px;
- }
-
- .added-columns-list,
- .available-columns-list {
- display: flex;
- flex-direction: column;
- gap: 8px;
-
- .added-column-item,
- .available-column-item {
- color: var(--l1-foreground);
- font-family: Inter;
- font-size: 12px;
- font-style: normal;
- font-weight: 400;
- line-height: 20px; /* 142.857% */
- letter-spacing: -0.07px;
-
- padding: 4px 0px 4px 12px;
-
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 8px;
-
- cursor: pointer;
- }
-
- .added-column-item-content,
- .available-column-item-content {
- display: flex;
- align-items: center;
- gap: 8px;
- }
- }
- }
-
- .horizontal-divider {
- border-top: 1px solid var(--l3-background);
- }
- }
- }
-}
diff --git a/frontend/src/container/InfraMonitoringK8s/K8sFiltersSidePanel/K8sFiltersSidePanel.tsx b/frontend/src/container/InfraMonitoringK8s/K8sFiltersSidePanel/K8sFiltersSidePanel.tsx
deleted file mode 100644
index bc7a451678..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/K8sFiltersSidePanel/K8sFiltersSidePanel.tsx
+++ /dev/null
@@ -1,146 +0,0 @@
-/* eslint-disable @typescript-eslint/explicit-function-return-type */
-import { useEffect, useRef, useState } from 'react';
-import { Button, Input } from 'antd';
-import { GripVertical, TableColumnsSplit, X } from 'lucide-react';
-
-import { IEntityColumn } from '../utils';
-
-import './K8sFiltersSidePanel.styles.scss';
-
-function K8sFiltersSidePanel({
- defaultAddedColumns,
- onClose,
- addedColumns = [],
- availableColumns = [],
- onAddColumn = () => {},
- onRemoveColumn = () => {},
-}: {
- defaultAddedColumns: IEntityColumn[];
- onClose: () => void;
- addedColumns?: IEntityColumn[];
- availableColumns?: IEntityColumn[];
- onAddColumn?: (column: IEntityColumn) => void;
- onRemoveColumn?: (column: IEntityColumn) => void;
-}): JSX.Element {
- const [searchValue, setSearchValue] = useState('');
- const sidePanelRef = useRef<HTMLDivElement>(null);
-
- const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
- setSearchValue(e.target.value);
- };
-
- useEffect(() => {
- if (sidePanelRef.current) {
- sidePanelRef.current.focus();
- }
- }, [searchValue]);
-
- // Close side panel when clicking outside of it
- useEffect(() => {
- const handleClickOutside = (event: MouseEvent) => {
- if (
- sidePanelRef.current &&
- !sidePanelRef.current.contains(event.target as Node)
- ) {
- onClose();
- }
- };
-
- document.addEventListener('mousedown', handleClickOutside);
-
- return () => {
- document.removeEventListener('mousedown', handleClickOutside);
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- return (
- <div className="k8s-filters-side-panel-container">
- <div className="k8s-filters-side-panel" ref={sidePanelRef}>
- <div className="k8s-filters-side-panel-header">
- <span className="k8s-filters-side-panel-header-title">
- <TableColumnsSplit size={16} /> Columns
- </span>
-
- <Button
- className="periscope-btn ghost"
- icon={<X size={14} strokeWidth={1.5} onClick={onClose} />}
- />
- </div>
-
- <div className="k8s-filters-side-panel-body">
- <div className="k8s-filters-side-panel-body-header">
- <Input
- autoFocus
- className="periscope-input borderless"
- placeholder="Search for a column ..."
- value={searchValue}
- onChange={handleSearchChange}
- />
- </div>
-
- <div className="k8s-filters-side-panel-body-content">
- <div className="added-columns">
- <div className="filter-columns-title">Added Columns</div>
-
- <div className="added-columns-list">
- {[...defaultAddedColumns, ...addedColumns]
- .filter((column) =>
- column.label.toLowerCase().includes(searchValue.toLowerCase()),
- )
- .map((column) => (
- <div className="added-column-item" key={column.value}>
- <div className="added-column-item-content">
- <GripVertical size={16} /> {column.label}
- </div>
-
- {column.canRemove && (
- <X
- size={14}
- strokeWidth={1.5}
- onClick={(): void => onRemoveColumn(column)}
- />
- )}
- </div>
- ))}
- </div>
- </div>
-
- <div className="horizontal-divider" />
-
- <div className="available-columns">
- <div className="filter-columns-title">Other Columns</div>
-
- <div className="available-columns-list">
- {availableColumns
- .filter((column) =>
- column.label.toLowerCase().includes(searchValue.toLowerCase()),
- )
- .map((column) => (
- <div
- className="available-column-item"
- key={column.value}
- onClick={(): void => onAddColumn(column)}
- >
- <div className="available-column-item-content">
- <GripVertical size={16} /> {column.label}
- </div>
- </div>
- ))}
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- );
-}
-
-K8sFiltersSidePanel.defaultProps = {
- addedColumns: [],
- availableColumns: [],
- onAddColumn: () => {},
- onRemoveColumn: () => {},
-};
-
-export default K8sFiltersSidePanel;
diff --git a/frontend/src/container/InfraMonitoringK8s/K8sHeader.tsx b/frontend/src/container/InfraMonitoringK8s/K8sHeader.tsx
deleted file mode 100644
index 95cd29d3aa..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/K8sHeader.tsx
+++ /dev/null
@@ -1,175 +0,0 @@
-/* eslint-disable @typescript-eslint/explicit-function-return-type */
-import { useCallback, useMemo, useState } from 'react';
-import { Button, Select } from 'antd';
-import { initialQueriesMap } from 'constants/queryBuilder';
-import QueryBuilderSearch from 'container/QueryBuilder/filters/QueryBuilderSearch';
-import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
-import { Filter, SlidersHorizontal } from 'lucide-react';
-import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { DataSource } from 'types/common/queryBuilder';
-
-import { K8sCategory } from './constants';
-import { useInfraMonitoringFiltersK8s } from './hooks';
-import K8sFiltersSidePanel from './K8sFiltersSidePanel/K8sFiltersSidePanel';
-import { IEntityColumn } from './utils';
-
-import './InfraMonitoringK8s.styles.scss';
-
-interface K8sHeaderProps {
- selectedGroupBy: BaseAutocompleteData[];
- groupByOptions: { value: string; label: string }[];
- isLoadingGroupByFilters: boolean;
- handleFiltersChange: (value: IBuilderQuery['filters']) => void;
- handleGroupByChange: (value: IBuilderQuery['groupBy']) => void;
- defaultAddedColumns: IEntityColumn[];
- addedColumns?: IEntityColumn[];
- availableColumns?: IEntityColumn[];
- onAddColumn?: (column: IEntityColumn) => void;
- onRemoveColumn?: (column: IEntityColumn) => void;
- handleFilterVisibilityChange: () => void;
- isFiltersVisible: boolean;
- entity: K8sCategory;
- showAutoRefresh: boolean;
-}
-
-function K8sHeader({
- selectedGroupBy,
- defaultAddedColumns,
- groupByOptions,
- isLoadingGroupByFilters,
- addedColumns,
- availableColumns,
- handleFiltersChange,
- handleGroupByChange,
- onAddColumn,
- onRemoveColumn,
- handleFilterVisibilityChange,
- isFiltersVisible,
- entity,
- showAutoRefresh,
-}: K8sHeaderProps): JSX.Element {
- const [isFiltersSidePanelOpen, setIsFiltersSidePanelOpen] = useState(false);
- const [urlFilters, setUrlFilters] = useInfraMonitoringFiltersK8s();
-
- const currentQuery = initialQueriesMap[DataSource.METRICS];
-
- const updatedCurrentQuery = useMemo(() => {
- let { filters } = currentQuery.builder.queryData[0];
- if (urlFilters) {
- filters = urlFilters;
- }
- return {
- ...currentQuery,
- builder: {
- ...currentQuery.builder,
- queryData: [
- {
- ...currentQuery.builder.queryData[0],
- aggregateOperator: 'noop',
- aggregateAttribute: {
- ...currentQuery.builder.queryData[0].aggregateAttribute,
- },
- filters,
- },
- ],
- },
- };
- }, [currentQuery, urlFilters]);
-
- const query = updatedCurrentQuery?.builder?.queryData[0] || null;
-
- const handleChangeTagFilters = useCallback(
- (value: IBuilderQuery['filters']) => {
- handleFiltersChange(value);
- setUrlFilters(value || null);
- },
- [handleFiltersChange, setUrlFilters],
- );
-
- return (
- <div className="k8s-list-controls">
- <div className="k8s-list-controls-left">
- {!isFiltersVisible && (
- <div className="quick-filters-toggle-container">
- <Button
- className="periscope-btn ghost"
- type="text"
- size="small"
- onClick={handleFilterVisibilityChange}
- >
- <Filter size={14} />
- </Button>
- </div>
- )}
-
- <div className="k8s-qb-search-container">
- <QueryBuilderSearch
- query={query as IBuilderQuery}
- onChange={handleChangeTagFilters}
- isInfraMonitoring
- disableNavigationShortcuts
- entity={entity}
- />
- </div>
-
- <div className="k8s-attribute-search-container">
- <div className="group-by-label"> Group by </div>
- <Select
- className="group-by-select"
- loading={isLoadingGroupByFilters}
- mode="multiple"
- value={selectedGroupBy}
- allowClear
- maxTagCount="responsive"
- placeholder="Search for attribute"
- style={{ width: '100%' }}
- options={groupByOptions}
- onChange={handleGroupByChange}
- />
- </div>
- </div>
-
- <div className="k8s-list-controls-right">
- <DateTimeSelectionV2
- showAutoRefresh={showAutoRefresh}
- showRefreshText={false}
- hideShareModal
- />
-
- <Button
- type="text"
- className="periscope-btn ghost"
- disabled={selectedGroupBy?.length > 0}
- onClick={(): void => setIsFiltersSidePanelOpen(true)}
- >
- <SlidersHorizontal size={14} />
- </Button>
- </div>
-
- {isFiltersSidePanelOpen && (
- <K8sFiltersSidePanel
- defaultAddedColumns={defaultAddedColumns}
- addedColumns={addedColumns}
- availableColumns={availableColumns}
- onClose={(): void => {
- if (isFiltersSidePanelOpen) {
- setIsFiltersSidePanelOpen(false);
- }
- }}
- onAddColumn={onAddColumn}
- onRemoveColumn={onRemoveColumn}
- />
- )}
- </div>
- );
-}
-
-K8sHeader.defaultProps = {
- addedColumns: [],
- availableColumns: [],
- onAddColumn: () => {},
- onRemoveColumn: () => {},
-};
-
-export default K8sHeader;
diff --git a/frontend/src/container/InfraMonitoringK8s/LoadingContainer.module.scss b/frontend/src/container/InfraMonitoringK8s/LoadingContainer.module.scss
new file mode 100644
index 0000000000..89eb1ac42d
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/LoadingContainer.module.scss
@@ -0,0 +1,11 @@
+.loadingState {
+ padding: 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.loadingStateItem {
+ height: 48px;
+ width: 100%;
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/LoadingContainer.tsx b/frontend/src/container/InfraMonitoringK8s/LoadingContainer.tsx
index e0d92c5e19..b0601e3878 100644
--- a/frontend/src/container/InfraMonitoringK8s/LoadingContainer.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/LoadingContainer.tsx
@@ -1,24 +1,24 @@
import { Skeleton } from 'antd';
-import './InfraMonitoringK8s.styles.scss';
+import styles from './LoadingContainer.module.scss';
function LoadingContainer(): JSX.Element {
return (
- <div className="k8s-list-loading-state" data-testid="loader">
+ <div className={styles.loadingState} data-testid="loader">
<Skeleton.Input
- className="k8s-list-loading-state-item"
+ className={styles.loadingStateItem}
size="large"
block
active
/>
<Skeleton.Input
- className="k8s-list-loading-state-item"
+ className={styles.loadingStateItem}
size="large"
block
active
/>
<Skeleton.Input
- className="k8s-list-loading-state-item"
+ className={styles.loadingStateItem}
size="large"
block
active
diff --git a/frontend/src/container/InfraMonitoringK8s/Namespaces/K8sNamespacesList.styles.scss b/frontend/src/container/InfraMonitoringK8s/Namespaces/K8sNamespacesList.styles.scss
deleted file mode 100644
index 9181a24e21..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Namespaces/K8sNamespacesList.styles.scss
+++ /dev/null
@@ -1,17 +0,0 @@
-.infra-monitoring-container {
- .namespaces-list-table {
- .expanded-table-container {
- padding-left: 80px;
- }
-
- .ant-table-cell {
- min-width: 223px !important;
- max-width: 223px !important;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
- }
-}
diff --git a/frontend/src/container/InfraMonitoringK8s/Namespaces/K8sNamespacesList.tsx b/frontend/src/container/InfraMonitoringK8s/Namespaces/K8sNamespacesList.tsx
index d45ac08b4a..07fdc2e0bd 100644
--- a/frontend/src/container/InfraMonitoringK8s/Namespaces/K8sNamespacesList.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/Namespaces/K8sNamespacesList.tsx
@@ -1,718 +1,118 @@
-import React, { useCallback, useEffect, useMemo, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { LoadingOutlined } from '@ant-design/icons';
-import {
- Button,
- Spin,
- Table,
- TableColumnType as ColumnType,
- TablePaginationConfig,
- TableProps,
- Typography,
-} from 'antd';
-import type { SorterResult } from 'antd/es/table/interface';
-import logEvent from 'api/common/logEvent';
-import { K8sNamespacesListPayload } from 'api/infraMonitoring/getK8sNamespacesList';
+import React, { useCallback } from 'react';
import { InfraMonitoringEvents } from 'constants/events';
import { FeatureKeys } from 'constants/features';
-import { useGetK8sNamespacesList } from 'hooks/infraMonitoring/useGetK8sNamespacesList';
-import { useGetAggregateKeys } from 'hooks/queryBuilder/useGetAggregateKeys';
-import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
-import { ChevronDown, ChevronRight } from 'lucide-react';
import { useAppContext } from 'providers/App/App';
-import { AppState } from 'store/reducers';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { buildAbsolutePath, isModifierKeyPressed } from 'utils/app';
-import { openInNewTab } from 'utils/navigation';
-
-import emptyStateUrl from '@/assets/Icons/emptyState.svg';
+import K8sBaseDetails, { K8sDetailsFilters } from '../Base/K8sBaseDetails';
+import { K8sBaseList } from '../Base/K8sBaseList';
+import { K8sBaseFilters } from '../Base/types';
+import { InfraMonitoringEntity } from '../constants';
+import { getK8sNamespacesList, K8sNamespacesData } from './api';
import {
- GetK8sEntityToAggregateAttribute,
- INFRA_MONITORING_K8S_PARAMS_KEYS,
- K8sCategory,
-} from '../constants';
-import {
- useInfraMonitoringCurrentPage,
- useInfraMonitoringEventsFilters,
- useInfraMonitoringGroupBy,
- useInfraMonitoringLogFilters,
- useInfraMonitoringNamespaceUID,
- useInfraMonitoringOrderBy,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from '../hooks';
-import K8sHeader from '../K8sHeader';
-import LoadingContainer from '../LoadingContainer';
-import { usePageSize } from '../utils';
-import NamespaceDetails from './NamespaceDetails';
+ getNamespaceMetricsQueryPayload,
+ k8sNamespaceDetailsMetadataConfig,
+ k8sNamespaceGetEntityName,
+ k8sNamespaceGetSelectedItemFilters,
+ k8sNamespaceInitialEventsFilter,
+ k8sNamespaceInitialFilters,
+ k8sNamespaceInitialLogTracesFilter,
+ namespaceWidgetInfo,
+} from './constants';
import {
- defaultAddedColumns,
- formatDataForTable,
- getK8sNamespacesListColumns,
- getK8sNamespacesListQuery,
- K8sNamespacesRowData,
-} from './utils';
-
-import '../InfraMonitoringK8s.styles.scss';
-import './K8sNamespacesList.styles.scss';
+ k8sNamespacesColumns,
+ k8sNamespacesColumnsConfig,
+ k8sNamespacesRenderRowData,
+} from './table.config';
function K8sNamespacesList({
- isFiltersVisible,
- handleFilterVisibilityChange,
- quickFiltersLastUpdated,
+ controlListPrefix,
}: {
- isFiltersVisible: boolean;
- handleFilterVisibilityChange: () => void;
- quickFiltersLastUpdated: number;
+ controlListPrefix?: React.ReactNode;
}): JSX.Element {
- const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
- (state) => state.globalTime,
- );
-
- const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
-
- const [currentPage, setCurrentPage] = useInfraMonitoringCurrentPage();
- const [filtersInitialised, setFiltersInitialised] = useState(false);
-
- const [orderBy, setOrderBy] = useInfraMonitoringOrderBy();
-
- const [
- selectedNamespaceUID,
- setselectedNamespaceUID,
- ] = useInfraMonitoringNamespaceUID();
-
- const { pageSize, setPageSize } = usePageSize(K8sCategory.NAMESPACES);
-
- const [groupBy, setGroupBy] = useInfraMonitoringGroupBy();
-
- const [, setView] = useInfraMonitoringView();
- const [, setTracesFilters] = useInfraMonitoringTracesFilters();
- const [, setEventsFilters] = useInfraMonitoringEventsFilters();
- const [, setLogFilters] = useInfraMonitoringLogFilters();
-
- const [
- selectedRowData,
- setSelectedRowData,
- ] = useState<K8sNamespacesRowData | null>(null);
-
- const [groupByOptions, setGroupByOptions] = useState<
- { value: string; label: string }[]
- >([]);
-
- const { currentQuery } = useQueryBuilder();
-
- const queryFilters = useMemo(
- () =>
- currentQuery?.builder?.queryData[0]?.filters || {
- items: [],
- op: 'and',
- },
- [currentQuery?.builder?.queryData],
- );
-
- // Reset pagination every time quick filters are changed
- useEffect(() => {
- if (quickFiltersLastUpdated !== -1) {
- setCurrentPage(1);
- }
- }, [quickFiltersLastUpdated, setCurrentPage]);
-
const { featureFlags } = useAppContext();
const dotMetricsEnabled =
featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
?.active || false;
- const createFiltersForSelectedRowData = (
- selectedRowData: K8sNamespacesRowData,
- groupBy: IBuilderQuery['groupBy'],
- ): IBuilderQuery['filters'] => {
- const baseFilters: IBuilderQuery['filters'] = {
- items: [...queryFilters.items],
- op: 'and',
- };
-
- if (!selectedRowData) {
- return baseFilters;
- }
-
- const { groupedByMeta } = selectedRowData;
-
- for (const key of groupBy) {
- baseFilters.items.push({
- key: {
- key: key.key,
- type: null,
- },
- op: '=',
- value: groupedByMeta[key.key],
- id: key.key,
- });
- }
-
- return baseFilters;
- };
-
- const fetchGroupedByRowDataQuery = useMemo(() => {
- if (!selectedRowData) {
- return null;
- }
-
- const baseQuery = getK8sNamespacesListQuery();
-
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- return {
- ...baseQuery,
- limit: 10,
- offset: 0,
- filters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [minTime, maxTime, orderBy, selectedRowData, groupBy]);
-
- const groupedByRowDataQueryKey = useMemo(() => {
- // be careful with what you serialize from selectedRowData
- // since it's react node, it could contain circular references
- const selectedRowDataKey = JSON.stringify(selectedRowData?.groupedByMeta);
- if (selectedNamespaceUID) {
- return [
- 'namespaceList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- ];
- }
- return [
- 'namespaceList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- String(minTime),
- String(maxTime),
- ];
- }, [
- queryFilters,
- orderBy,
- selectedNamespaceUID,
- minTime,
- maxTime,
- selectedRowData,
- ]);
-
- const {
- data: groupedByRowData,
- isFetching: isFetchingGroupedByRowData,
- isLoading: isLoadingGroupedByRowData,
- isError: isErrorGroupedByRowData,
- refetch: fetchGroupedByRowData,
- } = useGetK8sNamespacesList(
- fetchGroupedByRowDataQuery as K8sNamespacesListPayload,
- {
- queryKey: groupedByRowDataQueryKey,
- enabled: !!fetchGroupedByRowDataQuery && !!selectedRowData,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const {
- data: groupByFiltersData,
- isLoading: isLoadingGroupByFilters,
- } = useGetAggregateKeys(
- {
- dataSource: currentQuery.builder.queryData[0].dataSource,
- aggregateAttribute: GetK8sEntityToAggregateAttribute(
- K8sCategory.NAMESPACES,
+ const fetchListData = useCallback(
+ async (filters: K8sBaseFilters, signal?: AbortSignal) => {
+ filters.orderBy ||= {
+ columnName: 'cpu',
+ order: 'desc',
+ };
+
+ const response = await getK8sNamespacesList(
+ filters,
+ signal,
+ undefined,
dotMetricsEnabled,
- ),
- aggregateOperator: 'noop',
- searchText: '',
- tagType: '',
- },
- {
- queryKey: [currentQuery.builder.queryData[0].dataSource, 'noop'],
- },
- true,
- K8sCategory.NODES,
- );
-
- const query = useMemo(() => {
- const baseQuery = getK8sNamespacesListQuery();
- const queryPayload = {
- ...baseQuery,
- limit: pageSize,
- offset: (currentPage - 1) * pageSize,
- filters: queryFilters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- if (groupBy.length > 0) {
- queryPayload.groupBy = groupBy;
- }
- return queryPayload;
- }, [pageSize, currentPage, queryFilters, minTime, maxTime, orderBy, groupBy]);
-
- const formattedGroupedByNamespacesData = useMemo(
- () =>
- formatDataForTable(groupedByRowData?.payload?.data?.records || [], groupBy),
- [groupedByRowData, groupBy],
- );
-
- const queryKey = useMemo(() => {
- if (selectedNamespaceUID) {
- return [
- 'namespaceList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- ];
- }
- return [
- 'namespaceList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- String(minTime),
- String(maxTime),
- ];
- }, [
- selectedNamespaceUID,
- pageSize,
- currentPage,
- queryFilters,
- orderBy,
- groupBy,
- minTime,
- maxTime,
- ]);
-
- const { data, isFetching, isLoading, isError } = useGetK8sNamespacesList(
- query as K8sNamespacesListPayload,
- {
- queryKey,
- enabled: !!query,
- keepPreviousData: true,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const namespacesData = useMemo(() => data?.payload?.data?.records || [], [
- data,
- ]);
- const totalCount = data?.payload?.data?.total || 0;
-
- const formattedNamespacesData = useMemo(
- () => formatDataForTable(namespacesData, groupBy),
- [namespacesData, groupBy],
- );
-
- const nestedNamespacesData = useMemo(() => {
- if (!selectedRowData || !groupedByRowData?.payload?.data.records) {
- return [];
- }
- return groupedByRowData?.payload?.data?.records || [];
- }, [groupedByRowData, selectedRowData]);
-
- const columns = useMemo(() => getK8sNamespacesListColumns(groupBy), [groupBy]);
-
- const handleGroupByRowClick = (record: K8sNamespacesRowData): void => {
- setSelectedRowData(record);
-
- if (expandedRowKeys.includes(record.key)) {
- setExpandedRowKeys(expandedRowKeys.filter((key) => key !== record.key));
- } else {
- setExpandedRowKeys([record.key]);
- }
- };
-
- useEffect(() => {
- if (selectedRowData) {
- fetchGroupedByRowData();
- }
- }, [selectedRowData, fetchGroupedByRowData]);
-
- const handleTableChange: TableProps<K8sNamespacesRowData>['onChange'] = useCallback(
- (
- pagination: TablePaginationConfig,
- _filters: Record<string, (string | number | boolean)[] | null>,
- sorter:
- | SorterResult<K8sNamespacesRowData>
- | SorterResult<K8sNamespacesRowData>[],
- ): void => {
- if (pagination.current) {
- setCurrentPage(pagination.current);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Namespace,
- });
- }
-
- if ('field' in sorter && sorter.order) {
- setOrderBy({
- columnName: sorter.field as string,
- order: (sorter.order === 'ascend' ? 'asc' : 'desc') as 'asc' | 'desc',
- });
- } else {
- setOrderBy(null);
- }
- },
- [setCurrentPage, setOrderBy],
- );
-
- const { handleChangeQueryData } = useQueryOperations({
- index: 0,
- query: currentQuery.builder.queryData[0],
- entityVersion: '',
- });
-
- const handleFiltersChange = useCallback(
- (value: IBuilderQuery['filters']): void => {
- handleChangeQueryData('filters', value);
- if (filtersInitialised) {
- setCurrentPage(1);
- } else {
- setFiltersInitialised(true);
- }
+ );
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Namespace,
- });
- }
+ return {
+ data: response.payload?.data.records || [],
+ total: response.payload?.data.total || 0,
+ error: response.error,
+ rawData: response.payload?.data,
+ };
},
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Namespace,
- total: data?.payload?.data?.total,
- });
- }, [data?.payload?.data?.total]);
-
- const selectedNamespaceData = useMemo(() => {
- if (!selectedNamespaceUID) {
- return null;
- }
- if (groupBy.length > 0) {
- // If grouped by, return the namespace from the formatted grouped by namespaces data
- return (
- nestedNamespacesData.find(
- (namespace) => namespace.namespaceName === selectedNamespaceUID,
- ) || null
+ const fetchEntityData = useCallback(
+ async (
+ filters: K8sDetailsFilters,
+ signal?: AbortSignal,
+ ): Promise<{ data: K8sNamespacesData | null; error?: string | null }> => {
+ const response = await getK8sNamespacesList(
+ {
+ filters: filters.filters,
+ start: filters.start,
+ end: filters.end,
+ limit: 1,
+ offset: 0,
+ },
+ signal,
+ undefined,
+ dotMetricsEnabled,
);
- }
- // If not grouped by, return the node from the nodes data
- return (
- namespacesData.find(
- (namespace) => namespace.namespaceName === selectedNamespaceUID,
- ) || null
- );
- }, [
- selectedNamespaceUID,
- groupBy.length,
- namespacesData,
- nestedNamespacesData,
- ]);
-
- const openNamespaceInNewTab = (record: K8sNamespacesRowData): void => {
- const newParams = new URLSearchParams(document.location.search);
- newParams.set(
- INFRA_MONITORING_K8S_PARAMS_KEYS.NAMESPACE_UID,
- record.namespaceUID,
- );
- openInNewTab(
- buildAbsolutePath({
- relativePath: '',
- urlQueryString: newParams.toString(),
- }),
- );
- };
-
- const handleRowClick = (
- record: K8sNamespacesRowData,
- event: React.MouseEvent,
- ): void => {
- if (event && isModifierKeyPressed(event)) {
- openNamespaceInNewTab(record);
- return;
- }
- if (groupBy.length === 0) {
- setSelectedRowData(null);
- setselectedNamespaceUID(record.namespaceUID);
- } else {
- handleGroupByRowClick(record);
- }
-
- logEvent(InfraMonitoringEvents.ItemClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Namespace,
- });
- };
-
- const nestedColumns = useMemo(() => getK8sNamespacesListColumns([]), []);
- const isGroupedByAttribute = groupBy.length > 0;
+ const records = response.payload?.data.records || [];
- const handleExpandedRowViewAllClick = (): void => {
- if (!selectedRowData) {
- return;
- }
-
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- handleFiltersChange(filters);
-
- setCurrentPage(1);
- setSelectedRowData(null);
- setGroupBy([]);
- setOrderBy(null);
- };
-
- const expandedRowRender = (): JSX.Element => (
- <div className="expanded-table-container">
- {isErrorGroupedByRowData && (
- <Typography>{groupedByRowData?.error || 'Something went wrong'}</Typography>
- )}
- {isFetchingGroupedByRowData || isLoadingGroupedByRowData ? (
- <LoadingContainer />
- ) : (
- <div className="expanded-table">
- <Table
- columns={nestedColumns as ColumnType<K8sNamespacesRowData>[]}
- dataSource={formattedGroupedByNamespacesData}
- pagination={false}
- scroll={{ x: true }}
- tableLayout="fixed"
- size="small"
- loading={{
- spinning: isFetchingGroupedByRowData || isLoadingGroupedByRowData,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- showHeader={false}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => {
- if (isModifierKeyPressed(event)) {
- openNamespaceInNewTab(record);
- return;
- }
- setselectedNamespaceUID(record.namespaceUID);
- },
- className: 'expanded-clickable-row',
- })}
- />
-
- {groupedByRowData?.payload?.data?.total &&
- groupedByRowData?.payload?.data?.total > 10 ? (
- <div className="expanded-table-footer">
- <Button
- type="default"
- size="small"
- className="periscope-btn secondary"
- onClick={handleExpandedRowViewAllClick}
- >
- View All
- </Button>
- </div>
- ) : null}
- </div>
- )}
- </div>
- );
-
- const expandRowIconRenderer = ({
- expanded,
- onExpand,
- record,
- }: {
- expanded: boolean;
- onExpand: (
- record: K8sNamespacesRowData,
- e: React.MouseEvent<HTMLButtonElement>,
- ) => void;
- record: K8sNamespacesRowData;
- }): JSX.Element | null => {
- if (!isGroupedByAttribute) {
- return null;
- }
-
- return expanded ? (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronDown size={14} />
- </Button>
- ) : (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronRight size={14} />
- </Button>
- );
- };
-
- const handleCloseNamespaceDetail = (): void => {
- setselectedNamespaceUID(null);
- setView(null);
- setTracesFilters(null);
- setEventsFilters(null);
- setLogFilters(null);
- };
-
- const handleGroupByChange = useCallback(
- (value: IBuilderQuery['groupBy']) => {
- const groupBy = [];
-
- for (let index = 0; index < value.length; index++) {
- const element = (value[index] as unknown) as string;
-
- const key = groupByFiltersData?.payload?.attributeKeys?.find(
- (key) => key.key === element,
- );
-
- if (key) {
- groupBy.push(key);
- }
- }
-
- // Reset pagination on switching to groupBy
- setCurrentPage(1);
- setGroupBy(groupBy);
- setExpandedRowKeys([]);
-
- logEvent(InfraMonitoringEvents.GroupByChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Namespace,
- });
+ return {
+ data: records.length > 0 ? records[0] : null,
+ error: response.error,
+ };
},
- [groupByFiltersData, setCurrentPage, setGroupBy],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- if (groupByFiltersData?.payload) {
- setGroupByOptions(
- groupByFiltersData?.payload?.attributeKeys?.map((filter) => ({
- value: filter.key,
- label: filter.key,
- })) || [],
- );
- }
- }, [groupByFiltersData]);
-
- const onPaginationChange = (page: number, pageSize: number): void => {
- setCurrentPage(page);
- setPageSize(pageSize);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Namespace,
- });
- };
-
- const showTableLoadingState =
- (isFetching || isLoading) && formattedNamespacesData.length === 0;
-
return (
- <div className="k8s-list">
- <K8sHeader
- isFiltersVisible={isFiltersVisible}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- defaultAddedColumns={defaultAddedColumns}
- handleFiltersChange={handleFiltersChange}
- groupByOptions={groupByOptions}
- isLoadingGroupByFilters={isLoadingGroupByFilters}
- handleGroupByChange={handleGroupByChange}
- selectedGroupBy={groupBy}
- entity={K8sCategory.NODES}
- showAutoRefresh={!selectedNamespaceData}
+ <>
+ <K8sBaseList<K8sNamespacesData>
+ controlListPrefix={controlListPrefix}
+ entity={InfraMonitoringEntity.NAMESPACES}
+ tableColumnsDefinitions={k8sNamespacesColumns}
+ tableColumns={k8sNamespacesColumnsConfig}
+ fetchListData={fetchListData}
+ renderRowData={k8sNamespacesRenderRowData}
+ eventCategory={InfraMonitoringEvents.Namespace}
/>
- {isError && <Typography>{data?.error || 'Something went wrong'}</Typography>}
- <Table
- className="k8s-list-table namespaces-list-table"
- dataSource={showTableLoadingState ? [] : formattedNamespacesData}
- columns={columns}
- pagination={{
- current: currentPage,
- pageSize,
- total: totalCount,
- showSizeChanger: true,
- hideOnSinglePage: false,
- onChange: onPaginationChange,
- }}
- scroll={{ x: true }}
- loading={{
- spinning: showTableLoadingState,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- locale={{
- emptyText: showTableLoadingState ? null : (
- <div className="no-filtered-hosts-message-container">
- <div className="no-filtered-hosts-message-content">
- <img
- src={emptyStateUrl}
- alt="thinking-emoji"
- className="empty-state-svg"
- />
-
- <Typography.Text className="no-filtered-hosts-message">
- This query had no results. Edit your query and try again!
- </Typography.Text>
- </div>
- </div>
- ),
- }}
- tableLayout="fixed"
- onChange={handleTableChange}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => handleRowClick(record, event),
- className: 'clickable-row',
- })}
- expandable={{
- expandedRowRender: isGroupedByAttribute ? expandedRowRender : undefined,
- expandIcon: expandRowIconRenderer,
- expandedRowKeys,
- }}
- />
- <NamespaceDetails
- namespace={selectedNamespaceData}
- isModalTimeSelection
- onClose={handleCloseNamespaceDetail}
+ <K8sBaseDetails<K8sNamespacesData>
+ category={InfraMonitoringEntity.NAMESPACES}
+ eventCategory={InfraMonitoringEvents.Namespace}
+ getSelectedItemFilters={k8sNamespaceGetSelectedItemFilters}
+ fetchEntityData={fetchEntityData}
+ getEntityName={k8sNamespaceGetEntityName}
+ getInitialLogTracesFilters={k8sNamespaceInitialLogTracesFilter}
+ getInitialEventsFilters={k8sNamespaceInitialEventsFilter}
+ primaryFilterKeys={k8sNamespaceInitialFilters}
+ metadataConfig={k8sNamespaceDetailsMetadataConfig}
+ entityWidgetInfo={namespaceWidgetInfo}
+ getEntityQueryPayload={getNamespaceMetricsQueryPayload}
+ queryKeyPrefix="namespace"
/>
- </div>
+ </>
);
}
diff --git a/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/NamespaceDetails.interfaces.ts b/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/NamespaceDetails.interfaces.ts
deleted file mode 100644
index d24c992bfc..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/NamespaceDetails.interfaces.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { K8sNamespacesData } from 'api/infraMonitoring/getK8sNamespacesList';
-
-export type NamespaceDetailsProps = {
- namespace: K8sNamespacesData | null;
- isModalTimeSelection: boolean;
- onClose: () => void;
-};
diff --git a/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/NamespaceDetails.styles.scss b/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/NamespaceDetails.styles.scss
deleted file mode 100644
index 430428be59..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/NamespaceDetails.styles.scss
+++ /dev/null
@@ -1,249 +0,0 @@
-.namespace-detail-drawer {
- border-left: 1px solid var(--l1-border);
- background: var(--l2-background);
- box-shadow: -4px 10px 16px 2px rgba(0, 0, 0, 0.2);
-
- .ant-drawer-header {
- padding: 8px 16px;
- border-bottom: none;
-
- align-items: stretch;
-
- border-bottom: 1px solid var(--l1-border);
- background: var(--l2-background);
- }
-
- .ant-drawer-close {
- margin-inline-end: 0px;
- }
-
- .ant-drawer-body {
- display: flex;
- flex-direction: column;
- padding: 16px;
- }
-
- .title {
- color: var(--l2-foreground);
- font-family: 'Geist Mono';
- font-size: 14px;
- font-style: normal;
- font-weight: 500;
- line-height: 20px; /* 142.857% */
- letter-spacing: -0.07px;
- }
-
- .radio-button {
- display: flex;
- align-items: center;
- justify-content: center;
- padding-top: var(--padding-1);
- border: 1px solid var(--l1-border);
- background: var(--l3-background);
- box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
- }
-
- .namespace-detail-drawer__namespace {
- .namespace-details-grid {
- .labels-row,
- .values-row {
- display: grid;
- grid-template-columns: 1fr 1.5fr 1.5fr 1.5fr;
- gap: 30px;
- align-items: center;
- }
-
- .labels-row {
- margin-bottom: 8px;
- }
-
- .namespace-details-metadata-label {
- color: var(--l2-foreground);
- font-family: Inter;
- font-size: 11px;
- font-style: normal;
- font-weight: 500;
- line-height: 18px; /* 163.636% */
- letter-spacing: 0.44px;
- text-transform: uppercase;
- }
-
- .namespace-details-metadata-value {
- color: var(--l2-foreground);
- font-family: 'Geist Mono';
- font-size: 12px;
- font-style: normal;
- font-weight: 500;
- line-height: 20px; /* 142.857% */
- letter-spacing: -0.07px;
-
- width: 100%;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
-
- .status-tag {
- margin: 0;
-
- &.active {
- color: var(--success-500);
- background: var(--success-100);
- border-color: var(--success-500);
- }
-
- &.inactive {
- color: var(--error-500);
- background: var(--error-100);
- border-color: var(--error-500);
- }
- }
-
- .progress-container {
- width: 158px;
-
- .ant-progress {
- margin: 0;
-
- .ant-progress-text {
- font-weight: 600;
- }
- }
- }
-
- .ant-card {
- &.ant-card-bordered {
- border: 1px solid var(--l1-border) !important;
- }
- }
- }
- }
-
- .tabs-and-search {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin: 16px 0;
-
- .action-btn {
- border-radius: 2px;
- border: 1px solid var(--l1-border);
- background: var(--l3-background);
- box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
- display: flex;
- align-items: center;
- justify-content: center;
- }
- }
-
- .views-tabs-container {
- margin-top: 1.5rem;
- display: flex;
- justify-content: space-between;
- align-items: center;
-
- .views-tabs {
- color: var(--l2-foreground);
-
- .view-title {
- display: flex;
- gap: var(--margin-2);
- align-items: center;
- justify-content: center;
- font-size: var(--font-size-xs);
- font-style: normal;
- font-weight: var(--font-weight-normal);
- }
-
- .tab {
- border: 1px solid var(--l1-border);
- width: 114px;
- }
-
- .tab::before {
- background: var(--l1-border);
- }
-
- .selected_view {
- background: var(--l1-border);
- color: var(--l1-foreground);
- border: 1px solid var(--l1-border);
- }
-
- .selected_view::before {
- background: var(--l1-border);
- }
- }
-
- .compass-button {
- width: 30px;
- height: 30px;
-
- border-radius: 2px;
- border: 1px solid var(--l1-border);
- background: var(--l3-background);
- box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
- }
- }
-
- .ant-drawer-close {
- padding: 0px;
- }
-}
-
-.lightMode {
- .ant-drawer-header {
- border-bottom: 1px solid var(--l1-border);
- background: var(--l1-background);
- }
-
- .namespace-detail-drawer {
- .title {
- color: var(--l2-foreground);
- }
-
- .namespace-detail-drawer__namespace {
- .ant-typography {
- color: var(--l2-foreground);
- background: transparent;
- }
- }
-
- .radio-button {
- border: 1px solid var(--l1-border);
- background: var(--l1-background);
- color: var(--l2-foreground);
- }
-
- .views-tabs {
- .tab {
- background: var(--l1-background);
- }
-
- .selected_view {
- background: var(--l3-background);
- border: 1px solid var(--l1-border);
- color: var(--l2-foreground);
- }
-
- .selected_view::before {
- background: var(--l3-background);
- border-left: 1px solid var(--l1-border);
- }
- }
-
- .compass-button {
- border: 1px solid var(--l1-border);
- background: var(--l1-background);
- box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
- }
-
- .tabs-and-search {
- .action-btn {
- border: 1px solid var(--l1-border);
- background: var(--l1-background);
- color: var(--l2-foreground);
- }
- }
- }
-}
diff --git a/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/NamespaceDetails.tsx b/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/NamespaceDetails.tsx
deleted file mode 100644
index 3fa319a21a..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/NamespaceDetails.tsx
+++ /dev/null
@@ -1,640 +0,0 @@
-/* eslint-disable sonarjs/no-identical-functions */
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { Color, Spacing } from '@signozhq/design-tokens';
-import { Button, Divider, Drawer, Radio, Tooltip, Typography } from 'antd';
-import type { RadioChangeEvent } from 'antd/lib';
-import logEvent from 'api/common/logEvent';
-import { K8sNamespacesData } from 'api/infraMonitoring/getK8sNamespacesList';
-import { VIEW_TYPES, VIEWS } from 'components/HostMetricsDetail/constants';
-import { InfraMonitoringEvents } from 'constants/events';
-import { QueryParams } from 'constants/query';
-import {
- initialQueryBuilderFormValuesMap,
- initialQueryState,
-} from 'constants/queryBuilder';
-import ROUTES from 'constants/routes';
-import { filterDuplicateFilters } from 'container/InfraMonitoringK8s/commonUtils';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
-import { QUERY_KEYS } from 'container/InfraMonitoringK8s/EntityDetailsUtils/utils';
-import {
- useInfraMonitoringEventsFilters,
- useInfraMonitoringLogFilters,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from 'container/InfraMonitoringK8s/hooks';
-import {
- CustomTimeType,
- Time,
-} from 'container/TopNav/DateTimeSelectionV2/types';
-import { useIsDarkMode } from 'hooks/useDarkMode';
-import useUrlQuery from 'hooks/useUrlQuery';
-import GetMinMax from 'lib/getMinMax';
-import {
- BarChart2,
- ChevronsLeftRight,
- Compass,
- DraftingCompass,
- ScrollText,
- X,
-} from 'lucide-react';
-import { AppState } from 'store/reducers';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import {
- IBuilderQuery,
- TagFilterItem,
-} from 'types/api/queryBuilder/queryBuilderData';
-import {
- LogsAggregatorOperator,
- TracesAggregatorOperator,
-} from 'types/common/queryBuilder';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { v4 as uuidv4 } from 'uuid';
-
-import NamespaceEvents from '../../EntityDetailsUtils/EntityEvents';
-import NamespaceLogs from '../../EntityDetailsUtils/EntityLogs';
-import NamespaceMetrics from '../../EntityDetailsUtils/EntityMetrics';
-import NamespaceTraces from '../../EntityDetailsUtils/EntityTraces';
-import {
- getNamespaceMetricsQueryPayload,
- namespaceWidgetInfo,
-} from './constants';
-import { NamespaceDetailsProps } from './NamespaceDetails.interfaces';
-
-import './NamespaceDetails.styles.scss';
-
-function NamespaceDetails({
- namespace,
- onClose,
- isModalTimeSelection,
-}: NamespaceDetailsProps): JSX.Element {
- const { maxTime, minTime, selectedTime } = useSelector<
- AppState,
- GlobalReducer
- >((state) => state.globalTime);
-
- const startMs = useMemo(() => Math.floor(Number(minTime) / 1000000000), [
- minTime,
- ]);
- const endMs = useMemo(() => Math.floor(Number(maxTime) / 1000000000), [
- maxTime,
- ]);
-
- const urlQuery = useUrlQuery();
-
- const [modalTimeRange, setModalTimeRange] = useState(() => ({
- startTime: startMs,
- endTime: endMs,
- }));
-
- const lastSelectedInterval = useRef<Time | null>(null);
-
- const [selectedInterval, setSelectedInterval] = useState<Time>(
- lastSelectedInterval.current
- ? lastSelectedInterval.current
- : (selectedTime as Time),
- );
-
- const [selectedView, setSelectedView] = useInfraMonitoringView();
- const [logFiltersParam, setLogFiltersParam] = useInfraMonitoringLogFilters();
- const [
- tracesFiltersParam,
- setTracesFiltersParam,
- ] = useInfraMonitoringTracesFilters();
- const [
- eventsFiltersParam,
- setEventsFiltersParam,
- ] = useInfraMonitoringEventsFilters();
- const isDarkMode = useIsDarkMode();
-
- const initialFilters = useMemo(() => {
- const filters =
- selectedView === VIEW_TYPES.LOGS ? logFiltersParam : tracesFiltersParam;
- if (filters) {
- return filters;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_NAMESPACE_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s_namespace_name--string--resource--false',
- },
- op: '=',
- value: namespace?.namespaceName || '',
- },
- ],
- };
- }, [
- namespace?.namespaceName,
- selectedView,
- logFiltersParam,
- tracesFiltersParam,
- ]);
-
- const initialEventsFilters = useMemo(() => {
- if (eventsFiltersParam) {
- return eventsFiltersParam;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_KIND,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.kind--string--resource--false',
- },
- op: '=',
- value: 'Namespace',
- },
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.name--string--resource--false',
- },
- op: '=',
- value: namespace?.namespaceName || '',
- },
- ],
- };
- }, [namespace?.namespaceName, eventsFiltersParam]);
-
- const [logAndTracesFilters, setLogAndTracesFilters] = useState<
- IBuilderQuery['filters']
- >(initialFilters);
-
- const [eventsFilters, setEventsFilters] = useState<IBuilderQuery['filters']>(
- initialEventsFilters,
- );
-
- useEffect(() => {
- if (namespace) {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Namespace,
- });
- }
- }, [namespace]);
-
- useEffect(() => {
- setLogAndTracesFilters(initialFilters);
- setEventsFilters(initialEventsFilters);
- }, [initialFilters, initialEventsFilters]);
-
- useEffect(() => {
- const currentSelectedInterval = lastSelectedInterval.current || selectedTime;
- setSelectedInterval(currentSelectedInterval as Time);
-
- if (currentSelectedInterval !== 'custom') {
- const { maxTime, minTime } = GetMinMax(currentSelectedInterval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- }, [selectedTime, minTime, maxTime]);
-
- const handleTabChange = (e: RadioChangeEvent): void => {
- setSelectedView(e.target.value);
- setLogFiltersParam(null);
- setTracesFiltersParam(null);
- setEventsFiltersParam(null);
- logEvent(InfraMonitoringEvents.TabChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Namespace,
- view: e.target.value,
- });
- };
-
- const handleTimeChange = useCallback(
- (interval: Time | CustomTimeType, dateTimeRange?: [number, number]): void => {
- lastSelectedInterval.current = interval as Time;
- setSelectedInterval(interval as Time);
-
- if (interval === 'custom' && dateTimeRange) {
- setModalTimeRange({
- startTime: Math.floor(dateTimeRange[0] / 1000),
- endTime: Math.floor(dateTimeRange[1] / 1000),
- });
- } else {
- const { maxTime, minTime } = GetMinMax(interval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
-
- logEvent(InfraMonitoringEvents.TimeUpdated, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Namespace,
- interval,
- view: selectedView,
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeLogFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_NAMESPACE_NAME, QUERY_KEYS.K8S_CLUSTER_NAME].includes(
- item.key?.key ?? '',
- ),
- );
- const paginationFilter = value?.items?.find(
- (item) => item.key?.key === 'id',
- );
- const newFilters = value?.items?.filter(
- (item) =>
- item.key?.key !== 'id' && item.key?.key !== QUERY_KEYS.K8S_NAMESPACE_NAME,
- );
-
- if (newFilters && newFilters?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Namespace,
- view: InfraMonitoringEvents.LogsView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(newFilters || []),
- ...(paginationFilter ? [paginationFilter] : []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setLogFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeTracesFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_NAMESPACE_NAME, QUERY_KEYS.K8S_CLUSTER_NAME].includes(
- item.key?.key ?? '',
- ),
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Namespace,
- view: InfraMonitoringEvents.TracesView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(value?.items?.filter(
- (item) => item.key?.key !== QUERY_KEYS.K8S_NAMESPACE_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setTracesFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeEventsFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setEventsFilters((prevFilters) => {
- const namespaceKindFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_KIND,
- );
- const namespaceNameFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_NAME,
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Namespace,
- view: InfraMonitoringEvents.EventsView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: [
- namespaceKindFilter,
- namespaceNameFilter,
- ...(value?.items?.filter(
- (item) =>
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_KIND &&
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- };
-
- setEventsFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleExplorePagesRedirect = (): void => {
- if (selectedInterval !== 'custom') {
- urlQuery.set(QueryParams.relativeTime, selectedInterval);
- } else {
- urlQuery.delete(QueryParams.relativeTime);
- urlQuery.set(QueryParams.startTime, modalTimeRange.startTime.toString());
- urlQuery.set(QueryParams.endTime, modalTimeRange.endTime.toString());
- }
-
- logEvent(InfraMonitoringEvents.ExploreClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Namespace,
- view: selectedView,
- });
-
- if (selectedView === VIEW_TYPES.LOGS) {
- const filtersWithoutPagination = {
- ...logAndTracesFilters,
- items:
- logAndTracesFilters?.items?.filter((item) => item.key?.key !== 'id') || [],
- };
-
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.logs,
- aggregateOperator: LogsAggregatorOperator.NOOP,
- filters: filtersWithoutPagination,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.LOGS_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- } else if (selectedView === VIEW_TYPES.TRACES) {
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.traces,
- aggregateOperator: TracesAggregatorOperator.NOOP,
- filters: logAndTracesFilters,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.TRACES_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- }
- };
-
- const handleClose = (): void => {
- lastSelectedInterval.current = null;
- setSelectedInterval(selectedTime as Time);
-
- if (selectedTime !== 'custom') {
- const { maxTime, minTime } = GetMinMax(selectedTime);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- setSelectedView(VIEW_TYPES.METRICS);
- onClose();
- };
-
- return (
- <Drawer
- width="70%"
- title={
- <>
- <Divider type="vertical" />
- <Typography.Text className="title">
- {namespace?.namespaceName}
- </Typography.Text>
- </>
- }
- placement="right"
- onClose={handleClose}
- open={!!namespace}
- style={{
- overscrollBehavior: 'contain',
- background: isDarkMode ? Color.BG_INK_400 : Color.BG_VANILLA_100,
- }}
- className="entity-detail-drawer"
- destroyOnClose
- closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
- >
- {namespace && (
- <>
- <div className="entity-detail-drawer__entity">
- <div className="entity-details-grid">
- <div className="labels-row">
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Namespace Name
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Cluster Name
- </Typography.Text>
- </div>
- <div className="values-row">
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={namespace.namespaceName}>
- {namespace.namespaceName}
- </Tooltip>
- </Typography.Text>
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title="Cluster name">
- {namespace.meta.k8s_cluster_name}
- </Tooltip>
- </Typography.Text>
- </div>
- </div>
- </div>
-
- <div className="views-tabs-container">
- <Radio.Group
- className="views-tabs"
- onChange={handleTabChange}
- value={selectedView}
- >
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.METRICS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.METRICS}
- >
- <div className="view-title">
- <BarChart2 size={14} />
- Metrics
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.LOGS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.LOGS}
- >
- <div className="view-title">
- <ScrollText size={14} />
- Logs
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.TRACES ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.TRACES}
- >
- <div className="view-title">
- <DraftingCompass size={14} />
- Traces
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.EVENTS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.EVENTS}
- >
- <div className="view-title">
- <ChevronsLeftRight size={14} />
- Events
- </div>
- </Radio.Button>
- </Radio.Group>
-
- {(selectedView === VIEW_TYPES.LOGS ||
- selectedView === VIEW_TYPES.TRACES) && (
- <Button
- icon={<Compass size={18} />}
- className="compass-button"
- onClick={handleExplorePagesRedirect}
- />
- )}
- </div>
- {selectedView === VIEW_TYPES.METRICS && (
- <NamespaceMetrics<K8sNamespacesData>
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- entity={namespace}
- entityWidgetInfo={namespaceWidgetInfo}
- getEntityQueryPayload={getNamespaceMetricsQueryPayload}
- category={K8sCategory.NAMESPACES}
- queryKey="namespaceMetrics"
- />
- )}
- {selectedView === VIEW_TYPES.LOGS && (
- <NamespaceLogs
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeLogFilters={handleChangeLogFilters}
- logFilters={logAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKey="namespaceLogs"
- category={K8sCategory.NAMESPACES}
- queryKeyFilters={[QUERY_KEYS.K8S_NAMESPACE_NAME]}
- />
- )}
- {selectedView === VIEW_TYPES.TRACES && (
- <NamespaceTraces
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeTracesFilters={handleChangeTracesFilters}
- tracesFilters={logAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKey="namespaceTraces"
- category={InfraMonitoringEvents.Namespace}
- queryKeyFilters={[QUERY_KEYS.K8S_NAMESPACE_NAME]}
- />
- )}
- {selectedView === VIEW_TYPES.EVENTS && (
- <NamespaceEvents
- timeRange={modalTimeRange}
- handleChangeEventFilters={handleChangeEventsFilters}
- filters={eventsFilters}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- category={K8sCategory.NAMESPACES}
- queryKey="namespaceEvents"
- />
- )}
- </>
- )}
- </Drawer>
- );
-}
-
-export default NamespaceDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/index.ts b/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/index.ts
deleted file mode 100644
index 0dc1f3330a..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import NamespaceDetails from './NamespaceDetails';
-
-export default NamespaceDetails;
diff --git a/frontend/src/api/infraMonitoring/getK8sNamespacesList.ts b/frontend/src/container/InfraMonitoringK8s/Namespaces/api.ts
similarity index 70%
rename from frontend/src/api/infraMonitoring/getK8sNamespacesList.ts
rename to frontend/src/container/InfraMonitoringK8s/Namespaces/api.ts
index 86e7c28adf..9c7ee17e50 100644
--- a/frontend/src/api/infraMonitoring/getK8sNamespacesList.ts
+++ b/frontend/src/container/InfraMonitoringK8s/Namespaces/api.ts
@@ -1,11 +1,12 @@
import axios from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
+import { UnderscoreToDotMap } from 'api/utils';
import { AxiosError } from 'axios';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
-import { UnderscoreToDotMap } from '../utils';
+import { K8sBaseFilters } from '../Base/types';
export interface K8sNamespacesListPayload {
filters: TagFilter;
@@ -40,6 +41,7 @@ export interface K8sNamespacesListResponse {
};
}
+// TODO(H4ad): Erase this whole file when migrating to openapi
export const namespacesMetaMap = [
{ dot: 'k8s.cluster.name', under: 'k8s_cluster_name' },
{ dot: 'k8s.namespace.name', under: 'k8s_namespace_name' },
@@ -59,44 +61,43 @@ export function mapNamespacesMeta(
}
export const getK8sNamespacesList = async (
- props: K8sNamespacesListPayload,
+ props: K8sBaseFilters,
signal?: AbortSignal,
headers?: Record<string, string>,
dotMetricsEnabled = false,
): Promise<SuccessResponse<K8sNamespacesListResponse> | ErrorResponse> => {
try {
- const requestProps =
- dotMetricsEnabled && Array.isArray(props.filters?.items)
- ? {
- ...props,
- filters: {
- ...props.filters,
- items: props.filters.items.reduce<typeof props.filters.items>(
- (acc, item) => {
- if (item.value === undefined) {
- return acc;
- }
- if (
- item.key &&
- typeof item.key === 'object' &&
- 'key' in item.key &&
- typeof item.key.key === 'string'
- ) {
- const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
- acc.push({
- ...item,
- key: { ...item.key, key: mappedKey },
- });
- } else {
- acc.push(item);
- }
+ const requestProps = dotMetricsEnabled
+ ? {
+ ...props,
+ filters: {
+ ...props.filters,
+ items: props.filters?.items.reduce<typeof props.filters.items>(
+ (acc, item) => {
+ if (item.value === undefined) {
return acc;
- },
- [] as typeof props.filters.items,
- ),
- },
- }
- : props;
+ }
+ if (
+ item.key &&
+ typeof item.key === 'object' &&
+ 'key' in item.key &&
+ typeof item.key.key === 'string'
+ ) {
+ const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
+ acc.push({
+ ...item,
+ key: { ...item.key, key: mappedKey },
+ });
+ } else {
+ acc.push(item);
+ }
+ return acc;
+ },
+ [] as typeof props.filters.items,
+ ),
+ },
+ }
+ : props;
const response = await axios.post('/namespaces/list', requestProps, {
signal,
diff --git a/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/constants.ts b/frontend/src/container/InfraMonitoringK8s/Namespaces/constants.ts
similarity index 96%
rename from frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/constants.ts
rename to frontend/src/container/InfraMonitoringK8s/Namespaces/constants.ts
index 9ea110e993..b2b8fe39c5 100644
--- a/frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/constants.ts
+++ b/frontend/src/container/InfraMonitoringK8s/Namespaces/constants.ts
@@ -1,11 +1,67 @@
-import { K8sNamespacesData } from 'api/infraMonitoring/getK8sNamespacesList';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import {
+ TagFilter,
+ TagFilterItem,
+} from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { v4 } from 'uuid';
+import {
+ createFilterItem,
+ K8sDetailsMetadataConfig,
+} from '../Base/K8sBaseDetails';
+import { QUERY_KEYS } from '../EntityDetailsUtils/utils';
+import { K8sNamespacesData } from './api';
+
+export const k8sNamespaceGetSelectedItemFilters = (
+ selectedItemId: string,
+): TagFilter => ({
+ op: 'AND',
+ items: [
+ {
+ id: 'k8s_namespace_name',
+ key: {
+ key: 'k8s_namespace_name',
+ type: null,
+ },
+ op: '=',
+ value: selectedItemId,
+ },
+ ],
+});
+
+export const k8sNamespaceDetailsMetadataConfig: K8sDetailsMetadataConfig<K8sNamespacesData>[] = [
+ { label: 'Namespace Name', getValue: (p): string => p.namespaceName },
+ {
+ label: 'Cluster Name',
+ getValue: (p): string => p.meta.k8s_cluster_name,
+ },
+];
+
+export const k8sNamespaceInitialFilters = [
+ QUERY_KEYS.K8S_NAMESPACE_NAME,
+ QUERY_KEYS.K8S_CLUSTER_NAME,
+];
+
+export const k8sNamespaceInitialEventsFilter = (
+ item: K8sNamespacesData,
+): TagFilterItem[] => [
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_KIND, 'Namespace'),
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_NAME, item.namespaceName),
+];
+
+export const k8sNamespaceInitialLogTracesFilter = (
+ item: K8sNamespacesData,
+): TagFilterItem[] => [
+ createFilterItem(QUERY_KEYS.K8S_NAMESPACE_NAME, item.namespaceName),
+];
+
+export const k8sNamespaceGetEntityName = (item: K8sNamespacesData): string =>
+ item.namespaceName;
+
export const namespaceWidgetInfo = [
{
title: 'CPU Usage (cores)',
diff --git a/frontend/src/container/InfraMonitoringK8s/Namespaces/table.config.tsx b/frontend/src/container/InfraMonitoringK8s/Namespaces/table.config.tsx
new file mode 100644
index 0000000000..57bff0b01e
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Namespaces/table.config.tsx
@@ -0,0 +1,155 @@
+import { TableColumnType as ColumnType, Tooltip } from 'antd';
+import { Group } from 'lucide-react';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+
+import { K8sRenderedRowData } from '../Base/types';
+import { IEntityColumn } from '../Base/useInfraMonitoringTableColumnsStore';
+import { getGroupByEl, getGroupedByMeta, getRowKey } from '../Base/utils';
+import { formatBytes, ValidateColumnValueWrapper } from '../commonUtils';
+import { K8sNamespacesData, K8sNamespacesListPayload } from './api';
+
+import styles from './table.module.scss';
+
+export interface K8sNamespacesRowData {
+ key: string;
+ itemKey: string;
+ namespaceUID: string;
+ namespaceName: React.ReactNode;
+ clusterName: string;
+ cpu: React.ReactNode;
+ memory: React.ReactNode;
+ groupedByMeta?: Record<string, string>;
+}
+
+export const k8sNamespacesColumns: IEntityColumn[] = [
+ {
+ label: 'Namespace Group',
+ value: 'namespaceGroup',
+ id: 'namespaceGroup',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-collapse',
+ },
+ {
+ label: 'Namespace Name',
+ value: 'namespaceName',
+ id: 'namespaceName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-expand',
+ },
+ {
+ label: 'Cluster Name',
+ value: 'clusterName',
+ id: 'clusterName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Usage (cores)',
+ value: 'cpu',
+ id: 'cpu',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Memory Usage (WSS)',
+ value: 'memory',
+ id: 'memory',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+];
+
+export const getK8sNamespacesListQuery = (): K8sNamespacesListPayload => ({
+ filters: {
+ items: [],
+ op: 'and',
+ },
+ orderBy: { columnName: 'cpu', order: 'desc' },
+});
+
+export const k8sNamespacesColumnsConfig: ColumnType<K8sRenderedRowData>[] = [
+ {
+ title: (
+ <div className={styles.entityGroupHeader}>
+ <Group size={14} /> NAMESPACE GROUP
+ </div>
+ ),
+ dataIndex: 'namespaceGroup',
+ key: 'namespaceGroup',
+ ellipsis: true,
+ width: 150,
+ align: 'left',
+ sorter: false,
+ },
+ {
+ title: <div>Namespace Name</div>,
+ dataIndex: 'namespaceName',
+ key: 'namespaceName',
+ ellipsis: true,
+ width: 120,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>Cluster Name</div>,
+ dataIndex: 'clusterName',
+ key: 'clusterName',
+ ellipsis: true,
+ width: 120,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Usage (cores)</div>,
+ dataIndex: 'cpu',
+ key: 'cpu',
+ width: 100,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Usage (WSS)</div>,
+ dataIndex: 'memory',
+ key: 'memory',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+];
+
+export const k8sNamespacesRenderRowData = (
+ namespace: K8sNamespacesData,
+ groupBy: BaseAutocompleteData[],
+): K8sRenderedRowData => ({
+ key: getRowKey(
+ namespace,
+ () => namespace.namespaceName || namespace.meta.k8s_namespace_name,
+ groupBy,
+ ),
+ itemKey: namespace.meta.k8s_namespace_name,
+ namespaceUID: namespace.namespaceName,
+ namespaceName: (
+ <Tooltip title={namespace.namespaceName}>
+ {namespace.namespaceName || ''}
+ </Tooltip>
+ ),
+ clusterName: namespace.meta.k8s_cluster_name,
+ cpu: (
+ <ValidateColumnValueWrapper value={namespace.cpuUsage}>
+ {namespace.cpuUsage}
+ </ValidateColumnValueWrapper>
+ ),
+ memory: (
+ <ValidateColumnValueWrapper value={namespace.memoryUsage}>
+ {formatBytes(namespace.memoryUsage)}
+ </ValidateColumnValueWrapper>
+ ),
+ namespaceGroup: getGroupByEl(namespace, groupBy),
+ ...namespace.meta,
+ groupedByMeta: getGroupedByMeta(namespace, groupBy),
+});
diff --git a/frontend/src/container/InfraMonitoringK8s/Namespaces/table.module.scss b/frontend/src/container/InfraMonitoringK8s/Namespaces/table.module.scss
new file mode 100644
index 0000000000..b1fb6dd7c2
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Namespaces/table.module.scss
@@ -0,0 +1,6 @@
+.entityGroupHeader {
+ padding-left: var(--spacing-5);
+ gap: var(--spacing-5);
+ display: flex;
+ align-items: center;
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Namespaces/utils.tsx b/frontend/src/container/InfraMonitoringK8s/Namespaces/utils.tsx
deleted file mode 100644
index d1de646505..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Namespaces/utils.tsx
+++ /dev/null
@@ -1,179 +0,0 @@
-import { Color } from '@signozhq/design-tokens';
-import { TableColumnType as ColumnType, Tag } from 'antd';
-import {
- K8sNamespacesData,
- K8sNamespacesListPayload,
-} from 'api/infraMonitoring/getK8sNamespacesList';
-import { Group } from 'lucide-react';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-
-import { formatBytes, ValidateColumnValueWrapper } from '../commonUtils';
-import { IEntityColumn } from '../utils';
-
-export const defaultAddedColumns: IEntityColumn[] = [
- {
- label: 'Namespace Name',
- value: 'namespaceName',
- id: 'namespaceName',
- canRemove: false,
- },
- {
- label: 'Cluster Name',
- value: 'clusterName',
- id: 'clusterName',
- canRemove: false,
- },
- {
- label: 'CPU Utilization (cores)',
- value: 'cpu',
- id: 'cpu',
- canRemove: false,
- },
- {
- label: 'Memory Utilization (bytes)',
- value: 'memory',
- id: 'memory',
- canRemove: false,
- },
-];
-
-export interface K8sNamespacesRowData {
- key: string;
- namespaceUID: string;
- namespaceName: string;
- clusterName: string;
- cpu: React.ReactNode;
- memory: React.ReactNode;
- groupedByMeta?: any;
-}
-
-const namespaceGroupColumnConfig = {
- title: (
- <div className="column-header entity-group-header">
- <Group size={14} /> NAMESPACE GROUP
- </div>
- ),
- dataIndex: 'namespaceGroup',
- key: 'namespaceGroup',
- ellipsis: true,
- width: 150,
- align: 'left',
- sorter: false,
- className: 'column entity-group-header',
-};
-
-export const getK8sNamespacesListQuery = (): K8sNamespacesListPayload => ({
- filters: {
- items: [],
- op: 'and',
- },
- orderBy: { columnName: 'cpu', order: 'desc' },
-});
-
-const columnsConfig = [
- {
- title: <div className="column-header-left">Namespace Name</div>,
- dataIndex: 'namespaceName',
- key: 'namespaceName',
- ellipsis: true,
- width: 120,
- sorter: false,
- align: 'left',
- },
- {
- title: <div className="column-header-left">Cluster Name</div>,
- dataIndex: 'clusterName',
- key: 'clusterName',
- ellipsis: true,
- width: 120,
- sorter: false,
- align: 'left',
- },
- {
- title: <div className="column-header-left">CPU Usage (cores)</div>,
- dataIndex: 'cpu',
- key: 'cpu',
- width: 100,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header-left">Mem Usage (WSS)</div>,
- dataIndex: 'memory',
- key: 'memory',
- width: 120,
- sorter: true,
- align: 'left',
- },
-];
-
-export const getK8sNamespacesListColumns = (
- groupBy: IBuilderQuery['groupBy'],
-): ColumnType<K8sNamespacesRowData>[] => {
- if (groupBy.length > 0) {
- const filteredColumns = [...columnsConfig].filter(
- (column) => column.key !== 'namespaceName',
- );
- filteredColumns.unshift(namespaceGroupColumnConfig);
- return filteredColumns as ColumnType<K8sNamespacesRowData>[];
- }
-
- return columnsConfig as ColumnType<K8sNamespacesRowData>[];
-};
-
-const dotToUnder: Record<string, keyof K8sNamespacesData['meta']> = {
- 'k8s.namespace.name': 'k8s_namespace_name',
- 'k8s.cluster.name': 'k8s_cluster_name',
-};
-
-const getGroupByEle = (
- namespace: K8sNamespacesData,
- groupBy: IBuilderQuery['groupBy'],
-): React.ReactNode => {
- const groupByValues: string[] = [];
-
- groupBy.forEach((group) => {
- const rawKey = group.key as string;
-
- // Choose mapped key if present, otherwise use rawKey
- const metaKey = (dotToUnder[rawKey] ?? rawKey) as keyof typeof namespace.meta;
- const value = namespace.meta[metaKey];
-
- groupByValues.push(value);
- });
-
- return (
- <div className="pod-group">
- {groupByValues.map((value) => (
- <Tag key={value} color={Color.BG_SLATE_400} className="pod-group-tag-item">
- {value === '' ? '<no-value>' : value}
- </Tag>
- ))}
- </div>
- );
-};
-
-export const formatDataForTable = (
- data: K8sNamespacesData[],
- groupBy: IBuilderQuery['groupBy'],
-): K8sNamespacesRowData[] =>
- data.map((namespace, index) => ({
- key: index.toString(),
- namespaceUID: namespace.namespaceName,
- namespaceName: namespace.namespaceName,
- clusterName: namespace.meta.k8s_cluster_name,
- cpu: (
- <ValidateColumnValueWrapper value={namespace.cpuUsage}>
- {namespace.cpuUsage}
- </ValidateColumnValueWrapper>
- ),
- memory: (
- <ValidateColumnValueWrapper value={namespace.memoryUsage}>
- {formatBytes(namespace.memoryUsage)}
- </ValidateColumnValueWrapper>
- ),
- namespaceGroup: getGroupByEle(namespace, groupBy),
- meta: namespace.meta,
- ...namespace.meta,
- groupedByMeta: namespace.meta,
- }));
diff --git a/frontend/src/container/InfraMonitoringK8s/Nodes/K8sNodesList.styles.scss b/frontend/src/container/InfraMonitoringK8s/Nodes/K8sNodesList.styles.scss
deleted file mode 100644
index c09c569a03..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Nodes/K8sNodesList.styles.scss
+++ /dev/null
@@ -1,17 +0,0 @@
-.infra-monitoring-container {
- .nodes-list-table {
- .expanded-table-container {
- padding-left: 40px;
- }
-
- .ant-table-cell {
- min-width: 223px !important;
- max-width: 223px !important;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
- }
-}
diff --git a/frontend/src/container/InfraMonitoringK8s/Nodes/K8sNodesList.tsx b/frontend/src/container/InfraMonitoringK8s/Nodes/K8sNodesList.tsx
index 2143dff75f..bd2f0a54e0 100644
--- a/frontend/src/container/InfraMonitoringK8s/Nodes/K8sNodesList.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/Nodes/K8sNodesList.tsx
@@ -1,697 +1,118 @@
-import React, { useCallback, useEffect, useMemo, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { LoadingOutlined } from '@ant-design/icons';
-import {
- Button,
- Spin,
- Table,
- TableColumnType as ColumnType,
- TablePaginationConfig,
- TableProps,
- Typography,
-} from 'antd';
-import type { SorterResult } from 'antd/es/table/interface';
-import logEvent from 'api/common/logEvent';
-import { K8sNodesListPayload } from 'api/infraMonitoring/getK8sNodesList';
+import React, { useCallback } from 'react';
import { InfraMonitoringEvents } from 'constants/events';
import { FeatureKeys } from 'constants/features';
-import { useGetK8sNodesList } from 'hooks/infraMonitoring/useGetK8sNodesList';
-import { useGetAggregateKeys } from 'hooks/queryBuilder/useGetAggregateKeys';
-import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
-import { ChevronDown, ChevronRight } from 'lucide-react';
import { useAppContext } from 'providers/App/App';
-import { AppState } from 'store/reducers';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { buildAbsolutePath, isModifierKeyPressed } from 'utils/app';
-import { openInNewTab } from 'utils/navigation';
-
-import emptyStateUrl from '@/assets/Icons/emptyState.svg';
+import K8sBaseDetails, { K8sDetailsFilters } from '../Base/K8sBaseDetails';
+import { K8sBaseList } from '../Base/K8sBaseList';
+import { K8sBaseFilters } from '../Base/types';
+import { InfraMonitoringEntity } from '../constants';
+import { getK8sNodesList, K8sNodeData } from './api';
import {
- GetK8sEntityToAggregateAttribute,
- INFRA_MONITORING_K8S_PARAMS_KEYS,
- K8sCategory,
-} from '../constants';
-import {
- useInfraMonitoringCurrentPage,
- useInfraMonitoringEventsFilters,
- useInfraMonitoringGroupBy,
- useInfraMonitoringLogFilters,
- useInfraMonitoringNodeUID,
- useInfraMonitoringOrderBy,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from '../hooks';
-import K8sHeader from '../K8sHeader';
-import LoadingContainer from '../LoadingContainer';
-import { usePageSize } from '../utils';
-import NodeDetails from './NodeDetails';
+ getNodeMetricsQueryPayload,
+ k8sNodeDetailsMetadataConfig,
+ k8sNodeGetEntityName,
+ k8sNodeGetSelectedItemFilters,
+ k8sNodeInitialEventsFilter,
+ k8sNodeInitialFilters,
+ k8sNodeInitialLogTracesFilter,
+ nodeWidgetInfo,
+} from './constants';
import {
- defaultAddedColumns,
- formatDataForTable,
- getK8sNodesListColumns,
- getK8sNodesListQuery,
- K8sNodesRowData,
-} from './utils';
-
-import '../InfraMonitoringK8s.styles.scss';
-import './K8sNodesList.styles.scss';
+ k8sNodesColumns,
+ k8sNodesColumnsConfig,
+ k8sNodesRenderRowData,
+} from './table.config';
function K8sNodesList({
- isFiltersVisible,
- handleFilterVisibilityChange,
- quickFiltersLastUpdated,
+ controlListPrefix,
}: {
- isFiltersVisible: boolean;
- handleFilterVisibilityChange: () => void;
- quickFiltersLastUpdated: number;
+ controlListPrefix?: React.ReactNode;
}): JSX.Element {
- const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
- (state) => state.globalTime,
- );
-
- const [currentPage, setCurrentPage] = useInfraMonitoringCurrentPage();
- const [filtersInitialised, setFiltersInitialised] = useState(false);
-
- const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
- const [orderBy, setOrderBy] = useInfraMonitoringOrderBy();
-
- const [selectedNodeUID, setSelectedNodeUID] = useInfraMonitoringNodeUID();
-
- const { pageSize, setPageSize } = usePageSize(K8sCategory.NODES);
-
- const [groupBy, setGroupBy] = useInfraMonitoringGroupBy();
-
- // These params are used only for clearing in handleCloseNodeDetail
- const [, setView] = useInfraMonitoringView();
- const [, setTracesFilters] = useInfraMonitoringTracesFilters();
- const [, setEventsFilters] = useInfraMonitoringEventsFilters();
- const [, setLogFilters] = useInfraMonitoringLogFilters();
-
- const [selectedRowData, setSelectedRowData] = useState<K8sNodesRowData | null>(
- null,
- );
-
- const [groupByOptions, setGroupByOptions] = useState<
- { value: string; label: string }[]
- >([]);
-
- const { currentQuery } = useQueryBuilder();
-
- const queryFilters = useMemo(
- () =>
- currentQuery?.builder?.queryData[0]?.filters || {
- items: [],
- op: 'and',
- },
- [currentQuery?.builder?.queryData],
- );
-
- // Reset pagination every time quick filters are changed
- useEffect(() => {
- if (quickFiltersLastUpdated !== -1) {
- setCurrentPage(1);
- }
- }, [quickFiltersLastUpdated, setCurrentPage]);
-
const { featureFlags } = useAppContext();
const dotMetricsEnabled =
featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
?.active || false;
- const createFiltersForSelectedRowData = (
- selectedRowData: K8sNodesRowData,
- groupBy: IBuilderQuery['groupBy'],
- ): IBuilderQuery['filters'] => {
- const baseFilters: IBuilderQuery['filters'] = {
- items: [...queryFilters.items],
- op: 'and',
- };
-
- if (!selectedRowData) {
- return baseFilters;
- }
-
- const { groupedByMeta } = selectedRowData;
-
- for (const key of groupBy) {
- baseFilters.items.push({
- key: {
- key: key.key,
- type: null,
- },
- op: '=',
- value: groupedByMeta[key.key],
- id: key.key,
- });
- }
-
- return baseFilters;
- };
-
- const fetchGroupedByRowDataQuery = useMemo(() => {
- if (!selectedRowData) {
- return null;
- }
-
- const baseQuery = getK8sNodesListQuery();
-
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- return {
- ...baseQuery,
- limit: 10,
- offset: 0,
- filters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [minTime, maxTime, orderBy, selectedRowData, groupBy]);
-
- const groupedByRowDataQueryKey = useMemo(() => {
- // be careful with what you serialize from selectedRowData
- // since it's react node, it could contain circular references
- const selectedRowDataKey = JSON.stringify(selectedRowData?.groupedByMeta);
- if (selectedNodeUID) {
- return [
- 'nodeList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- ];
- }
- return [
- 'nodeList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- String(minTime),
- String(maxTime),
- ];
- }, [
- queryFilters,
- orderBy,
- selectedNodeUID,
- minTime,
- maxTime,
- selectedRowData,
- ]);
-
- const {
- data: groupedByRowData,
- isFetching: isFetchingGroupedByRowData,
- isLoading: isLoadingGroupedByRowData,
- isError: isErrorGroupedByRowData,
- refetch: fetchGroupedByRowData,
- } = useGetK8sNodesList(
- fetchGroupedByRowDataQuery as K8sNodesListPayload,
- {
- queryKey: groupedByRowDataQueryKey,
- enabled: !!fetchGroupedByRowDataQuery && !!selectedRowData,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const {
- data: groupByFiltersData,
- isLoading: isLoadingGroupByFilters,
- } = useGetAggregateKeys(
- {
- dataSource: currentQuery.builder.queryData[0].dataSource,
- aggregateAttribute: GetK8sEntityToAggregateAttribute(
- K8sCategory.NODES,
+ const fetchListData = useCallback(
+ async (filters: K8sBaseFilters, signal?: AbortSignal) => {
+ filters.orderBy ||= {
+ columnName: 'cpu',
+ order: 'desc',
+ };
+
+ const response = await getK8sNodesList(
+ filters,
+ signal,
+ undefined,
dotMetricsEnabled,
- ),
- aggregateOperator: 'noop',
- searchText: '',
- tagType: '',
- },
- {
- queryKey: [currentQuery.builder.queryData[0].dataSource, 'noop'],
- },
- true,
- K8sCategory.NODES,
- );
-
- const query = useMemo(() => {
- const baseQuery = getK8sNodesListQuery();
- const queryPayload = {
- ...baseQuery,
- limit: pageSize,
- offset: (currentPage - 1) * pageSize,
- filters: queryFilters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- if (groupBy.length > 0) {
- queryPayload.groupBy = groupBy;
- }
- return queryPayload;
- }, [pageSize, currentPage, queryFilters, minTime, maxTime, orderBy, groupBy]);
-
- const nestedNodesData = useMemo(() => {
- if (!selectedRowData || !groupedByRowData?.payload?.data.records) {
- return [];
- }
- return groupedByRowData?.payload?.data?.records || [];
- }, [groupedByRowData, selectedRowData]);
-
- const formattedGroupedByNodesData = useMemo(
- () =>
- formatDataForTable(groupedByRowData?.payload?.data?.records || [], groupBy),
- [groupedByRowData, groupBy],
- );
-
- const queryKey = useMemo(() => {
- if (selectedNodeUID) {
- return [
- 'nodeList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- ];
- }
- return [
- 'nodeList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- String(minTime),
- String(maxTime),
- ];
- }, [
- selectedNodeUID,
- pageSize,
- currentPage,
- queryFilters,
- orderBy,
- groupBy,
- minTime,
- maxTime,
- ]);
-
- const { data, isFetching, isLoading, isError } = useGetK8sNodesList(
- query as K8sNodesListPayload,
- {
- queryKey,
- enabled: !!query,
- keepPreviousData: true,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const nodesData = useMemo(() => data?.payload?.data?.records || [], [data]);
- const totalCount = data?.payload?.data?.total || 0;
-
- const formattedNodesData = useMemo(
- () => formatDataForTable(nodesData, groupBy),
- [nodesData, groupBy],
- );
-
- const columns = useMemo(() => getK8sNodesListColumns(groupBy), [groupBy]);
-
- const handleGroupByRowClick = (record: K8sNodesRowData): void => {
- setSelectedRowData(record);
-
- if (expandedRowKeys.includes(record.key)) {
- setExpandedRowKeys(expandedRowKeys.filter((key) => key !== record.key));
- } else {
- setExpandedRowKeys([record.key]);
- }
- };
-
- useEffect(() => {
- if (selectedRowData) {
- fetchGroupedByRowData();
- }
- }, [selectedRowData, fetchGroupedByRowData]);
-
- const handleTableChange: TableProps<K8sNodesRowData>['onChange'] = useCallback(
- (
- pagination: TablePaginationConfig,
- _filters: Record<string, (string | number | boolean)[] | null>,
- sorter: SorterResult<K8sNodesRowData> | SorterResult<K8sNodesRowData>[],
- ): void => {
- if (pagination.current) {
- setCurrentPage(pagination.current);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Node,
- });
- }
-
- if ('field' in sorter && sorter.order) {
- setOrderBy({
- columnName: sorter.field as string,
- order: (sorter.order === 'ascend' ? 'asc' : 'desc') as 'asc' | 'desc',
- });
- } else {
- setOrderBy(null);
- }
- },
- [setCurrentPage, setOrderBy],
- );
-
- const { handleChangeQueryData } = useQueryOperations({
- index: 0,
- query: currentQuery.builder.queryData[0],
- entityVersion: '',
- });
-
- const handleFiltersChange = useCallback(
- (value: IBuilderQuery['filters']): void => {
- handleChangeQueryData('filters', value);
- if (filtersInitialised) {
- setCurrentPage(1);
- } else {
- setFiltersInitialised(true);
- }
+ );
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Node,
- });
- }
+ return {
+ data: response.payload?.data.records || [],
+ total: response.payload?.data.total || 0,
+ error: response.error,
+ rawData: response.payload?.data,
+ };
},
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Node,
- total: data?.payload?.data?.total,
- });
- }, [data?.payload?.data?.total]);
-
- const selectedNodeData = useMemo(() => {
- if (!selectedNodeUID) {
- return null;
- }
- if (groupBy.length > 0) {
- // If grouped by, return the node from the formatted grouped by nodes data
- return (
- nestedNodesData.find((node) => node.nodeUID === selectedNodeUID) || null
+ const fetchEntityData = useCallback(
+ async (
+ filters: K8sDetailsFilters,
+ signal?: AbortSignal,
+ ): Promise<{ data: K8sNodeData | null; error?: string | null }> => {
+ const response = await getK8sNodesList(
+ {
+ filters: filters.filters,
+ start: filters.start,
+ end: filters.end,
+ limit: 1,
+ offset: 0,
+ },
+ signal,
+ undefined,
+ dotMetricsEnabled,
);
- }
- // If not grouped by, return the node from the nodes data
- return nodesData.find((node) => node.nodeUID === selectedNodeUID) || null;
- }, [selectedNodeUID, groupBy.length, nodesData, nestedNodesData]);
-
- const openNodeInNewTab = (record: K8sNodesRowData): void => {
- const newParams = new URLSearchParams(document.location.search);
- newParams.set(INFRA_MONITORING_K8S_PARAMS_KEYS.NODE_UID, record.nodeUID);
- openInNewTab(
- buildAbsolutePath({
- relativePath: '',
- urlQueryString: newParams.toString(),
- }),
- );
- };
-
- const handleRowClick = (
- record: K8sNodesRowData,
- event: React.MouseEvent,
- ): void => {
- if (event && isModifierKeyPressed(event)) {
- openNodeInNewTab(record);
- return;
- }
- if (groupBy.length === 0) {
- setSelectedRowData(null);
- setSelectedNodeUID(record.nodeUID);
- } else {
- handleGroupByRowClick(record);
- }
-
- logEvent(InfraMonitoringEvents.ItemClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Node,
- });
- };
-
- const nestedColumns = useMemo(() => getK8sNodesListColumns([]), []);
- const isGroupedByAttribute = groupBy.length > 0;
+ const records = response.payload?.data.records || [];
- const handleExpandedRowViewAllClick = (): void => {
- if (!selectedRowData) {
- return;
- }
-
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- handleFiltersChange(filters);
-
- setCurrentPage(1);
- setSelectedRowData(null);
- setGroupBy([]);
- setOrderBy(null);
- };
-
- const expandedRowRender = (): JSX.Element => (
- <div className="expanded-table-container">
- {isErrorGroupedByRowData && (
- <Typography>{groupedByRowData?.error || 'Something went wrong'}</Typography>
- )}
- {isFetchingGroupedByRowData || isLoadingGroupedByRowData ? (
- <LoadingContainer />
- ) : (
- <div className="expanded-table">
- <Table
- className="expanded-table-view"
- columns={nestedColumns as ColumnType<K8sNodesRowData>[]}
- dataSource={formattedGroupedByNodesData}
- pagination={false}
- scroll={{ x: true }}
- tableLayout="fixed"
- size="small"
- loading={{
- spinning: isFetchingGroupedByRowData || isLoadingGroupedByRowData,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- showHeader={false}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => {
- if (isModifierKeyPressed(event)) {
- openNodeInNewTab(record);
- return;
- }
- setSelectedNodeUID(record.nodeUID);
- },
- className: 'expanded-clickable-row',
- })}
- />
-
- {groupedByRowData?.payload?.data?.total &&
- groupedByRowData?.payload?.data?.total > 10 ? (
- <div className="expanded-table-footer">
- <Button
- type="default"
- size="small"
- className="periscope-btn secondary"
- onClick={handleExpandedRowViewAllClick}
- >
- View All
- </Button>
- </div>
- ) : null}
- </div>
- )}
- </div>
- );
-
- const expandRowIconRenderer = ({
- expanded,
- onExpand,
- record,
- }: {
- expanded: boolean;
- onExpand: (
- record: K8sNodesRowData,
- e: React.MouseEvent<HTMLButtonElement>,
- ) => void;
- record: K8sNodesRowData;
- }): JSX.Element | null => {
- if (!isGroupedByAttribute) {
- return null;
- }
-
- return expanded ? (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronDown size={14} />
- </Button>
- ) : (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronRight size={14} />
- </Button>
- );
- };
-
- const handleCloseNodeDetail = (): void => {
- setSelectedNodeUID(null);
- setView(null);
- setTracesFilters(null);
- setEventsFilters(null);
- setLogFilters(null);
- };
-
- const handleGroupByChange = useCallback(
- (value: IBuilderQuery['groupBy']) => {
- const newGroupBy = [];
-
- for (let index = 0; index < value.length; index++) {
- const element = (value[index] as unknown) as string;
-
- const key = groupByFiltersData?.payload?.attributeKeys?.find(
- (k) => k.key === element,
- );
-
- if (key) {
- newGroupBy.push(key);
- }
- }
- // Reset pagination on switching to groupBy
- setCurrentPage(1);
- setGroupBy(newGroupBy);
- setExpandedRowKeys([]);
-
- logEvent(InfraMonitoringEvents.GroupByChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Node,
- });
+ return {
+ data: records.length > 0 ? records[0] : null,
+ error: response.error,
+ };
},
- [groupByFiltersData, setCurrentPage, setGroupBy],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- if (groupByFiltersData?.payload) {
- setGroupByOptions(
- groupByFiltersData?.payload?.attributeKeys?.map((filter) => ({
- value: filter.key,
- label: filter.key,
- })) || [],
- );
- }
- }, [groupByFiltersData]);
-
- const onPaginationChange = (page: number, pageSize: number): void => {
- setCurrentPage(page);
- setPageSize(pageSize);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Node,
- });
- };
-
- const showTableLoadingState =
- (isFetching || isLoading) && formattedNodesData.length === 0;
-
return (
- <div className="k8s-list">
- <K8sHeader
- isFiltersVisible={isFiltersVisible}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- defaultAddedColumns={defaultAddedColumns}
- handleFiltersChange={handleFiltersChange}
- groupByOptions={groupByOptions}
- isLoadingGroupByFilters={isLoadingGroupByFilters}
- handleGroupByChange={handleGroupByChange}
- selectedGroupBy={groupBy}
- entity={K8sCategory.NODES}
- showAutoRefresh={!selectedNodeData}
- />
- {isError && <Typography>{data?.error || 'Something went wrong'}</Typography>}
-
- <Table
- className="k8s-list-table nodes-list-table"
- dataSource={showTableLoadingState ? [] : formattedNodesData}
- columns={columns}
- pagination={{
- current: currentPage,
- pageSize,
- total: totalCount,
- showSizeChanger: true,
- hideOnSinglePage: false,
- onChange: onPaginationChange,
- }}
- scroll={{ x: true }}
- loading={{
- spinning: showTableLoadingState,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- locale={{
- emptyText: showTableLoadingState ? null : (
- <div className="no-filtered-hosts-message-container">
- <div className="no-filtered-hosts-message-content">
- <img
- src={emptyStateUrl}
- alt="thinking-emoji"
- className="empty-state-svg"
- />
-
- <Typography.Text className="no-filtered-hosts-message">
- This query had no results. Edit your query and try again!
- </Typography.Text>
- </div>
- </div>
- ),
- }}
- tableLayout="fixed"
- onChange={handleTableChange}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => handleRowClick(record, event),
- className: 'clickable-row',
- })}
- expandable={{
- expandedRowRender: isGroupedByAttribute ? expandedRowRender : undefined,
- expandIcon: expandRowIconRenderer,
- expandedRowKeys,
- }}
+ <>
+ <K8sBaseList<K8sNodeData>
+ controlListPrefix={controlListPrefix}
+ entity={InfraMonitoringEntity.NODES}
+ tableColumnsDefinitions={k8sNodesColumns}
+ tableColumns={k8sNodesColumnsConfig}
+ fetchListData={fetchListData}
+ renderRowData={k8sNodesRenderRowData}
+ eventCategory={InfraMonitoringEvents.Node}
/>
- <NodeDetails
- node={selectedNodeData}
- isModalTimeSelection
- onClose={handleCloseNodeDetail}
+ <K8sBaseDetails<K8sNodeData>
+ category={InfraMonitoringEntity.NODES}
+ eventCategory={InfraMonitoringEvents.Node}
+ getSelectedItemFilters={k8sNodeGetSelectedItemFilters}
+ fetchEntityData={fetchEntityData}
+ getEntityName={k8sNodeGetEntityName}
+ getInitialLogTracesFilters={k8sNodeInitialLogTracesFilter}
+ getInitialEventsFilters={k8sNodeInitialEventsFilter}
+ primaryFilterKeys={k8sNodeInitialFilters}
+ metadataConfig={k8sNodeDetailsMetadataConfig}
+ entityWidgetInfo={nodeWidgetInfo}
+ getEntityQueryPayload={getNodeMetricsQueryPayload}
+ queryKeyPrefix="node"
/>
- </div>
+ </>
);
}
diff --git a/frontend/src/container/InfraMonitoringK8s/Nodes/NodeDetails/NodeDetails.interfaces.ts b/frontend/src/container/InfraMonitoringK8s/Nodes/NodeDetails/NodeDetails.interfaces.ts
deleted file mode 100644
index eaa2613260..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Nodes/NodeDetails/NodeDetails.interfaces.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { K8sNodesData } from 'api/infraMonitoring/getK8sNodesList';
-
-export type NodeDetailsProps = {
- node: K8sNodesData | null;
- isModalTimeSelection: boolean;
- onClose: () => void;
-};
diff --git a/frontend/src/container/InfraMonitoringK8s/Nodes/NodeDetails/NodeDetails.tsx b/frontend/src/container/InfraMonitoringK8s/Nodes/NodeDetails/NodeDetails.tsx
deleted file mode 100644
index 56b91334ec..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Nodes/NodeDetails/NodeDetails.tsx
+++ /dev/null
@@ -1,635 +0,0 @@
-/* eslint-disable sonarjs/no-identical-functions */
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { Color, Spacing } from '@signozhq/design-tokens';
-import { Button, Divider, Drawer, Radio, Tooltip, Typography } from 'antd';
-import type { RadioChangeEvent } from 'antd/lib';
-import logEvent from 'api/common/logEvent';
-import { K8sNodesData } from 'api/infraMonitoring/getK8sNodesList';
-import { VIEW_TYPES, VIEWS } from 'components/HostMetricsDetail/constants';
-import { InfraMonitoringEvents } from 'constants/events';
-import { QueryParams } from 'constants/query';
-import {
- initialQueryBuilderFormValuesMap,
- initialQueryState,
-} from 'constants/queryBuilder';
-import ROUTES from 'constants/routes';
-import { filterDuplicateFilters } from 'container/InfraMonitoringK8s/commonUtils';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
-import NodeEvents from 'container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents';
-import {
- useInfraMonitoringEventsFilters,
- useInfraMonitoringLogFilters,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from 'container/InfraMonitoringK8s/hooks';
-import {
- CustomTimeType,
- Time,
-} from 'container/TopNav/DateTimeSelectionV2/types';
-import { useIsDarkMode } from 'hooks/useDarkMode';
-import useUrlQuery from 'hooks/useUrlQuery';
-import GetMinMax from 'lib/getMinMax';
-import {
- BarChart2,
- ChevronsLeftRight,
- Compass,
- DraftingCompass,
- ScrollText,
- X,
-} from 'lucide-react';
-import { AppState } from 'store/reducers';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import {
- IBuilderQuery,
- TagFilterItem,
-} from 'types/api/queryBuilder/queryBuilderData';
-import {
- LogsAggregatorOperator,
- TracesAggregatorOperator,
-} from 'types/common/queryBuilder';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { v4 as uuidv4 } from 'uuid';
-
-import NodeLogs from '../../EntityDetailsUtils/EntityLogs';
-import NodeMetrics from '../../EntityDetailsUtils/EntityMetrics';
-import NodeTraces from '../../EntityDetailsUtils/EntityTraces';
-import { QUERY_KEYS } from '../../EntityDetailsUtils/utils';
-import { getNodeMetricsQueryPayload, nodeWidgetInfo } from './constants';
-import { NodeDetailsProps } from './NodeDetails.interfaces';
-
-import '../../EntityDetailsUtils/entityDetails.styles.scss';
-
-function NodeDetails({
- node,
- onClose,
- isModalTimeSelection,
-}: NodeDetailsProps): JSX.Element {
- const { maxTime, minTime, selectedTime } = useSelector<
- AppState,
- GlobalReducer
- >((state) => state.globalTime);
-
- const startMs = useMemo(() => Math.floor(Number(minTime) / 1000000000), [
- minTime,
- ]);
- const endMs = useMemo(() => Math.floor(Number(maxTime) / 1000000000), [
- maxTime,
- ]);
-
- const urlQuery = useUrlQuery();
-
- const [modalTimeRange, setModalTimeRange] = useState(() => ({
- startTime: startMs,
- endTime: endMs,
- }));
-
- const lastSelectedInterval = useRef<Time | null>(null);
-
- const [selectedInterval, setSelectedInterval] = useState<Time>(
- lastSelectedInterval.current
- ? lastSelectedInterval.current
- : (selectedTime as Time),
- );
-
- const [selectedView, setSelectedView] = useInfraMonitoringView();
- const [logFiltersParam, setLogFiltersParam] = useInfraMonitoringLogFilters();
- const [
- tracesFiltersParam,
- setTracesFiltersParam,
- ] = useInfraMonitoringTracesFilters();
- const [
- eventsFiltersParam,
- setEventsFiltersParam,
- ] = useInfraMonitoringEventsFilters();
- const isDarkMode = useIsDarkMode();
-
- const initialFilters = useMemo(() => {
- const filters =
- selectedView === VIEW_TYPES.LOGS ? logFiltersParam : tracesFiltersParam;
- if (filters) {
- return filters;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_NODE_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s_node_name--string--resource--false',
- },
- op: '=',
- value: node?.meta.k8s_node_name || '',
- },
- ],
- };
- }, [
- node?.meta.k8s_node_name,
- selectedView,
- logFiltersParam,
- tracesFiltersParam,
- ]);
-
- const initialEventsFilters = useMemo(() => {
- if (eventsFiltersParam) {
- return eventsFiltersParam;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_KIND,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.kind--string--resource--false',
- },
- op: '=',
- value: 'Node',
- },
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.name--string--resource--false',
- },
- op: '=',
- value: node?.meta.k8s_node_name || '',
- },
- ],
- };
- }, [node?.meta.k8s_node_name, eventsFiltersParam]);
-
- const [logAndTracesFilters, setLogAndTracesFilters] = useState<
- IBuilderQuery['filters']
- >(initialFilters);
-
- const [eventsFilters, setEventsFilters] = useState<IBuilderQuery['filters']>(
- initialEventsFilters,
- );
-
- useEffect(() => {
- if (node) {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Node,
- });
- }
- }, [node]);
-
- useEffect(() => {
- setLogAndTracesFilters(initialFilters);
- setEventsFilters(initialEventsFilters);
- }, [initialFilters, initialEventsFilters]);
-
- useEffect(() => {
- const currentSelectedInterval = lastSelectedInterval.current || selectedTime;
- setSelectedInterval(currentSelectedInterval as Time);
-
- if (currentSelectedInterval !== 'custom') {
- const { maxTime, minTime } = GetMinMax(currentSelectedInterval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- }, [selectedTime, minTime, maxTime]);
-
- const handleTabChange = (e: RadioChangeEvent): void => {
- setSelectedView(e.target.value);
- setLogFiltersParam(null);
- setTracesFiltersParam(null);
- setEventsFiltersParam(null);
- logEvent(InfraMonitoringEvents.TabChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Node,
- view: e.target.value,
- });
- };
-
- const handleTimeChange = useCallback(
- (interval: Time | CustomTimeType, dateTimeRange?: [number, number]): void => {
- lastSelectedInterval.current = interval as Time;
- setSelectedInterval(interval as Time);
-
- if (interval === 'custom' && dateTimeRange) {
- setModalTimeRange({
- startTime: Math.floor(dateTimeRange[0] / 1000),
- endTime: Math.floor(dateTimeRange[1] / 1000),
- });
- } else {
- const { maxTime, minTime } = GetMinMax(interval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
-
- logEvent(InfraMonitoringEvents.TimeUpdated, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Node,
- interval,
- view: selectedView,
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeLogFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_NODE_NAME, QUERY_KEYS.K8S_CLUSTER_NAME].includes(
- item.key?.key ?? '',
- ),
- );
- const paginationFilter = value?.items?.find(
- (item) => item.key?.key === 'id',
- );
- const newFilters = value?.items?.filter(
- (item) =>
- item.key?.key !== 'id' && item.key?.key !== QUERY_KEYS.K8S_NODE_NAME,
- );
-
- if (newFilters && newFilters?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Node,
- view: InfraMonitoringEvents.LogsView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(newFilters || []),
- ...(paginationFilter ? [paginationFilter] : []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setLogFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeTracesFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_NODE_NAME, QUERY_KEYS.K8S_CLUSTER_NAME].includes(
- item.key?.key ?? '',
- ),
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Node,
- view: InfraMonitoringEvents.TracesView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(value?.items?.filter(
- (item) => item.key?.key !== QUERY_KEYS.K8S_NODE_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setTracesFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeEventsFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setEventsFilters((prevFilters) => {
- const nodeKindFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_KIND,
- );
- const nodeNameFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_NAME,
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Node,
- view: InfraMonitoringEvents.EventsView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: [
- nodeKindFilter,
- nodeNameFilter,
- ...(value?.items?.filter(
- (item) =>
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_KIND &&
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- };
-
- setEventsFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleExplorePagesRedirect = (): void => {
- if (selectedInterval !== 'custom') {
- urlQuery.set(QueryParams.relativeTime, selectedInterval);
- } else {
- urlQuery.delete(QueryParams.relativeTime);
- urlQuery.set(QueryParams.startTime, modalTimeRange.startTime.toString());
- urlQuery.set(QueryParams.endTime, modalTimeRange.endTime.toString());
- }
-
- logEvent(InfraMonitoringEvents.ExploreClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Node,
- view: selectedView,
- });
-
- if (selectedView === VIEW_TYPES.LOGS) {
- const filtersWithoutPagination = {
- ...logAndTracesFilters,
- items:
- logAndTracesFilters?.items?.filter((item) => item.key?.key !== 'id') || [],
- };
-
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.logs,
- aggregateOperator: LogsAggregatorOperator.NOOP,
- filters: filtersWithoutPagination,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.LOGS_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- } else if (selectedView === VIEW_TYPES.TRACES) {
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.traces,
- aggregateOperator: TracesAggregatorOperator.NOOP,
- filters: logAndTracesFilters,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.TRACES_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- }
- };
-
- const handleClose = (): void => {
- lastSelectedInterval.current = null;
- setSelectedInterval(selectedTime as Time);
-
- if (selectedTime !== 'custom') {
- const { maxTime, minTime } = GetMinMax(selectedTime);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- setSelectedView(VIEW_TYPES.METRICS);
- onClose();
- };
-
- return (
- <Drawer
- width="70%"
- title={
- <>
- <Divider type="vertical" />
- <Typography.Text className="title">
- {node?.meta.k8s_node_name}
- </Typography.Text>
- </>
- }
- placement="right"
- onClose={handleClose}
- open={!!node}
- style={{
- overscrollBehavior: 'contain',
- background: isDarkMode ? Color.BG_INK_400 : Color.BG_VANILLA_100,
- }}
- className="entity-detail-drawer"
- destroyOnClose
- closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
- >
- {node && (
- <>
- <div className="entity-detail-drawer__entity">
- <div className="entity-details-grid">
- <div className="labels-row">
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Node Name
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Cluster Name
- </Typography.Text>
- </div>
- <div className="values-row">
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={node.meta.k8s_node_name}>
- {node.meta.k8s_node_name}
- </Tooltip>
- </Typography.Text>
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title="Cluster name">{node.meta.k8s_cluster_name}</Tooltip>
- </Typography.Text>
- </div>
- </div>
- </div>
-
- <div className="views-tabs-container">
- <Radio.Group
- className="views-tabs"
- onChange={handleTabChange}
- value={selectedView}
- >
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.METRICS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.METRICS}
- >
- <div className="view-title">
- <BarChart2 size={14} />
- Metrics
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.LOGS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.LOGS}
- >
- <div className="view-title">
- <ScrollText size={14} />
- Logs
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.TRACES ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.TRACES}
- >
- <div className="view-title">
- <DraftingCompass size={14} />
- Traces
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.EVENTS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.EVENTS}
- >
- <div className="view-title">
- <ChevronsLeftRight size={14} />
- Events
- </div>
- </Radio.Button>
- </Radio.Group>
-
- {(selectedView === VIEW_TYPES.LOGS ||
- selectedView === VIEW_TYPES.TRACES) && (
- <Button
- icon={<Compass size={18} />}
- className="compass-button"
- onClick={handleExplorePagesRedirect}
- />
- )}
- </div>
- {selectedView === VIEW_TYPES.METRICS && (
- <NodeMetrics<K8sNodesData>
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- entity={node}
- entityWidgetInfo={nodeWidgetInfo}
- getEntityQueryPayload={getNodeMetricsQueryPayload}
- category={K8sCategory.NODES}
- queryKey="nodeMetrics"
- />
- )}
- {selectedView === VIEW_TYPES.LOGS && (
- <NodeLogs
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeLogFilters={handleChangeLogFilters}
- logFilters={logAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKeyFilters={[QUERY_KEYS.K8S_NODE_NAME, QUERY_KEYS.K8S_CLUSTER_NAME]}
- queryKey="nodeLogs"
- category={K8sCategory.NODES}
- />
- )}
- {selectedView === VIEW_TYPES.TRACES && (
- <NodeTraces
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeTracesFilters={handleChangeTracesFilters}
- tracesFilters={logAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKeyFilters={[QUERY_KEYS.K8S_NODE_NAME, QUERY_KEYS.K8S_CLUSTER_NAME]}
- queryKey="nodeTraces"
- category={InfraMonitoringEvents.Node}
- />
- )}
- {selectedView === VIEW_TYPES.EVENTS && (
- <NodeEvents
- timeRange={modalTimeRange}
- handleChangeEventFilters={handleChangeEventsFilters}
- filters={eventsFilters}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- category={K8sCategory.NODES}
- queryKey="nodeEvents"
- />
- )}
- </>
- )}
- </Drawer>
- );
-}
-
-export default NodeDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/Nodes/NodeDetails/index.ts b/frontend/src/container/InfraMonitoringK8s/Nodes/NodeDetails/index.ts
deleted file mode 100644
index c6617c46f9..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Nodes/NodeDetails/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import NodeDetails from './NodeDetails';
-
-export default NodeDetails;
diff --git a/frontend/src/api/infraMonitoring/getK8sClustersList.ts b/frontend/src/container/InfraMonitoringK8s/Nodes/api.ts
similarity index 66%
rename from frontend/src/api/infraMonitoring/getK8sClustersList.ts
rename to frontend/src/container/InfraMonitoringK8s/Nodes/api.ts
index f56d21bd81..bb72560656 100644
--- a/frontend/src/api/infraMonitoring/getK8sClustersList.ts
+++ b/frontend/src/container/InfraMonitoringK8s/Nodes/api.ts
@@ -1,13 +1,14 @@
import axios from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
+import { UnderscoreToDotMap } from 'api/utils';
import { AxiosError } from 'axios';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
-import { UnderscoreToDotMap } from '../utils';
+import { K8sBaseFilters } from '../Base/types';
-export interface K8sClustersListPayload {
+export interface K8sNodesListPayload {
filters: TagFilter;
groupBy?: BaseAutocompleteData[];
offset?: number;
@@ -18,23 +19,24 @@ export interface K8sClustersListPayload {
};
}
-export interface K8sClustersData {
- clusterUID: string;
- cpuUsage: number;
- cpuAllocatable: number;
- memoryUsage: number;
- memoryAllocatable: number;
+export interface K8sNodeData {
+ nodeUID: string;
+ nodeCPUUsage: number;
+ nodeCPUAllocatable: number;
+ nodeMemoryUsage: number;
+ nodeMemoryAllocatable: number;
meta: {
+ k8s_node_name: string;
+ k8s_node_uid: string;
k8s_cluster_name: string;
- k8s_cluster_uid: string;
};
}
-export interface K8sClustersListResponse {
+export interface K8sNodesListResponse {
status: string;
data: {
type: string;
- records: K8sClustersData[];
+ records: K8sNodeData[];
groups: null;
total: number;
sentAnyHostMetricsData: boolean;
@@ -42,30 +44,32 @@ export interface K8sClustersListResponse {
};
}
-export const clustersMetaMap = [
+// TODO(H4ad): Erase this whole file when migrating to openapi
+export const nodesMetaMap = [
+ { dot: 'k8s.node.name', under: 'k8s_node_name' },
+ { dot: 'k8s.node.uid', under: 'k8s_node_uid' },
{ dot: 'k8s.cluster.name', under: 'k8s_cluster_name' },
- { dot: 'k8s.cluster.uid', under: 'k8s_cluster_uid' },
] as const;
-export function mapClustersMeta(
+export function mapNodesMeta(
raw: Record<string, unknown>,
-): K8sClustersData['meta'] {
+): K8sNodeData['meta'] {
const out: Record<string, unknown> = { ...raw };
- clustersMetaMap.forEach(({ dot, under }) => {
+ nodesMetaMap.forEach(({ dot, under }) => {
if (dot in raw) {
const v = raw[dot];
out[under] = typeof v === 'string' ? v : raw[under];
}
});
- return out as K8sClustersData['meta'];
+ return out as K8sNodeData['meta'];
}
-export const getK8sClustersList = async (
- props: K8sClustersListPayload,
+export const getK8sNodesList = async (
+ props: K8sBaseFilters,
signal?: AbortSignal,
headers?: Record<string, string>,
dotMetricsEnabled = false,
-): Promise<SuccessResponse<K8sClustersListResponse> | ErrorResponse> => {
+): Promise<SuccessResponse<K8sNodesListResponse> | ErrorResponse> => {
try {
const requestProps =
dotMetricsEnabled && Array.isArray(props.filters?.items)
@@ -100,16 +104,16 @@ export const getK8sClustersList = async (
}
: props;
- const response = await axios.post('/clusters/list', requestProps, {
+ const response = await axios.post('/nodes/list', requestProps, {
signal,
headers,
});
- const payload: K8sClustersListResponse = response.data;
+ const payload: K8sNodesListResponse = response.data;
- // one-liner meta mapping
+ // one-liner to map dot→underscore
payload.data.records = payload.data.records.map((record) => ({
...record,
- meta: mapClustersMeta(record.meta as Record<string, unknown>),
+ meta: mapNodesMeta(record.meta as Record<string, unknown>),
}));
return {
diff --git a/frontend/src/container/InfraMonitoringK8s/Nodes/NodeDetails/constants.ts b/frontend/src/container/InfraMonitoringK8s/Nodes/constants.ts
similarity index 96%
rename from frontend/src/container/InfraMonitoringK8s/Nodes/NodeDetails/constants.ts
rename to frontend/src/container/InfraMonitoringK8s/Nodes/constants.ts
index f092fd1b08..909904b863 100644
--- a/frontend/src/container/InfraMonitoringK8s/Nodes/NodeDetails/constants.ts
+++ b/frontend/src/container/InfraMonitoringK8s/Nodes/constants.ts
@@ -1,11 +1,67 @@
-import { K8sNodesData } from 'api/infraMonitoring/getK8sNodesList';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { v4 } from 'uuid';
+import {
+ createFilterItem,
+ K8sDetailsMetadataConfig,
+} from '../Base/K8sBaseDetails';
+import { QUERY_KEYS } from '../EntityDetailsUtils/utils';
+import { K8sNodeData } from './api';
+
+export const k8sNodeGetSelectedItemFilters = (
+ selectedItemId: string,
+): TagFilter => {
+ return {
+ op: 'AND',
+ items: [
+ {
+ id: 'k8s_node_name',
+ key: {
+ key: 'k8s_node_name',
+ type: null,
+ },
+ op: '=',
+ value: selectedItemId,
+ },
+ ],
+ };
+};
+
+export const k8sNodeDetailsMetadataConfig: K8sDetailsMetadataConfig<K8sNodeData>[] = [
+ { label: 'Node Name', getValue: (p): string => p.meta.k8s_node_name },
+ {
+ label: 'Cluster Name',
+ getValue: (p): string => p.meta.k8s_cluster_name,
+ },
+];
+
+export const k8sNodeInitialFilters = [
+ QUERY_KEYS.K8S_NODE_NAME,
+ QUERY_KEYS.K8S_CLUSTER_NAME,
+];
+
+export const k8sNodeInitialEventsFilter = (
+ item: K8sNodeData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_KIND, 'Node'),
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_NAME, item.meta.k8s_node_name),
+];
+
+export const k8sNodeInitialLogTracesFilter = (
+ item: K8sNodeData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(QUERY_KEYS.K8S_NODE_NAME, item.meta.k8s_node_name),
+ createFilterItem(QUERY_KEYS.K8S_CLUSTER_NAME, item.meta.k8s_cluster_name),
+];
+
+export const k8sNodeGetEntityName = (item: K8sNodeData): string =>
+ item.meta.k8s_node_name;
+
export const nodeWidgetInfo = [
{
title: 'CPU Usage (cores)',
@@ -50,7 +106,7 @@ export const nodeWidgetInfo = [
];
export const getNodeMetricsQueryPayload = (
- node: K8sNodesData,
+ node: K8sNodeData,
start: number,
end: number,
dotMetricsEnabled: boolean,
diff --git a/frontend/src/container/InfraMonitoringK8s/Nodes/table.config.tsx b/frontend/src/container/InfraMonitoringK8s/Nodes/table.config.tsx
new file mode 100644
index 0000000000..bde81fe18e
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Nodes/table.config.tsx
@@ -0,0 +1,199 @@
+import { TableColumnType as ColumnType, Tooltip } from 'antd';
+import { Group } from 'lucide-react';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+
+import { K8sRenderedRowData } from '../Base/types';
+import { IEntityColumn } from '../Base/useInfraMonitoringTableColumnsStore';
+import { getGroupByEl, getGroupedByMeta, getRowKey } from '../Base/utils';
+import { formatBytes, ValidateColumnValueWrapper } from '../commonUtils';
+import { K8sNodeData, K8sNodesListPayload } from './api';
+
+import styles from './table.module.scss';
+
+export interface K8sNodesRowData {
+ key: string;
+ itemKey: string;
+ nodeUID: string;
+ nodeName: React.ReactNode;
+ clusterName: string;
+ cpu: React.ReactNode;
+ cpu_allocatable: React.ReactNode;
+ memory: React.ReactNode;
+ memory_allocatable: React.ReactNode;
+ groupedByMeta?: any;
+}
+
+export const k8sNodesColumns: IEntityColumn[] = [
+ {
+ label: 'Node Group',
+ value: 'nodeGroup',
+ id: 'nodeGroup',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-collapse',
+ },
+ {
+ label: 'Node Name',
+ value: 'nodeName',
+ id: 'nodeName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-expand',
+ },
+ {
+ label: 'Cluster Name',
+ value: 'clusterName',
+ id: 'clusterName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Usage (cores)',
+ value: 'cpu',
+ id: 'cpu',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Alloc (cores)',
+ value: 'cpu_allocatable',
+ id: 'cpu_allocatable',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Memory Usage (WSS)',
+ value: 'memory',
+ id: 'memory',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Memory Alloc (bytes)',
+ value: 'memory_allocatable',
+ id: 'memory_allocatable',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+];
+
+export const getK8sNodesListQuery = (): K8sNodesListPayload => ({
+ filters: {
+ items: [],
+ op: 'and',
+ },
+ orderBy: { columnName: 'cpu', order: 'desc' },
+});
+
+export const k8sNodesColumnsConfig: ColumnType<K8sRenderedRowData>[] = [
+ {
+ title: (
+ <div className={styles.entityGroupHeader}>
+ <Group size={14} /> NODE GROUP
+ </div>
+ ),
+ dataIndex: 'nodeGroup',
+ key: 'nodeGroup',
+ ellipsis: true,
+ width: 150,
+ align: 'left',
+ sorter: false,
+ },
+ {
+ title: <div>Node Name</div>,
+ dataIndex: 'nodeName',
+ key: 'nodeName',
+ ellipsis: true,
+ width: 80,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>Cluster Name</div>,
+ dataIndex: 'clusterName',
+ key: 'clusterName',
+ ellipsis: true,
+ width: 80,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Usage (cores)</div>,
+ dataIndex: 'cpu',
+ key: 'cpu',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Alloc (cores)</div>,
+ dataIndex: 'cpu_allocatable',
+ key: 'cpu_allocatable',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Memory Usage (WSS)</div>,
+ dataIndex: 'memory',
+ key: 'memory',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Memory Allocatable</div>,
+ dataIndex: 'memory_allocatable',
+ key: 'memory_allocatable',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+];
+
+export const k8sNodesRenderRowData = (
+ node: K8sNodeData,
+ groupBy: BaseAutocompleteData[],
+): K8sRenderedRowData => ({
+ key: getRowKey(
+ node,
+ () => node.nodeUID || node.meta.k8s_node_uid || node.meta.k8s_node_name,
+ groupBy,
+ ),
+ itemKey: node.meta.k8s_node_name,
+ nodeUID: node.nodeUID || node.meta.k8s_node_uid,
+ nodeName: (
+ <Tooltip title={node.meta.k8s_node_name}>
+ {node.meta.k8s_node_name || ''}
+ </Tooltip>
+ ),
+ clusterName: node.meta.k8s_cluster_name,
+ cpu: (
+ <ValidateColumnValueWrapper value={node.nodeCPUUsage}>
+ {node.nodeCPUUsage}
+ </ValidateColumnValueWrapper>
+ ),
+ memory: (
+ <ValidateColumnValueWrapper value={node.nodeMemoryUsage}>
+ {formatBytes(node.nodeMemoryUsage)}
+ </ValidateColumnValueWrapper>
+ ),
+ cpu_allocatable: (
+ <ValidateColumnValueWrapper value={node.nodeCPUAllocatable}>
+ {node.nodeCPUAllocatable}
+ </ValidateColumnValueWrapper>
+ ),
+ memory_allocatable: (
+ <ValidateColumnValueWrapper value={node.nodeMemoryAllocatable}>
+ {formatBytes(node.nodeMemoryAllocatable)}
+ </ValidateColumnValueWrapper>
+ ),
+ nodeGroup: getGroupByEl(node, groupBy),
+ ...node.meta,
+ groupedByMeta: getGroupedByMeta(node, groupBy),
+});
diff --git a/frontend/src/container/InfraMonitoringK8s/Nodes/table.module.scss b/frontend/src/container/InfraMonitoringK8s/Nodes/table.module.scss
new file mode 100644
index 0000000000..a2cdaf51c3
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Nodes/table.module.scss
@@ -0,0 +1,6 @@
+.entityGroupHeader {
+ display: flex;
+ align-items: center;
+ padding-left: var(--spacing-5);
+ gap: var(--spacing-5);
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Nodes/utils.tsx b/frontend/src/container/InfraMonitoringK8s/Nodes/utils.tsx
deleted file mode 100644
index 601c7d068e..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Nodes/utils.tsx
+++ /dev/null
@@ -1,225 +0,0 @@
-import { Color } from '@signozhq/design-tokens';
-import { TableColumnType as ColumnType, Tag, Tooltip } from 'antd';
-import {
- K8sNodesData,
- K8sNodesListPayload,
-} from 'api/infraMonitoring/getK8sNodesList';
-import { Group } from 'lucide-react';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-
-import { formatBytes, ValidateColumnValueWrapper } from '../commonUtils';
-import { IEntityColumn } from '../utils';
-
-export const defaultAddedColumns: IEntityColumn[] = [
- {
- label: 'Node Name',
- value: 'nodeName',
- id: 'nodeName',
- canRemove: false,
- },
- {
- label: 'Cluster Name',
- value: 'clusterStatus',
- id: 'clusterStatus',
- canRemove: false,
- },
- {
- label: 'CPU Usage (cores)',
- value: 'cpu',
- id: 'cpu',
- canRemove: false,
- },
- {
- label: 'CPU Alloc (cores)',
- value: 'cpu_allocatable',
- id: 'cpu_allocatable',
- canRemove: false,
- },
- {
- label: 'Memory Usage (WSS)',
- value: 'memory',
- id: 'memory',
- canRemove: false,
- },
- {
- label: 'Memory Alloc (bytes)',
- value: 'memory_allocatable',
- id: 'memory_allocatable',
- canRemove: false,
- },
-];
-
-export interface K8sNodesRowData {
- key: string;
- nodeUID: string;
- nodeName: React.ReactNode;
- clusterName: string;
- cpu: React.ReactNode;
- cpu_allocatable: React.ReactNode;
- memory: React.ReactNode;
- memory_allocatable: React.ReactNode;
- groupedByMeta?: any;
-}
-
-const nodeGroupColumnConfig = {
- title: (
- <div className="column-header entity-group-header">
- <Group size={14} /> NODE GROUP
- </div>
- ),
- dataIndex: 'nodeGroup',
- key: 'nodeGroup',
- ellipsis: true,
- width: 150,
- align: 'left',
- sorter: false,
- className: 'column entity-group-header',
-};
-
-export const getK8sNodesListQuery = (): K8sNodesListPayload => ({
- filters: {
- items: [],
- op: 'and',
- },
- orderBy: { columnName: 'cpu', order: 'desc' },
-});
-
-const columnsConfig = [
- {
- title: <div className="column-header-left name-header">Node Name</div>,
- dataIndex: 'nodeName',
- key: 'nodeName',
- ellipsis: true,
- width: 80,
- sorter: false,
- align: 'left',
- },
- {
- title: <div className="column-header-left name-header">Cluster Name</div>,
- dataIndex: 'clusterName',
- key: 'clusterName',
- ellipsis: true,
- width: 80,
- sorter: false,
- align: 'left',
- },
- {
- title: <div className="column-header-left">CPU Usage (cores)</div>,
- dataIndex: 'cpu',
- key: 'cpu',
- width: 80,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header-left">CPU Alloc (cores)</div>,
- dataIndex: 'cpu_allocatable',
- key: 'cpu_allocatable',
- width: 80,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header-left">Memory Usage (WSS)</div>,
- dataIndex: 'memory',
- key: 'memory',
- width: 80,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header-left">Memory Allocatable</div>,
- dataIndex: 'memory_allocatable',
- key: 'memory_allocatable',
- width: 80,
- sorter: true,
- align: 'left',
- },
-];
-
-export const getK8sNodesListColumns = (
- groupBy: IBuilderQuery['groupBy'],
-): ColumnType<K8sNodesRowData>[] => {
- if (groupBy.length > 0) {
- const filteredColumns = [...columnsConfig].filter(
- (column) => column.key !== 'nodeName',
- );
- filteredColumns.unshift(nodeGroupColumnConfig);
- return filteredColumns as ColumnType<K8sNodesRowData>[];
- }
-
- return columnsConfig as ColumnType<K8sNodesRowData>[];
-};
-
-const dotToUnder: Record<string, keyof K8sNodesData['meta']> = {
- 'k8s.node.name': 'k8s_node_name',
- 'k8s.cluster.name': 'k8s_cluster_name',
- 'k8s.node.uid': 'k8s_node_uid',
-};
-
-const getGroupByEle = (
- node: K8sNodesData,
- groupBy: IBuilderQuery['groupBy'],
-): React.ReactNode => {
- const groupByValues: string[] = [];
-
- groupBy.forEach((group) => {
- const rawKey = group.key as string;
-
- // Choose mapped key if present, otherwise use rawKey
- const metaKey = (dotToUnder[rawKey] ?? rawKey) as keyof typeof node.meta;
-
- const value = node.meta[metaKey];
-
- groupByValues.push(value);
- });
-
- return (
- <div className="pod-group">
- {groupByValues.map((value) => (
- <Tag key={value} color={Color.BG_SLATE_400} className="pod-group-tag-item">
- {value === '' ? '<no-value>' : value}
- </Tag>
- ))}
- </div>
- );
-};
-
-export const formatDataForTable = (
- data: K8sNodesData[],
- groupBy: IBuilderQuery['groupBy'],
-): K8sNodesRowData[] =>
- data.map((node, index) => ({
- key: `${node.nodeUID}-${index}`,
- nodeUID: node.nodeUID || '',
- nodeName: (
- <Tooltip title={node.meta.k8s_node_name}>
- {node.meta.k8s_node_name || ''}
- </Tooltip>
- ),
- clusterName: node.meta.k8s_cluster_name,
- cpu: (
- <ValidateColumnValueWrapper value={node.nodeCPUUsage}>
- {node.nodeCPUUsage}
- </ValidateColumnValueWrapper>
- ),
- memory: (
- <ValidateColumnValueWrapper value={node.nodeMemoryUsage}>
- {formatBytes(node.nodeMemoryUsage)}
- </ValidateColumnValueWrapper>
- ),
- cpu_allocatable: (
- <ValidateColumnValueWrapper value={node.nodeCPUAllocatable}>
- {node.nodeCPUAllocatable}
- </ValidateColumnValueWrapper>
- ),
- memory_allocatable: (
- <ValidateColumnValueWrapper value={node.nodeMemoryAllocatable}>
- {formatBytes(node.nodeMemoryAllocatable)}
- </ValidateColumnValueWrapper>
- ),
- nodeGroup: getGroupByEle(node, groupBy),
- meta: node.meta,
- ...node.meta,
- groupedByMeta: node.meta,
- }));
diff --git a/frontend/src/container/InfraMonitoringK8s/Pods/K8sPodLists.tsx b/frontend/src/container/InfraMonitoringK8s/Pods/K8sPodLists.tsx
index 890e6c03f6..6ba77661d3 100644
--- a/frontend/src/container/InfraMonitoringK8s/Pods/K8sPodLists.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/Pods/K8sPodLists.tsx
@@ -1,755 +1,118 @@
-import React, { useCallback, useEffect, useMemo, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { LoadingOutlined } from '@ant-design/icons';
-import {
- Button,
- Spin,
- Table,
- TableColumnType as ColumnType,
- TablePaginationConfig,
- TableProps,
- Typography,
-} from 'antd';
-import type { SorterResult } from 'antd/es/table/interface';
-import get from 'api/browser/localstorage/get';
-import set from 'api/browser/localstorage/set';
-import logEvent from 'api/common/logEvent';
-import { K8sPodsListPayload } from 'api/infraMonitoring/getK8sPodsList';
-import classNames from 'classnames';
+import React, { useCallback } from 'react';
import { InfraMonitoringEvents } from 'constants/events';
import { FeatureKeys } from 'constants/features';
-import { useGetK8sPodsList } from 'hooks/infraMonitoring/useGetK8sPodsList';
-import { useGetAggregateKeys } from 'hooks/queryBuilder/useGetAggregateKeys';
-import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
-import { ChevronDown, ChevronRight, CornerDownRight } from 'lucide-react';
import { useAppContext } from 'providers/App/App';
-import { AppState } from 'store/reducers';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { buildAbsolutePath, isModifierKeyPressed } from 'utils/app';
-import { openInNewTab } from 'utils/navigation';
-
-import emptyStateUrl from '@/assets/Icons/emptyState.svg';
+import K8sBaseDetails, { K8sDetailsFilters } from '../Base/K8sBaseDetails';
+import { K8sBaseList } from '../Base/K8sBaseList';
+import { K8sBaseFilters } from '../Base/types';
+import { InfraMonitoringEntity } from '../constants';
+import { getK8sPodsList, K8sPodsData } from './api';
import {
- GetK8sEntityToAggregateAttribute,
- INFRA_MONITORING_K8S_PARAMS_KEYS,
- K8sCategory,
-} from '../constants';
+ getPodMetricsQueryPayload,
+ k8sPodDetailsMetadataConfig,
+ k8sPodGetEntityName,
+ k8sPodGetSelectedItemFilters,
+ k8sPodInitialEventsFilter,
+ k8sPodInitialFilters,
+ k8sPodInitialLogTracesFilter,
+ podWidgetInfo,
+} from './constants';
import {
- useInfraMonitoringCurrentPage,
- useInfraMonitoringEventsFilters,
- useInfraMonitoringGroupBy,
- useInfraMonitoringLogFilters,
- useInfraMonitoringOrderBy,
- useInfraMonitoringPodUID,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from '../hooks';
-import K8sHeader from '../K8sHeader';
-import LoadingContainer from '../LoadingContainer';
-import {
- defaultAddedColumns,
- defaultAvailableColumns,
- formatDataForTable,
- getK8sPodsListColumns,
- getK8sPodsListQuery,
- IEntityColumn,
- K8sPodsRowData,
- usePageSize,
-} from '../utils';
-import PodDetails from './PodDetails/PodDetails';
-
-import '../InfraMonitoringK8s.styles.scss';
+ k8sPodColumns,
+ k8sPodColumnsConfig,
+ k8sPodRenderRowData,
+} from './table.config';
function K8sPodsList({
- isFiltersVisible,
- handleFilterVisibilityChange,
- quickFiltersLastUpdated,
+ controlListPrefix,
}: {
- isFiltersVisible: boolean;
- handleFilterVisibilityChange: () => void;
- quickFiltersLastUpdated: number;
+ controlListPrefix?: React.ReactNode;
}): JSX.Element {
- const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
- (state) => state.globalTime,
- );
-
- const [currentPage, setCurrentPage] = useInfraMonitoringCurrentPage();
- const [groupBy, setGroupBy] = useInfraMonitoringGroupBy();
- const [orderBy, setOrderBy] = useInfraMonitoringOrderBy();
- const [defaultOrderBy] = useState(orderBy);
- const [selectedPodUID, setSelectedPodUID] = useInfraMonitoringPodUID();
- const [, setView] = useInfraMonitoringView();
- const [, setTracesFilters] = useInfraMonitoringTracesFilters();
- const [, setEventsFilters] = useInfraMonitoringEventsFilters();
- const [, setLogFilters] = useInfraMonitoringLogFilters();
-
- const [filtersInitialised, setFiltersInitialised] = useState(false);
-
- const [addedColumns, setAddedColumns] = useState<IEntityColumn[]>([]);
-
- const [availableColumns, setAvailableColumns] = useState<IEntityColumn[]>(
- defaultAvailableColumns,
- );
-
- const [selectedRowData, setSelectedRowData] = useState<K8sPodsRowData | null>(
- null,
- );
-
- const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
-
- const [groupByOptions, setGroupByOptions] = useState<
- { value: string; label: string }[]
- >([]);
-
- const { currentQuery } = useQueryBuilder();
-
- const queryFilters = useMemo(
- () =>
- currentQuery?.builder?.queryData[0]?.filters || {
- items: [],
- op: 'and',
- },
- [currentQuery?.builder?.queryData],
- );
-
const { featureFlags } = useAppContext();
const dotMetricsEnabled =
featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
?.active || false;
- const {
- data: groupByFiltersData,
- isLoading: isLoadingGroupByFilters,
- } = useGetAggregateKeys(
- {
- dataSource: currentQuery.builder.queryData[0].dataSource,
- aggregateAttribute: GetK8sEntityToAggregateAttribute(
- K8sCategory.PODS,
+ const fetchListData = useCallback(
+ async (filters: K8sBaseFilters, signal?: AbortSignal) => {
+ filters.orderBy ||= {
+ columnName: 'cpu',
+ order: 'desc',
+ };
+
+ const response = await getK8sPodsList(
+ filters,
+ signal,
+ undefined,
dotMetricsEnabled,
- ),
- aggregateOperator: 'noop',
- searchText: '',
- tagType: '',
- },
- {
- queryKey: [currentQuery.builder.queryData[0].dataSource, 'noop'],
- },
- true, // isInfraMonitoring
- K8sCategory.PODS, // infraMonitoringEntity
- );
-
- // Reset pagination every time quick filters are changed
- useEffect(() => {
- if (quickFiltersLastUpdated !== -1) {
- setCurrentPage(1);
- }
- }, [quickFiltersLastUpdated, setCurrentPage]);
-
- useEffect(() => {
- const addedColumns = JSON.parse(get('k8sPodsAddedColumns') ?? '[]');
-
- if (addedColumns && addedColumns.length > 0) {
- const availableColumns = defaultAvailableColumns.filter(
- (column) => !addedColumns.includes(column.id),
);
- const newAddedColumns = defaultAvailableColumns.filter((column) =>
- addedColumns.includes(column.id),
- );
-
- setAvailableColumns(availableColumns);
- setAddedColumns(newAddedColumns);
- }
- }, []);
-
- const { pageSize, setPageSize } = usePageSize(K8sCategory.PODS);
-
- const query = useMemo(() => {
- const baseQuery = getK8sPodsListQuery();
-
- const queryPayload = {
- ...baseQuery,
- limit: pageSize,
- offset: (currentPage - 1) * pageSize,
- filters: queryFilters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
-
- if (groupBy.length > 0) {
- queryPayload.groupBy = groupBy;
- }
-
- return queryPayload;
- }, [pageSize, currentPage, queryFilters, minTime, maxTime, orderBy, groupBy]);
-
- const queryKey = useMemo(() => {
- if (selectedPodUID) {
- return [
- 'podList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- ];
- }
- return [
- 'podList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- String(minTime),
- String(maxTime),
- ];
- }, [
- selectedPodUID,
- pageSize,
- currentPage,
- queryFilters,
- orderBy,
- groupBy,
- minTime,
- maxTime,
- ]);
-
- const { data, isFetching, isLoading, isError } = useGetK8sPodsList(
- query as K8sPodsListPayload,
- {
- queryKey,
- enabled: !!query,
- keepPreviousData: true,
+ return {
+ data: response.payload?.data.records || [],
+ total: response.payload?.data.total || 0,
+ error: response.error,
+ rawData: response.payload?.data,
+ };
},
- undefined,
- dotMetricsEnabled,
- );
-
- const createFiltersForSelectedRowData = (
- selectedRowData: K8sPodsRowData,
- ): IBuilderQuery['filters'] => {
- const baseFilters: IBuilderQuery['filters'] = {
- items: [...queryFilters.items],
- op: 'and',
- };
-
- if (!selectedRowData) {
- return baseFilters;
- }
-
- const { groupedByMeta } = selectedRowData;
-
- for (const key of Object.keys(groupedByMeta)) {
- baseFilters.items.push({
- key: {
- key,
- type: null,
+ [dotMetricsEnabled],
+ );
+
+ const fetchEntityData = useCallback(
+ async (
+ filters: K8sDetailsFilters,
+ signal?: AbortSignal,
+ ): Promise<{ data: K8sPodsData | null; error?: string | null }> => {
+ const response = await getK8sPodsList(
+ {
+ filters: filters.filters,
+ start: filters.start,
+ end: filters.end,
+ limit: 1,
+ offset: 0,
},
- op: '=',
- value: groupedByMeta[key],
- id: key,
- });
- }
-
- return baseFilters;
- };
-
- const fetchGroupedByRowDataQuery = useMemo(() => {
- if (!selectedRowData) {
- return null;
- }
-
- const baseQuery = getK8sPodsListQuery();
-
- const filters = createFiltersForSelectedRowData(selectedRowData);
-
- return {
- ...baseQuery,
- limit: 10,
- offset: 0,
- filters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [minTime, maxTime, orderBy, selectedRowData]);
-
- const groupedByRowDataQueryKey = useMemo(() => {
- // be careful with what you serialize from selectedRowData
- // since it's react node, it could contain circular references
- const selectedRowDataKey = JSON.stringify(selectedRowData?.groupedByMeta);
- if (selectedPodUID) {
- return [
- 'podList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- ];
- }
- return [
- 'podList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- String(minTime),
- String(maxTime),
- ];
- }, [queryFilters, orderBy, selectedPodUID, minTime, maxTime, selectedRowData]);
-
- const {
- data: groupedByRowData,
- isFetching: isFetchingGroupedByRowData,
- isLoading: isLoadingGroupedByRowData,
- isError: isErrorGroupedByRowData,
- refetch: fetchGroupedByRowData,
- } = useGetK8sPodsList(
- fetchGroupedByRowDataQuery as K8sPodsListPayload,
- {
- queryKey: groupedByRowDataQueryKey,
- enabled: !!fetchGroupedByRowDataQuery && !!selectedRowData,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const podsData = useMemo(() => data?.payload?.data?.records || [], [data]);
- const totalCount = data?.payload?.data?.total || 0;
-
- const nestedPodsData = useMemo(() => {
- if (!selectedRowData || !groupedByRowData?.payload?.data.records) {
- return [];
- }
- return groupedByRowData?.payload?.data?.records || [];
- }, [groupedByRowData, selectedRowData]);
-
- const formattedPodsData = useMemo(
- () => formatDataForTable(podsData, groupBy),
- [podsData, groupBy],
- );
-
- const formattedGroupedByPodsData = useMemo(
- () =>
- formatDataForTable(groupedByRowData?.payload?.data?.records || [], groupBy),
- [groupedByRowData, groupBy],
- );
-
- const columns = useMemo(
- () => getK8sPodsListColumns(addedColumns, groupBy, defaultOrderBy),
- [addedColumns, groupBy, defaultOrderBy],
- );
-
- const handleTableChange: TableProps<K8sPodsRowData>['onChange'] = useCallback(
- (
- pagination: TablePaginationConfig,
- _filters: Record<string, (string | number | boolean)[] | null>,
- sorter: SorterResult<K8sPodsRowData> | SorterResult<K8sPodsRowData>[],
- ): void => {
- if (pagination.current) {
- setCurrentPage(pagination.current);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Pod,
- });
- }
-
- if ('field' in sorter && sorter.order) {
- setOrderBy({
- columnName: sorter.field as string,
- order: (sorter.order === 'ascend' ? 'asc' : 'desc') as 'asc' | 'desc',
- });
- } else {
- setOrderBy(null);
- }
- },
- [setCurrentPage, setOrderBy],
- );
-
- const { handleChangeQueryData } = useQueryOperations({
- index: 0,
- query: currentQuery.builder.queryData[0],
- entityVersion: '',
- });
-
- const handleFiltersChange = useCallback(
- (value: IBuilderQuery['filters']): void => {
- handleChangeQueryData('filters', value);
- if (filtersInitialised) {
- setCurrentPage(1);
- } else {
- setFiltersInitialised(true);
- }
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Pod,
- });
- }
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleGroupByChange = useCallback(
- (value: IBuilderQuery['groupBy']) => {
- const newGroupBy = [];
-
- for (let index = 0; index < value.length; index++) {
- const element = (value[index] as unknown) as string;
-
- const key = groupByFiltersData?.payload?.attributeKeys?.find(
- (k) => k.key === element,
- );
-
- if (key) {
- newGroupBy.push(key);
- }
- }
-
- // Reset pagination on switching to groupBy
- setCurrentPage(1);
- setGroupBy(newGroupBy);
- setExpandedRowKeys([]);
-
- logEvent(InfraMonitoringEvents.GroupByChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Pod,
- });
- },
- [groupByFiltersData, setCurrentPage, setGroupBy],
- );
-
- useEffect(() => {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Pod,
- total: data?.payload?.data?.total,
- });
- }, [data?.payload?.data?.total]);
-
- const selectedPodData = useMemo(() => {
- if (!selectedPodUID) {
- return null;
- }
- if (groupBy.length > 0) {
- // If grouped by, return the pod from the formatted grouped by pods data
- return nestedPodsData.find((pod) => pod.podUID === selectedPodUID) || null;
- }
- // If not grouped by, return the node from the nodes data
- return podsData.find((pod) => pod.podUID === selectedPodUID) || null;
- }, [selectedPodUID, groupBy.length, podsData, nestedPodsData]);
-
- const handleGroupByRowClick = (record: K8sPodsRowData): void => {
- setSelectedRowData(record);
-
- if (expandedRowKeys.includes(record.key)) {
- setExpandedRowKeys(expandedRowKeys.filter((key) => key !== record.key));
- } else {
- setExpandedRowKeys([record.key]);
- }
- };
-
- useEffect(() => {
- if (selectedRowData) {
- fetchGroupedByRowData();
- }
- }, [selectedRowData, fetchGroupedByRowData]);
-
- const openPodInNewTab = (record: K8sPodsRowData): void => {
- const newParams = new URLSearchParams(document.location.search);
- newParams.set(INFRA_MONITORING_K8S_PARAMS_KEYS.POD_UID, record.podUID);
- openInNewTab(
- buildAbsolutePath({
- relativePath: '',
- urlQueryString: newParams.toString(),
- }),
- );
- };
-
- const handleRowClick = (
- record: K8sPodsRowData,
- event: React.MouseEvent,
- ): void => {
- if (event && isModifierKeyPressed(event)) {
- openPodInNewTab(record);
- return;
- }
- if (groupBy.length === 0) {
- setSelectedPodUID(record.podUID);
- setSelectedRowData(null);
- } else {
- handleGroupByRowClick(record);
- }
-
- logEvent(InfraMonitoringEvents.ItemClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Pod,
- });
- };
-
- const handleClosePodDetail = (): void => {
- setSelectedPodUID(null);
- setView(null);
- setTracesFilters(null);
- setEventsFilters(null);
- setLogFilters(null);
- };
-
- const handleAddColumn = useCallback(
- (column: IEntityColumn): void => {
- setAddedColumns((prev) => [...prev, column]);
-
- setAvailableColumns((prev) => prev.filter((c) => c.value !== column.value));
- },
- [setAddedColumns, setAvailableColumns],
- );
-
- // Update local storage when added columns updated
- useEffect(() => {
- const addedColumnIDs = addedColumns.map((column) => column.id);
-
- set('k8sPodsAddedColumns', JSON.stringify(addedColumnIDs));
- }, [addedColumns]);
-
- useEffect(() => {
- if (groupByFiltersData?.payload) {
- setGroupByOptions(
- groupByFiltersData?.payload?.attributeKeys?.map((filter) => ({
- value: filter.key,
- label: filter.key,
- })) || [],
+ signal,
+ undefined,
+ dotMetricsEnabled,
);
- }
- }, [groupByFiltersData]);
- const handleRemoveColumn = useCallback(
- (column: IEntityColumn): void => {
- setAddedColumns((prev) => prev.filter((c) => c.value !== column.value));
+ const records = response.payload?.data.records || [];
- setAvailableColumns((prev) => [...prev, column]);
+ return {
+ data: records.length > 0 ? records[0] : null,
+ error: response.error,
+ };
},
- [setAddedColumns, setAvailableColumns],
- );
-
- const nestedColumns = useMemo(
- () => getK8sPodsListColumns(addedColumns, [], defaultOrderBy),
- [addedColumns, defaultOrderBy],
- );
-
- const isGroupedByAttribute = groupBy.length > 0;
-
- const handleExpandedRowViewAllClick = (): void => {
- if (!selectedRowData) {
- return;
- }
-
- const filters = createFiltersForSelectedRowData(selectedRowData);
-
- handleFiltersChange(filters);
-
- setCurrentPage(1);
- setSelectedRowData(null);
- setGroupBy([]);
- setOrderBy(null);
- };
-
- const expandedRowRender = (): JSX.Element => (
- <div className="expanded-table-container">
- {isErrorGroupedByRowData && (
- <Typography>{groupedByRowData?.error || 'Something went wrong'}</Typography>
- )}
-
- {isFetchingGroupedByRowData || isLoadingGroupedByRowData ? (
- <LoadingContainer />
- ) : (
- <div className="expanded-table">
- <Table
- columns={nestedColumns as ColumnType<K8sPodsRowData>[]}
- dataSource={formattedGroupedByPodsData}
- pagination={false}
- scroll={{ x: true }}
- tableLayout="fixed"
- showHeader={false}
- loading={{
- spinning: isFetchingGroupedByRowData || isLoadingGroupedByRowData,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- onRow={(
- record: K8sPodsRowData,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => {
- if (isModifierKeyPressed(event)) {
- openPodInNewTab(record);
- return;
- }
- setSelectedPodUID(record.podUID);
- },
- className: 'expanded-clickable-row',
- })}
- />
-
- {groupedByRowData?.payload?.data?.total &&
- groupedByRowData?.payload?.data?.total > 10 && (
- <div className="expanded-table-footer">
- <Button
- type="default"
- size="small"
- className="periscope-btn secondary"
- onClick={handleExpandedRowViewAllClick}
- >
- <CornerDownRight size={14} />
- View All
- </Button>
- </div>
- )}
- </div>
- )}
- </div>
+ [dotMetricsEnabled],
);
- const expandRowIconRenderer = ({
- expanded,
- onExpand,
- record,
- }: {
- expanded: boolean;
- onExpand: (
- record: K8sPodsRowData,
- e: React.MouseEvent<HTMLButtonElement>,
- ) => void;
- record: K8sPodsRowData;
- }): JSX.Element | null => {
- if (!isGroupedByAttribute) {
- return null;
- }
-
- return expanded ? (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronDown size={14} />
- </Button>
- ) : (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronRight size={14} />
- </Button>
- );
- };
-
- const onPaginationChange = (page: number, pageSize: number): void => {
- setCurrentPage(page);
- setPageSize(pageSize);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Pod,
- });
- };
-
- const showTableLoadingState =
- (isFetching || isLoading) && formattedPodsData.length === 0;
-
return (
- <div className="k8s-list">
- <K8sHeader
- selectedGroupBy={groupBy}
- groupByOptions={groupByOptions}
- isLoadingGroupByFilters={isLoadingGroupByFilters}
- isFiltersVisible={isFiltersVisible}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- defaultAddedColumns={defaultAddedColumns}
- addedColumns={addedColumns}
- availableColumns={availableColumns}
- handleFiltersChange={handleFiltersChange}
- handleGroupByChange={handleGroupByChange}
- onAddColumn={handleAddColumn}
- onRemoveColumn={handleRemoveColumn}
- entity={K8sCategory.PODS}
- showAutoRefresh={!selectedPodData}
+ <>
+ <K8sBaseList<K8sPodsData>
+ controlListPrefix={controlListPrefix}
+ entity={InfraMonitoringEntity.PODS}
+ tableColumnsDefinitions={k8sPodColumns}
+ tableColumns={k8sPodColumnsConfig}
+ fetchListData={fetchListData}
+ renderRowData={k8sPodRenderRowData}
+ eventCategory={InfraMonitoringEvents.Pod}
/>
- {isError && <Typography>{data?.error || 'Something went wrong'}</Typography>}
-
- <Table
- className={classNames('k8s-list-table', {
- 'expanded-k8s-list-table': isGroupedByAttribute,
- })}
- dataSource={showTableLoadingState ? [] : formattedPodsData}
- columns={columns}
- pagination={{
- current: currentPage,
- pageSize,
- total: totalCount,
- showSizeChanger: true,
- hideOnSinglePage: false,
- onChange: onPaginationChange,
- }}
- loading={{
- spinning: showTableLoadingState,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- locale={{
- emptyText: showTableLoadingState ? null : (
- <div className="no-filtered-hosts-message-container">
- <div className="no-filtered-hosts-message-content">
- <img
- src={emptyStateUrl}
- alt="thinking-emoji"
- className="empty-state-svg"
- />
- <Typography.Text className="no-filtered-hosts-message">
- This query had no results. Edit your query and try again!
- </Typography.Text>
- </div>
- </div>
- ),
- }}
- scroll={{ x: true }}
- tableLayout="fixed"
- onChange={handleTableChange}
- onRow={(
- record: K8sPodsRowData,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => handleRowClick(record, event),
- className: 'clickable-row',
- })}
- expandable={{
- expandedRowRender: isGroupedByAttribute ? expandedRowRender : undefined,
- expandIcon: expandRowIconRenderer,
- expandedRowKeys,
- }}
+ <K8sBaseDetails<K8sPodsData>
+ category={InfraMonitoringEntity.PODS}
+ eventCategory={InfraMonitoringEvents.Pod}
+ getSelectedItemFilters={k8sPodGetSelectedItemFilters}
+ fetchEntityData={fetchEntityData}
+ getEntityName={k8sPodGetEntityName}
+ getInitialLogTracesFilters={k8sPodInitialLogTracesFilter}
+ getInitialEventsFilters={k8sPodInitialEventsFilter}
+ primaryFilterKeys={k8sPodInitialFilters}
+ metadataConfig={k8sPodDetailsMetadataConfig}
+ entityWidgetInfo={podWidgetInfo}
+ getEntityQueryPayload={getPodMetricsQueryPayload}
+ queryKeyPrefix="pod"
/>
-
- {selectedPodData && (
- <PodDetails
- pod={selectedPodData}
- isModalTimeSelection
- onClose={handleClosePodDetail}
- />
- )}
- </div>
+ </>
);
}
diff --git a/frontend/src/container/InfraMonitoringK8s/Pods/PodDetails/PodDetail.interfaces.ts b/frontend/src/container/InfraMonitoringK8s/Pods/PodDetails/PodDetail.interfaces.ts
deleted file mode 100644
index 7f07be841e..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Pods/PodDetails/PodDetail.interfaces.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { K8sPodsData } from 'api/infraMonitoring/getK8sPodsList';
-
-export type PodDetailProps = {
- pod: K8sPodsData | null;
- isModalTimeSelection: boolean;
- onClose: () => void;
-};
diff --git a/frontend/src/container/InfraMonitoringK8s/Pods/PodDetails/PodDetails.tsx b/frontend/src/container/InfraMonitoringK8s/Pods/PodDetails/PodDetails.tsx
deleted file mode 100644
index 310b23ab52..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Pods/PodDetails/PodDetails.tsx
+++ /dev/null
@@ -1,680 +0,0 @@
-/* eslint-disable sonarjs/no-identical-functions */
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { Color, Spacing } from '@signozhq/design-tokens';
-import { Button, Divider, Drawer, Radio, Tooltip, Typography } from 'antd';
-import type { RadioChangeEvent } from 'antd/lib';
-import logEvent from 'api/common/logEvent';
-import { K8sPodsData } from 'api/infraMonitoring/getK8sPodsList';
-import { VIEW_TYPES, VIEWS } from 'components/HostMetricsDetail/constants';
-import { InfraMonitoringEvents } from 'constants/events';
-import { QueryParams } from 'constants/query';
-import {
- initialQueryBuilderFormValuesMap,
- initialQueryState,
-} from 'constants/queryBuilder';
-import ROUTES from 'constants/routes';
-import { filterDuplicateFilters } from 'container/InfraMonitoringK8s/commonUtils';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
-import { QUERY_KEYS } from 'container/InfraMonitoringK8s/EntityDetailsUtils/utils';
-import {
- useInfraMonitoringEventsFilters,
- useInfraMonitoringLogFilters,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from 'container/InfraMonitoringK8s/hooks';
-import {
- CustomTimeType,
- Time,
-} from 'container/TopNav/DateTimeSelectionV2/types';
-import { useIsDarkMode } from 'hooks/useDarkMode';
-import useUrlQuery from 'hooks/useUrlQuery';
-import GetMinMax from 'lib/getMinMax';
-import {
- BarChart2,
- ChevronsLeftRight,
- Compass,
- DraftingCompass,
- ScrollText,
- X,
-} from 'lucide-react';
-import { AppState } from 'store/reducers';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import {
- IBuilderQuery,
- TagFilterItem,
-} from 'types/api/queryBuilder/queryBuilderData';
-import {
- LogsAggregatorOperator,
- TracesAggregatorOperator,
-} from 'types/common/queryBuilder';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { v4 as uuidv4 } from 'uuid';
-
-import PodEvents from '../../EntityDetailsUtils/EntityEvents';
-import PodLogs from '../../EntityDetailsUtils/EntityLogs';
-import PodMetrics from '../../EntityDetailsUtils/EntityMetrics';
-import PodTraces from '../../EntityDetailsUtils/EntityTraces';
-import { getPodMetricsQueryPayload, podWidgetInfo } from './constants';
-import { PodDetailProps } from './PodDetail.interfaces';
-
-import '../../EntityDetailsUtils/entityDetails.styles.scss';
-
-const TimeRangeOffset = 1000000000;
-
-function PodDetails({
- pod,
- onClose,
- isModalTimeSelection,
-}: PodDetailProps): JSX.Element {
- const { maxTime, minTime, selectedTime } = useSelector<
- AppState,
- GlobalReducer
- >((state) => state.globalTime);
-
- const startMs = useMemo(() => Math.floor(Number(minTime) / TimeRangeOffset), [
- minTime,
- ]);
- const endMs = useMemo(() => Math.floor(Number(maxTime) / TimeRangeOffset), [
- maxTime,
- ]);
-
- const urlQuery = useUrlQuery();
-
- const [modalTimeRange, setModalTimeRange] = useState(() => ({
- startTime: startMs,
- endTime: endMs,
- }));
-
- const lastSelectedInterval = useRef<Time | null>(null);
-
- const [selectedInterval, setSelectedInterval] = useState<Time>(
- lastSelectedInterval.current
- ? lastSelectedInterval.current
- : (selectedTime as Time),
- );
-
- const [selectedView, setSelectedView] = useInfraMonitoringView();
- const [logFiltersParam, setLogFiltersParam] = useInfraMonitoringLogFilters();
- const [
- tracesFiltersParam,
- setTracesFiltersParam,
- ] = useInfraMonitoringTracesFilters();
- const [
- eventsFiltersParam,
- setEventsFiltersParam,
- ] = useInfraMonitoringEventsFilters();
- const isDarkMode = useIsDarkMode();
-
- const initialFilters = useMemo(() => {
- const filters =
- selectedView === VIEW_TYPES.LOGS ? logFiltersParam : tracesFiltersParam;
- if (filters) {
- return filters;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_POD_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s_pod_name--string--resource--false',
- },
- op: '=',
- value: pod?.meta.k8s_pod_name || '',
- },
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_NAMESPACE_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s_pod_name--string--resource--false',
- },
- op: '=',
- value: pod?.meta.k8s_namespace_name || '',
- },
- ],
- };
- }, [
- pod?.meta.k8s_namespace_name,
- pod?.meta.k8s_pod_name,
- selectedView,
- logFiltersParam,
- tracesFiltersParam,
- ]);
-
- const initialEventsFilters = useMemo(() => {
- if (eventsFiltersParam) {
- return eventsFiltersParam;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_KIND,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.kind--string--resource--false',
- },
- op: '=',
- value: 'Pod',
- },
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.name--string--resource--false',
- },
- op: '=',
- value: pod?.meta.k8s_pod_name || '',
- },
- ],
- };
- }, [pod?.meta.k8s_pod_name, eventsFiltersParam]);
-
- const [logsAndTracesFilters, setLogsAndTracesFilters] = useState<
- IBuilderQuery['filters']
- >(initialFilters);
-
- const [eventsFilters, setEventsFilters] = useState<IBuilderQuery['filters']>(
- initialEventsFilters,
- );
-
- useEffect(() => {
- if (pod) {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Pod,
- });
- }
- }, [pod]);
-
- useEffect(() => {
- setLogsAndTracesFilters(initialFilters);
- setEventsFilters(initialEventsFilters);
- }, [initialFilters, initialEventsFilters]);
-
- useEffect(() => {
- const currentSelectedInterval = lastSelectedInterval.current || selectedTime;
- setSelectedInterval(currentSelectedInterval as Time);
-
- if (currentSelectedInterval !== 'custom') {
- const { maxTime, minTime } = GetMinMax(currentSelectedInterval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / TimeRangeOffset),
- endTime: Math.floor(maxTime / TimeRangeOffset),
- });
- }
- }, [selectedTime, minTime, maxTime]);
-
- const handleTabChange = (e: RadioChangeEvent): void => {
- setSelectedView(e.target.value);
- setLogFiltersParam(null);
- setTracesFiltersParam(null);
- setEventsFiltersParam(null);
- logEvent(InfraMonitoringEvents.TabChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Pod,
- view: e.target.value,
- });
- };
-
- const handleTimeChange = useCallback(
- (interval: Time | CustomTimeType, dateTimeRange?: [number, number]): void => {
- lastSelectedInterval.current = interval as Time;
- setSelectedInterval(interval as Time);
-
- if (interval === 'custom' && dateTimeRange) {
- setModalTimeRange({
- startTime: Math.floor(dateTimeRange[0] / 1000),
- endTime: Math.floor(dateTimeRange[1] / 1000),
- });
- } else {
- const { maxTime, minTime } = GetMinMax(interval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / TimeRangeOffset),
- endTime: Math.floor(maxTime / TimeRangeOffset),
- });
- }
-
- logEvent(InfraMonitoringEvents.TimeUpdated, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Pod,
- interval,
- view: selectedView,
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeLogFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogsAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [
- QUERY_KEYS.K8S_POD_NAME,
- QUERY_KEYS.K8S_CLUSTER_NAME,
- QUERY_KEYS.K8S_NAMESPACE_NAME,
- ].includes(item.key?.key ?? ''),
- );
- const paginationFilter = value?.items?.find(
- (item) => item.key?.key === 'id',
- );
- const newFilters = value?.items?.filter(
- (item) =>
- item.key?.key !== 'id' && item.key?.key !== QUERY_KEYS.K8S_CLUSTER_NAME,
- );
-
- if (newFilters && newFilters?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Pod,
- view: selectedView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(newFilters || []),
- ...(paginationFilter ? [paginationFilter] : []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setLogFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeTracesFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogsAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [
- QUERY_KEYS.K8S_POD_NAME,
- QUERY_KEYS.K8S_CLUSTER_NAME,
- QUERY_KEYS.K8S_NAMESPACE_NAME,
- ].includes(item.key?.key ?? ''),
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Pod,
- view: selectedView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(value?.items?.filter(
- (item) => item.key?.key !== QUERY_KEYS.K8S_POD_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setTracesFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeEventsFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setEventsFilters((prevFilters) => {
- const podKindFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_KIND,
- );
- const podNameFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_NAME,
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Pod,
- view: selectedView,
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: [
- podKindFilter,
- podNameFilter,
- ...(value?.items?.filter(
- (item) =>
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_KIND &&
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- };
-
- setEventsFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleExplorePagesRedirect = (): void => {
- if (selectedInterval !== 'custom') {
- urlQuery.set(QueryParams.relativeTime, selectedInterval);
- } else {
- urlQuery.delete(QueryParams.relativeTime);
- urlQuery.set(QueryParams.startTime, modalTimeRange.startTime.toString());
- urlQuery.set(QueryParams.endTime, modalTimeRange.endTime.toString());
- }
-
- logEvent(InfraMonitoringEvents.ExploreClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Pod,
- view: selectedView,
- });
-
- if (selectedView === VIEW_TYPES.LOGS) {
- const filtersWithoutPagination = {
- ...logsAndTracesFilters,
- items:
- logsAndTracesFilters?.items?.filter((item) => item.key?.key !== 'id') ||
- [],
- };
-
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.logs,
- aggregateOperator: LogsAggregatorOperator.NOOP,
- filters: filtersWithoutPagination,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.LOGS_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- } else if (selectedView === VIEW_TYPES.TRACES) {
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.traces,
- aggregateOperator: TracesAggregatorOperator.NOOP,
- filters: logsAndTracesFilters,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.TRACES_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- }
- };
-
- const handleClose = (): void => {
- lastSelectedInterval.current = null;
- setSelectedInterval(selectedTime as Time);
-
- if (selectedTime !== 'custom') {
- const { maxTime, minTime } = GetMinMax(selectedTime);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / TimeRangeOffset),
- endTime: Math.floor(maxTime / TimeRangeOffset),
- });
- }
- setSelectedView(VIEW_TYPES.METRICS);
- onClose();
- };
-
- return (
- <Drawer
- width="70%"
- title={
- <>
- <Divider type="vertical" />
- <Typography.Text className="title">
- {pod?.meta.k8s_pod_name}
- </Typography.Text>
- </>
- }
- placement="right"
- onClose={handleClose}
- open={!!pod}
- style={{
- overscrollBehavior: 'contain',
- background: isDarkMode ? Color.BG_INK_400 : Color.BG_VANILLA_100,
- }}
- className="entity-detail-drawer"
- destroyOnClose
- closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
- >
- {pod && (
- <>
- <div className="entity-detail-drawer__entity">
- <div className="entity-details-grid">
- <div className="labels-row">
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- NAMESPACE
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Cluster Name
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Node
- </Typography.Text>
- </div>
-
- <div className="values-row">
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={pod.meta.k8s_namespace_name}>
- {pod.meta.k8s_namespace_name}
- </Tooltip>
- </Typography.Text>
-
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={pod.meta.k8s_cluster_name}>
- {pod.meta.k8s_cluster_name}
- </Tooltip>
- </Typography.Text>
-
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={pod.meta.k8s_node_name}>
- {pod.meta.k8s_node_name}
- </Tooltip>
- </Typography.Text>
- </div>
- </div>
- </div>
-
- <div className="views-tabs-container">
- <Radio.Group
- className="views-tabs"
- onChange={handleTabChange}
- value={selectedView}
- >
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.METRICS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.METRICS}
- >
- <div className="view-title">
- <BarChart2 size={14} />
- Metrics
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.LOGS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.LOGS}
- >
- <div className="view-title">
- <ScrollText size={14} />
- Logs
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.TRACES ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.TRACES}
- >
- <div className="view-title">
- <DraftingCompass size={14} />
- Traces
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.EVENTS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.EVENTS}
- >
- <div className="view-title">
- <ChevronsLeftRight size={14} />
- Events
- </div>
- </Radio.Button>
- </Radio.Group>
-
- {(selectedView === VIEW_TYPES.LOGS ||
- selectedView === VIEW_TYPES.TRACES) && (
- <Button
- icon={<Compass size={18} />}
- className="compass-button"
- onClick={handleExplorePagesRedirect}
- />
- )}
- </div>
-
- {selectedView === VIEW_TYPES.METRICS && (
- <PodMetrics<K8sPodsData>
- entity={pod}
- selectedInterval={selectedInterval}
- timeRange={modalTimeRange}
- handleTimeChange={handleTimeChange}
- isModalTimeSelection={isModalTimeSelection}
- entityWidgetInfo={podWidgetInfo}
- getEntityQueryPayload={getPodMetricsQueryPayload}
- category={K8sCategory.PODS}
- queryKey="podMetrics"
- />
- )}
- {selectedView === VIEW_TYPES.LOGS && (
- <PodLogs
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeLogFilters={handleChangeLogFilters}
- logFilters={logsAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKeyFilters={[
- QUERY_KEYS.K8S_POD_NAME,
- QUERY_KEYS.K8S_CLUSTER_NAME,
- QUERY_KEYS.K8S_NAMESPACE_NAME,
- ]}
- queryKey="podLogs"
- category={K8sCategory.PODS}
- />
- )}
- {selectedView === VIEW_TYPES.TRACES && (
- <PodTraces
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeTracesFilters={handleChangeTracesFilters}
- tracesFilters={logsAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKey="podTraces"
- category={InfraMonitoringEvents.Pod}
- queryKeyFilters={[
- QUERY_KEYS.K8S_POD_NAME,
- QUERY_KEYS.K8S_CLUSTER_NAME,
- QUERY_KEYS.K8S_NAMESPACE_NAME,
- ]}
- />
- )}
-
- {selectedView === VIEW_TYPES.EVENTS && (
- <PodEvents
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeEventFilters={handleChangeEventsFilters}
- filters={eventsFilters}
- selectedInterval={selectedInterval}
- category={K8sCategory.PODS}
- queryKey="podEvents"
- />
- )}
- </>
- )}
- </Drawer>
- );
-}
-
-export default PodDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/Pods/PodDetails/index.tsx b/frontend/src/container/InfraMonitoringK8s/Pods/PodDetails/index.tsx
deleted file mode 100644
index 4eb6ef5359..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Pods/PodDetails/index.tsx
+++ /dev/null
@@ -1,3 +0,0 @@
-import PodDetails from './PodDetails';
-
-export default PodDetails;
diff --git a/frontend/src/api/infraMonitoring/getK8sPodsList.ts b/frontend/src/container/InfraMonitoringK8s/Pods/api.ts
similarity index 70%
rename from frontend/src/api/infraMonitoring/getK8sPodsList.ts
rename to frontend/src/container/InfraMonitoringK8s/Pods/api.ts
index 57fadbbb0b..1e449e8d68 100644
--- a/frontend/src/api/infraMonitoring/getK8sPodsList.ts
+++ b/frontend/src/container/InfraMonitoringK8s/Pods/api.ts
@@ -1,21 +1,36 @@
import axios from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
+import { UnderscoreToDotMap } from 'api/utils';
import { AxiosError } from 'axios';
import { ErrorResponse, SuccessResponse } from 'types/api';
-import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
-import { UnderscoreToDotMap } from '../utils';
+import { K8sBaseFilters } from '../Base/types';
-export interface K8sPodsListPayload {
- filters: TagFilter;
- groupBy?: BaseAutocompleteData[];
- offset?: number;
- limit?: number;
- orderBy?: {
- columnName: string;
- order: 'asc' | 'desc';
- };
+// TODO(H4ad): Erase this whole file when migrating to openapi
+export const podsMetaMap = [
+ { dot: 'k8s.cronjob.name', under: 'k8s_cronjob_name' },
+ { dot: 'k8s.daemonset.name', under: 'k8s_daemonset_name' },
+ { dot: 'k8s.deployment.name', under: 'k8s_deployment_name' },
+ { dot: 'k8s.job.name', under: 'k8s_job_name' },
+ { dot: 'k8s.namespace.name', under: 'k8s_namespace_name' },
+ { dot: 'k8s.node.name', under: 'k8s_node_name' },
+ { dot: 'k8s.pod.name', under: 'k8s_pod_name' },
+ { dot: 'k8s.pod.uid', under: 'k8s_pod_uid' },
+ { dot: 'k8s.statefulset.name', under: 'k8s_statefulset_name' },
+ { dot: 'k8s.cluster.name', under: 'k8s_cluster_name' },
+] as const;
+
+export function mapPodsMeta(raw: Record<string, unknown>): K8sPodsData['meta'] {
+ // clone everything
+ const out: Record<string, unknown> = { ...raw };
+ // overlay only the dot→under mappings
+ podsMetaMap.forEach(({ dot, under }) => {
+ if (dot in raw) {
+ const v = raw[dot];
+ out[under] = typeof v === 'string' ? v : raw[under];
+ }
+ });
+ return out as K8sPodsData['meta'];
}
export interface TimeSeriesValue {
@@ -71,72 +86,44 @@ export interface K8sPodsListResponse {
};
}
-export const podsMetaMap = [
- { dot: 'k8s.cronjob.name', under: 'k8s_cronjob_name' },
- { dot: 'k8s.daemonset.name', under: 'k8s_daemonset_name' },
- { dot: 'k8s.deployment.name', under: 'k8s_deployment_name' },
- { dot: 'k8s.job.name', under: 'k8s_job_name' },
- { dot: 'k8s.namespace.name', under: 'k8s_namespace_name' },
- { dot: 'k8s.node.name', under: 'k8s_node_name' },
- { dot: 'k8s.pod.name', under: 'k8s_pod_name' },
- { dot: 'k8s.pod.uid', under: 'k8s_pod_uid' },
- { dot: 'k8s.statefulset.name', under: 'k8s_statefulset_name' },
- { dot: 'k8s.cluster.name', under: 'k8s_cluster_name' },
-] as const;
-
-export function mapPodsMeta(raw: Record<string, unknown>): K8sPodsData['meta'] {
- // clone everything
- const out: Record<string, unknown> = { ...raw };
- // overlay only the dot→under mappings
- podsMetaMap.forEach(({ dot, under }) => {
- if (dot in raw) {
- const v = raw[dot];
- out[under] = typeof v === 'string' ? v : raw[under];
- }
- });
- return out as K8sPodsData['meta'];
-}
-
-// getK8sPodsList
export const getK8sPodsList = async (
- props: K8sPodsListPayload,
+ props: K8sBaseFilters,
signal?: AbortSignal,
headers?: Record<string, string>,
dotMetricsEnabled = false,
): Promise<SuccessResponse<K8sPodsListResponse> | ErrorResponse> => {
try {
- const requestProps =
- dotMetricsEnabled && Array.isArray(props.filters?.items)
- ? {
- ...props,
- filters: {
- ...props.filters,
- items: props.filters.items.reduce<typeof props.filters.items>(
- (acc, item) => {
- if (item.value === undefined) {
- return acc;
- }
- if (
- item.key &&
- typeof item.key === 'object' &&
- 'key' in item.key &&
- typeof item.key.key === 'string'
- ) {
- const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
- acc.push({
- ...item,
- key: { ...item.key, key: mappedKey },
- });
- } else {
- acc.push(item);
- }
+ const requestProps = dotMetricsEnabled
+ ? {
+ ...props,
+ filters: {
+ ...props.filters,
+ items: props.filters?.items.reduce<typeof props.filters.items>(
+ (acc, item) => {
+ if (item.value === undefined) {
return acc;
- },
- [] as typeof props.filters.items,
- ),
- },
- }
- : props;
+ }
+ if (
+ item.key &&
+ typeof item.key === 'object' &&
+ 'key' in item.key &&
+ typeof item.key.key === 'string'
+ ) {
+ const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
+ acc.push({
+ ...item,
+ key: { ...item.key, key: mappedKey },
+ });
+ } else {
+ acc.push(item);
+ }
+ return acc;
+ },
+ [] as typeof props.filters.items,
+ ),
+ },
+ }
+ : props;
const response = await axios.post('/pods/list', requestProps, {
signal,
diff --git a/frontend/src/container/InfraMonitoringK8s/Pods/PodDetails/constants.ts b/frontend/src/container/InfraMonitoringK8s/Pods/constants.ts
similarity index 97%
rename from frontend/src/container/InfraMonitoringK8s/Pods/PodDetails/constants.ts
rename to frontend/src/container/InfraMonitoringK8s/Pods/constants.ts
index eb52a62bee..5a5605ac2b 100644
--- a/frontend/src/container/InfraMonitoringK8s/Pods/PodDetails/constants.ts
+++ b/frontend/src/container/InfraMonitoringK8s/Pods/constants.ts
@@ -1,11 +1,69 @@
-import { K8sPodsData } from 'api/infraMonitoring/getK8sPodsList';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { v4 } from 'uuid';
+import {
+ createFilterItem,
+ K8sDetailsMetadataConfig,
+} from '../Base/K8sBaseDetails';
+import { QUERY_KEYS } from '../EntityDetailsUtils/utils';
+import { K8sPodsData } from './api';
+
+export const k8sPodGetSelectedItemFilters = (
+ selectedItemId: string,
+): TagFilter => {
+ return {
+ op: 'AND',
+ items: [
+ {
+ id: 'k8s_pod_uid',
+ key: {
+ key: 'k8s_pod_uid',
+ type: null,
+ },
+ op: '=',
+ value: selectedItemId,
+ },
+ ],
+ };
+};
+
+export const k8sPodDetailsMetadataConfig: K8sDetailsMetadataConfig<K8sPodsData>[] = [
+ { label: 'NAMESPACE', getValue: (p): string => p.meta.k8s_namespace_name },
+ {
+ label: 'Cluster Name',
+ getValue: (p): string => p.meta.k8s_cluster_name,
+ },
+ { label: 'Node', getValue: (p): string => p.meta.k8s_node_name },
+];
+
+export const k8sPodInitialFilters = [
+ QUERY_KEYS.K8S_POD_NAME,
+ QUERY_KEYS.K8S_CLUSTER_NAME,
+ QUERY_KEYS.K8S_NAMESPACE_NAME,
+];
+
+export const k8sPodInitialEventsFilter = (
+ pod: K8sPodsData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_KIND, 'Pod'),
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_NAME, pod.meta.k8s_pod_name),
+];
+
+export const k8sPodInitialLogTracesFilter = (
+ pod: K8sPodsData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(QUERY_KEYS.K8S_POD_NAME, pod.meta.k8s_pod_name),
+ createFilterItem(QUERY_KEYS.K8S_NAMESPACE_NAME, pod.meta.k8s_namespace_name),
+];
+
+export const k8sPodGetEntityName = (pod: K8sPodsData): string =>
+ pod.meta.k8s_pod_name;
+
export const podWidgetInfo = [
{
title: 'CPU Usage (cores)',
diff --git a/frontend/src/container/InfraMonitoringK8s/Pods/table.config.tsx b/frontend/src/container/InfraMonitoringK8s/Pods/table.config.tsx
new file mode 100644
index 0000000000..735656b2c1
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Pods/table.config.tsx
@@ -0,0 +1,328 @@
+import React from 'react';
+import { TableColumnType as ColumnType, Tooltip } from 'antd';
+import { Group } from 'lucide-react';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+
+import { K8sRenderedRowData } from '../Base/types';
+import { IEntityColumn } from '../Base/useInfraMonitoringTableColumnsStore';
+import { getGroupByEl, getGroupedByMeta, getRowKey } from '../Base/utils';
+import {
+ EntityProgressBar,
+ formatBytes,
+ ValidateColumnValueWrapper,
+} from '../commonUtils';
+import { InfraMonitoringEntity } from '../constants';
+import { K8sPodsData } from './api';
+
+import styles from './table.module.scss';
+
+export interface K8sPodsRowData {
+ key: string;
+ podName: React.ReactNode;
+ podUID: string;
+ cpu_request: React.ReactNode;
+ cpu_limit: React.ReactNode;
+ cpu: React.ReactNode;
+ memory_request: React.ReactNode;
+ memory_limit: React.ReactNode;
+ memory: React.ReactNode;
+ restarts: React.ReactNode;
+ groupedByMeta?: any;
+}
+
+export const k8sPodColumns: IEntityColumn[] = [
+ {
+ label: 'Pod Group',
+ value: 'podGroup',
+ id: 'podGroup',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-collapse',
+ },
+ {
+ label: 'Pod name',
+ value: 'podName',
+ id: 'podName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-expand',
+ },
+ {
+ label: 'CPU Req Usage (%)',
+ value: 'cpu_request',
+ id: 'cpu_request',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Limit Usage (%)',
+ value: 'cpu_limit',
+ id: 'cpu_limit',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Usage (cores)',
+ value: 'cpu',
+ id: 'cpu',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Req Usage (%)',
+ value: 'memory_request',
+ id: 'memory_request',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Limit Usage (%)',
+ value: 'memory_limit',
+ id: 'memory_limit',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Usage (WSS)',
+ value: 'memory',
+ id: 'memory',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Namespace name',
+ value: 'namespace',
+ id: 'namespace',
+ canBeHidden: true,
+ defaultVisibility: false,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Node name',
+ value: 'node',
+ id: 'node',
+ canBeHidden: true,
+ defaultVisibility: false,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Cluster name',
+ value: 'cluster',
+ id: 'cluster',
+ canBeHidden: true,
+ defaultVisibility: false,
+ behavior: 'always-visible',
+ },
+ // TODO - Re-enable the column once backend issue is fixed
+ // {
+ // label: 'Restarts',
+ // value: 'restarts',
+ // id: 'restarts',
+ // canRemove: false,
+ // },
+];
+
+export const k8sPodColumnsConfig: ColumnType<K8sRenderedRowData>[] = [
+ {
+ title: (
+ <div className={styles.entityGroupHeader}>
+ <Group size={14} /> POD GROUP
+ </div>
+ ),
+ dataIndex: 'podGroup',
+ key: 'podGroup',
+ ellipsis: true,
+ width: 180,
+ sorter: false,
+ },
+ {
+ title: <div>Pod Name</div>,
+ dataIndex: 'podName',
+ key: 'podName',
+ width: 180,
+ ellipsis: true,
+ sorter: false,
+ },
+ {
+ title: <div>CPU Req Usage (%)</div>,
+ dataIndex: 'cpu_request',
+ key: 'cpu_request',
+ width: 180,
+ ellipsis: true,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Limit Usage (%)</div>,
+ dataIndex: 'cpu_limit',
+ key: 'cpu_limit',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Usage (cores)</div>,
+ dataIndex: 'cpu',
+ key: 'cpu',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Req Usage (%)</div>,
+ dataIndex: 'memory_request',
+ key: 'memory_request',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Limit Usage (%)</div>,
+ dataIndex: 'memory_limit',
+ key: 'memory_limit',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Usage (WSS)</div>,
+ dataIndex: 'memory',
+ key: 'memory',
+ width: 120,
+ ellipsis: true,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Namespace</div>,
+ dataIndex: 'namespace',
+ key: 'namespace',
+ width: 100,
+ sorter: false,
+ ellipsis: true,
+ align: 'left',
+ },
+ {
+ title: <div>Node</div>,
+ dataIndex: 'node',
+ key: 'node',
+ width: 100,
+ sorter: false,
+ ellipsis: true,
+ align: 'left',
+ },
+ {
+ title: <div>Cluster</div>,
+ dataIndex: 'cluster',
+ key: 'cluster',
+ width: 100,
+ sorter: false,
+ ellipsis: true,
+ align: 'left',
+ },
+ // TODO - Re-enable the column once backend issue is fixed
+ // {
+ // title: (
+ // <div className="column-header">
+ // <Tooltip title="Container Restarts">Restarts</Tooltip>
+ // </div>
+ // ),
+ // dataIndex: 'restarts',
+ // key: 'restarts',
+ // width: 40,
+ // ellipsis: true,
+ // sorter: true,
+ // align: 'left',
+ // className: `column ${columnProgressBarClassName}`,
+ // },
+];
+
+export const k8sPodRenderRowData = (
+ pod: K8sPodsData,
+ groupBy: BaseAutocompleteData[],
+): K8sRenderedRowData => ({
+ key: getRowKey(
+ pod,
+ () => pod.podUID || pod.meta.k8s_pod_uid || pod.meta.k8s_pod_name,
+ groupBy,
+ ),
+ itemKey: pod.podUID,
+ podName: (
+ <Tooltip title={pod.meta.k8s_pod_name || ''}>
+ {pod.meta.k8s_pod_name || ''}
+ </Tooltip>
+ ),
+ podUID: pod.podUID || '',
+ cpu_request: (
+ <ValidateColumnValueWrapper
+ value={pod.podCPURequest}
+ entity={InfraMonitoringEntity.PODS}
+ attribute="CPU Request"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={pod.podCPURequest} type="request" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ cpu_limit: (
+ <ValidateColumnValueWrapper
+ value={pod.podCPULimit}
+ entity={InfraMonitoringEntity.PODS}
+ attribute="CPU Limit"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={pod.podCPULimit} type="limit" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ cpu: (
+ <ValidateColumnValueWrapper value={pod.podCPU}>
+ {pod.podCPU}
+ </ValidateColumnValueWrapper>
+ ),
+ memory_request: (
+ <ValidateColumnValueWrapper
+ value={pod.podMemoryRequest}
+ entity={InfraMonitoringEntity.PODS}
+ attribute="Memory Request"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={pod.podMemoryRequest} type="request" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ memory_limit: (
+ <ValidateColumnValueWrapper
+ value={pod.podMemoryLimit}
+ entity={InfraMonitoringEntity.PODS}
+ attribute="Memory Limit"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={pod.podMemoryLimit} type="limit" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ memory: (
+ <ValidateColumnValueWrapper value={pod.podMemory}>
+ {formatBytes(pod.podMemory)}
+ </ValidateColumnValueWrapper>
+ ),
+ restarts: (
+ <ValidateColumnValueWrapper value={pod.restartCount}>
+ {pod.restartCount}
+ </ValidateColumnValueWrapper>
+ ),
+ namespace: pod.meta.k8s_namespace_name,
+ node: pod.meta.k8s_node_name,
+ cluster: pod.meta.k8s_cluster_name,
+ meta: pod.meta,
+ podGroup: getGroupByEl(pod, groupBy),
+ ...pod.meta,
+ groupedByMeta: getGroupedByMeta(pod, groupBy),
+});
diff --git a/frontend/src/container/InfraMonitoringK8s/Pods/table.module.scss b/frontend/src/container/InfraMonitoringK8s/Pods/table.module.scss
new file mode 100644
index 0000000000..bc11f496a1
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Pods/table.module.scss
@@ -0,0 +1,11 @@
+.entityGroupHeader {
+ padding-left: var(--spacing-5);
+ gap: var(--spacing-5);
+ display: flex;
+ align-items: center;
+}
+
+.progressBar {
+ display: flex;
+ justify-content: start;
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/StatefulSets/K8sStatefulSetsList.styles.scss b/frontend/src/container/InfraMonitoringK8s/StatefulSets/K8sStatefulSetsList.styles.scss
deleted file mode 100644
index 29e3ebe33d..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/StatefulSets/K8sStatefulSetsList.styles.scss
+++ /dev/null
@@ -1,62 +0,0 @@
-.infra-monitoring-container {
- .statefulSets-list-table {
- .expanded-table-container {
- padding-left: 20px;
- }
-
- .ant-table-cell.column-progress-bar {
- min-width: 180px;
- max-width: 180px;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
-
- .progress-container {
- display: flex;
- justify-content: start;
- }
- }
-}
-
-.ant-table-cell {
- &:has(.statefulset-name-header) {
- min-width: 250px !important;
- max-width: 250px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.namespace-name-header) {
- min-width: 220px !important;
- max-width: 220px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.med-col) {
- min-width: 200px !important;
- max-width: 200px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.small-col) {
- min-width: 120px !important;
- max-width: 120px !important;
- }
-}
-
-.expanded-statefulsets-list-table {
- .ant-table-cell {
- min-width: 180px !important;
- max-width: 180px !important;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
-}
diff --git a/frontend/src/container/InfraMonitoringK8s/StatefulSets/K8sStatefulSetsList.tsx b/frontend/src/container/InfraMonitoringK8s/StatefulSets/K8sStatefulSetsList.tsx
index a77df43493..fc5ec5fd15 100644
--- a/frontend/src/container/InfraMonitoringK8s/StatefulSets/K8sStatefulSetsList.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/StatefulSets/K8sStatefulSetsList.tsx
@@ -1,721 +1,118 @@
-import React, { useCallback, useEffect, useMemo, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { LoadingOutlined } from '@ant-design/icons';
-import {
- Button,
- Spin,
- Table,
- TableColumnType as ColumnType,
- TablePaginationConfig,
- TableProps,
- Typography,
-} from 'antd';
-import type { SorterResult } from 'antd/es/table/interface';
-import logEvent from 'api/common/logEvent';
-import { K8sStatefulSetsListPayload } from 'api/infraMonitoring/getsK8sStatefulSetsList';
-import classNames from 'classnames';
+import React, { useCallback } from 'react';
import { InfraMonitoringEvents } from 'constants/events';
import { FeatureKeys } from 'constants/features';
-import { useGetK8sStatefulSetsList } from 'hooks/infraMonitoring/useGetK8sStatefulSetsList';
-import { useGetAggregateKeys } from 'hooks/queryBuilder/useGetAggregateKeys';
-import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
-import { ChevronDown, ChevronRight } from 'lucide-react';
import { useAppContext } from 'providers/App/App';
-import { AppState } from 'store/reducers';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { buildAbsolutePath, isModifierKeyPressed } from 'utils/app';
-import { openInNewTab } from 'utils/navigation';
-
-import emptyStateUrl from '@/assets/Icons/emptyState.svg';
+import K8sBaseDetails, { K8sDetailsFilters } from '../Base/K8sBaseDetails';
+import { K8sBaseList } from '../Base/K8sBaseList';
+import { K8sBaseFilters } from '../Base/types';
+import { InfraMonitoringEntity } from '../constants';
+import { getK8sStatefulSetsList, K8sStatefulSetsData } from './api';
import {
- GetK8sEntityToAggregateAttribute,
- INFRA_MONITORING_K8S_PARAMS_KEYS,
- K8sCategory,
-} from '../constants';
-import {
- useInfraMonitoringCurrentPage,
- useInfraMonitoringEventsFilters,
- useInfraMonitoringGroupBy,
- useInfraMonitoringLogFilters,
- useInfraMonitoringOrderBy,
- useInfraMonitoringStatefulSetUID,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from '../hooks';
-import K8sHeader from '../K8sHeader';
-import LoadingContainer from '../LoadingContainer';
-import { usePageSize } from '../utils';
-import StatefulSetDetails from './StatefulSetDetails';
+ getStatefulSetMetricsQueryPayload,
+ k8sStatefulSetDetailsMetadataConfig,
+ k8sStatefulSetGetEntityName,
+ k8sStatefulSetGetSelectedItemFilters,
+ k8sStatefulSetInitialEventsFilter,
+ k8sStatefulSetInitialFilters,
+ k8sStatefulSetInitialLogTracesFilter,
+ statefulSetWidgetInfo,
+} from './constants';
import {
- defaultAddedColumns,
- formatDataForTable,
- getK8sStatefulSetsListColumns,
- getK8sStatefulSetsListQuery,
- K8sStatefulSetsRowData,
-} from './utils';
-
-import '../InfraMonitoringK8s.styles.scss';
-import './K8sStatefulSetsList.styles.scss';
+ k8sStatefulSetsColumns,
+ k8sStatefulSetsColumnsConfig,
+ k8sStatefulSetsRenderRowData,
+} from './table.config';
function K8sStatefulSetsList({
- isFiltersVisible,
- handleFilterVisibilityChange,
- quickFiltersLastUpdated,
+ controlListPrefix,
}: {
- isFiltersVisible: boolean;
- handleFilterVisibilityChange: () => void;
- quickFiltersLastUpdated: number;
+ controlListPrefix?: React.ReactNode;
}): JSX.Element {
- const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
- (state) => state.globalTime,
- );
-
- const [currentPage, setCurrentPage] = useInfraMonitoringCurrentPage();
- const [filtersInitialised, setFiltersInitialised] = useState(false);
-
- const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
-
- const [orderBy, setOrderBy] = useInfraMonitoringOrderBy();
-
- const [
- selectedStatefulSetUID,
- setselectedStatefulSetUID,
- ] = useInfraMonitoringStatefulSetUID();
-
- const { pageSize, setPageSize } = usePageSize(K8sCategory.STATEFULSETS);
-
- const [groupBy, setGroupBy] = useInfraMonitoringGroupBy();
-
- const [, setView] = useInfraMonitoringView();
- const [, setTracesFilters] = useInfraMonitoringTracesFilters();
- const [, setEventsFilters] = useInfraMonitoringEventsFilters();
- const [, setLogFilters] = useInfraMonitoringLogFilters();
-
- const [
- selectedRowData,
- setSelectedRowData,
- ] = useState<K8sStatefulSetsRowData | null>(null);
-
- const [groupByOptions, setGroupByOptions] = useState<
- { value: string; label: string }[]
- >([]);
-
- const { currentQuery } = useQueryBuilder();
-
- const queryFilters = useMemo(
- () =>
- currentQuery?.builder?.queryData[0]?.filters || {
- items: [],
- op: 'and',
- },
- [currentQuery?.builder?.queryData],
- );
-
- // Reset pagination every time quick filters are changed
- useEffect(() => {
- if (quickFiltersLastUpdated !== -1) {
- setCurrentPage(1);
- }
- }, [quickFiltersLastUpdated, setCurrentPage]);
-
const { featureFlags } = useAppContext();
const dotMetricsEnabled =
featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
?.active || false;
- const createFiltersForSelectedRowData = (
- selectedRowData: K8sStatefulSetsRowData,
- groupBy: IBuilderQuery['groupBy'],
- ): IBuilderQuery['filters'] => {
- const baseFilters: IBuilderQuery['filters'] = {
- items: [...queryFilters.items],
- op: 'and',
- };
-
- if (!selectedRowData) {
- return baseFilters;
- }
-
- const { groupedByMeta } = selectedRowData;
-
- for (const key of groupBy) {
- baseFilters.items.push({
- key: {
- key: key.key,
- type: null,
- },
- op: '=',
- value: groupedByMeta[key.key],
- id: key.key,
- });
- }
-
- return baseFilters;
- };
-
- const fetchGroupedByRowDataQuery = useMemo(() => {
- if (!selectedRowData) {
- return null;
- }
-
- const baseQuery = getK8sStatefulSetsListQuery();
-
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- return {
- ...baseQuery,
- limit: 10,
- offset: 0,
- filters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [minTime, maxTime, orderBy, selectedRowData, groupBy]);
-
- const groupedByRowDataQueryKey = useMemo(() => {
- // be careful with what you serialize from selectedRowData
- // since it's react node, it could contain circular references
- const selectedRowDataKey = JSON.stringify(selectedRowData?.groupedByMeta);
- if (selectedStatefulSetUID) {
- return [
- 'statefulSetList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- ];
- }
- return [
- 'statefulSetList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- selectedRowDataKey,
- String(minTime),
- String(maxTime),
- ];
- }, [
- queryFilters,
- orderBy,
- selectedStatefulSetUID,
- minTime,
- maxTime,
- selectedRowData,
- ]);
-
- const {
- data: groupedByRowData,
- isFetching: isFetchingGroupedByRowData,
- isLoading: isLoadingGroupedByRowData,
- isError: isErrorGroupedByRowData,
- refetch: fetchGroupedByRowData,
- } = useGetK8sStatefulSetsList(
- fetchGroupedByRowDataQuery as K8sStatefulSetsListPayload,
- {
- queryKey: groupedByRowDataQueryKey,
- enabled: !!fetchGroupedByRowDataQuery && !!selectedRowData,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const {
- data: groupByFiltersData,
- isLoading: isLoadingGroupByFilters,
- } = useGetAggregateKeys(
- {
- dataSource: currentQuery.builder.queryData[0].dataSource,
- aggregateAttribute: GetK8sEntityToAggregateAttribute(
- K8sCategory.STATEFULSETS,
+ const fetchListData = useCallback(
+ async (filters: K8sBaseFilters, signal?: AbortSignal) => {
+ filters.orderBy ||= {
+ columnName: 'cpu',
+ order: 'desc',
+ };
+
+ const response = await getK8sStatefulSetsList(
+ filters,
+ signal,
+ undefined,
dotMetricsEnabled,
- ),
- aggregateOperator: 'noop',
- searchText: '',
- tagType: '',
- },
- {
- queryKey: [currentQuery.builder.queryData[0].dataSource, 'noop'],
- },
- true,
- K8sCategory.STATEFULSETS,
- );
-
- const query = useMemo(() => {
- const baseQuery = getK8sStatefulSetsListQuery();
- const queryPayload = {
- ...baseQuery,
- limit: pageSize,
- offset: (currentPage - 1) * pageSize,
- filters: queryFilters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- if (groupBy.length > 0) {
- queryPayload.groupBy = groupBy;
- }
- return queryPayload;
- }, [pageSize, currentPage, queryFilters, minTime, maxTime, orderBy, groupBy]);
-
- const formattedGroupedByStatefulSetsData = useMemo(
- () =>
- formatDataForTable(groupedByRowData?.payload?.data?.records || [], groupBy),
- [groupedByRowData, groupBy],
- );
-
- const nestedStatefulSetsData = useMemo(() => {
- if (!selectedRowData || !groupedByRowData?.payload?.data.records) {
- return [];
- }
- return groupedByRowData?.payload?.data?.records || [];
- }, [groupedByRowData, selectedRowData]);
-
- const queryKey = useMemo(() => {
- if (selectedStatefulSetUID) {
- return [
- 'statefulSetList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- ];
- }
- return [
- 'statefulSetList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- String(minTime),
- String(maxTime),
- ];
- }, [
- selectedStatefulSetUID,
- pageSize,
- currentPage,
- queryFilters,
- orderBy,
- groupBy,
- minTime,
- maxTime,
- ]);
-
- const { data, isFetching, isLoading, isError } = useGetK8sStatefulSetsList(
- query as K8sStatefulSetsListPayload,
- {
- queryKey,
- enabled: !!query,
- keepPreviousData: true,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const statefulSetsData = useMemo(() => data?.payload?.data?.records || [], [
- data,
- ]);
- const totalCount = data?.payload?.data?.total || 0;
-
- const formattedStatefulSetsData = useMemo(
- () => formatDataForTable(statefulSetsData, groupBy),
- [statefulSetsData, groupBy],
- );
-
- const columns = useMemo(() => getK8sStatefulSetsListColumns(groupBy), [
- groupBy,
- ]);
-
- const handleGroupByRowClick = (record: K8sStatefulSetsRowData): void => {
- setSelectedRowData(record);
-
- if (expandedRowKeys.includes(record.key)) {
- setExpandedRowKeys(expandedRowKeys.filter((key) => key !== record.key));
- } else {
- setExpandedRowKeys([record.key]);
- }
- };
-
- useEffect(() => {
- if (selectedRowData) {
- fetchGroupedByRowData();
- }
- }, [selectedRowData, fetchGroupedByRowData]);
-
- const handleTableChange: TableProps<K8sStatefulSetsRowData>['onChange'] = useCallback(
- (
- pagination: TablePaginationConfig,
- _filters: Record<string, (string | number | boolean)[] | null>,
- sorter:
- | SorterResult<K8sStatefulSetsRowData>
- | SorterResult<K8sStatefulSetsRowData>[],
- ): void => {
- if (pagination.current) {
- setCurrentPage(pagination.current);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.StatefulSet,
- });
- }
-
- if ('field' in sorter && sorter.order) {
- setOrderBy({
- columnName: sorter.field as string,
- order: (sorter.order === 'ascend' ? 'asc' : 'desc') as 'asc' | 'desc',
- });
- } else {
- setOrderBy(null);
- }
- },
- [setCurrentPage, setOrderBy],
- );
-
- const { handleChangeQueryData } = useQueryOperations({
- index: 0,
- query: currentQuery.builder.queryData[0],
- entityVersion: '',
- });
-
- const handleFiltersChange = useCallback(
- (value: IBuilderQuery['filters']): void => {
- handleChangeQueryData('filters', value);
- if (filtersInitialised) {
- setCurrentPage(1);
- } else {
- setFiltersInitialised(true);
- }
+ );
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.StatefulSet,
- });
- }
+ return {
+ data: response.payload?.data.records || [],
+ total: response.payload?.data.total || 0,
+ error: response.error,
+ rawData: response.payload?.data,
+ };
},
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.StatefulSet,
- total: data?.payload?.data?.total,
- });
- }, [data?.payload?.data?.total]);
-
- const selectedStatefulSetData = useMemo(() => {
- if (!selectedStatefulSetUID) {
- return null;
- }
- if (groupBy.length > 0) {
- return (
- nestedStatefulSetsData.find(
- (statefulSet) => statefulSet.statefulSetName === selectedStatefulSetUID,
- ) || null
+ const fetchEntityData = useCallback(
+ async (
+ filters: K8sDetailsFilters,
+ signal?: AbortSignal,
+ ): Promise<{ data: K8sStatefulSetsData | null; error?: string | null }> => {
+ const response = await getK8sStatefulSetsList(
+ {
+ filters: filters.filters,
+ start: filters.start,
+ end: filters.end,
+ limit: 1,
+ offset: 0,
+ },
+ signal,
+ undefined,
+ dotMetricsEnabled,
);
- }
- return (
- statefulSetsData.find(
- (statefulSet) => statefulSet.statefulSetName === selectedStatefulSetUID,
- ) || null
- );
- }, [
- selectedStatefulSetUID,
- groupBy.length,
- statefulSetsData,
- nestedStatefulSetsData,
- ]);
-
- const openStatefulSetInNewTab = (record: K8sStatefulSetsRowData): void => {
- const newParams = new URLSearchParams(document.location.search);
- newParams.set(
- INFRA_MONITORING_K8S_PARAMS_KEYS.STATEFULSET_UID,
- record.statefulsetUID,
- );
- openInNewTab(
- buildAbsolutePath({
- relativePath: '',
- urlQueryString: newParams.toString(),
- }),
- );
- };
-
- const handleRowClick = (
- record: K8sStatefulSetsRowData,
- event: React.MouseEvent,
- ): void => {
- if (event && isModifierKeyPressed(event)) {
- openStatefulSetInNewTab(record);
- return;
- }
- if (groupBy.length === 0) {
- setSelectedRowData(null);
- setselectedStatefulSetUID(record.statefulsetUID);
- } else {
- handleGroupByRowClick(record);
- }
-
- logEvent(InfraMonitoringEvents.ItemClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.StatefulSet,
- });
- };
-
- const nestedColumns = useMemo(() => getK8sStatefulSetsListColumns([]), []);
-
- const isGroupedByAttribute = groupBy.length > 0;
- const handleExpandedRowViewAllClick = (): void => {
- if (!selectedRowData) {
- return;
- }
+ const records = response.payload?.data.records || [];
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- handleFiltersChange(filters);
-
- setCurrentPage(1);
- setSelectedRowData(null);
- setGroupBy([]);
- setOrderBy(null);
- };
-
- const expandedRowRender = (): JSX.Element => (
- <div className="expanded-table-container">
- {isErrorGroupedByRowData && (
- <Typography>{groupedByRowData?.error || 'Something went wrong'}</Typography>
- )}
- {isFetchingGroupedByRowData || isLoadingGroupedByRowData ? (
- <LoadingContainer />
- ) : (
- <div className="expanded-table">
- <Table
- columns={nestedColumns as ColumnType<K8sStatefulSetsRowData>[]}
- dataSource={formattedGroupedByStatefulSetsData}
- pagination={false}
- scroll={{ x: true }}
- tableLayout="fixed"
- size="small"
- loading={{
- spinning: isFetchingGroupedByRowData || isLoadingGroupedByRowData,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- showHeader={false}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => {
- if (event && isModifierKeyPressed(event)) {
- openStatefulSetInNewTab(record);
- return;
- }
- setselectedStatefulSetUID(record.statefulsetUID);
- },
- className: 'expanded-clickable-row',
- })}
- />
-
- {groupedByRowData?.payload?.data?.total &&
- groupedByRowData?.payload?.data?.total > 10 ? (
- <div className="expanded-table-footer">
- <Button
- type="default"
- size="small"
- className="periscope-btn secondary"
- onClick={handleExpandedRowViewAllClick}
- >
- View All
- </Button>
- </div>
- ) : null}
- </div>
- )}
- </div>
- );
-
- const expandRowIconRenderer = ({
- expanded,
- onExpand,
- record,
- }: {
- expanded: boolean;
- onExpand: (
- record: K8sStatefulSetsRowData,
- e: React.MouseEvent<HTMLButtonElement>,
- ) => void;
- record: K8sStatefulSetsRowData;
- }): JSX.Element | null => {
- if (!isGroupedByAttribute) {
- return null;
- }
-
- return expanded ? (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronDown size={14} />
- </Button>
- ) : (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronRight size={14} />
- </Button>
- );
- };
-
- const handleCloseStatefulSetDetail = (): void => {
- setselectedStatefulSetUID(null);
- setView(null);
- setTracesFilters(null);
- setEventsFilters(null);
- setLogFilters(null);
- };
-
- const handleGroupByChange = useCallback(
- (value: IBuilderQuery['groupBy']) => {
- const groupBy = [];
-
- for (let index = 0; index < value.length; index++) {
- const element = (value[index] as unknown) as string;
-
- const key = groupByFiltersData?.payload?.attributeKeys?.find(
- (key) => key.key === element,
- );
-
- if (key) {
- groupBy.push(key);
- }
- }
-
- setCurrentPage(1);
- setGroupBy(groupBy);
- setExpandedRowKeys([]);
-
- logEvent(InfraMonitoringEvents.GroupByChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.StatefulSet,
- });
+ return {
+ data: records.length > 0 ? records[0] : null,
+ error: response.error,
+ };
},
- [groupByFiltersData, setCurrentPage, setGroupBy],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- if (groupByFiltersData?.payload) {
- setGroupByOptions(
- groupByFiltersData?.payload?.attributeKeys?.map((filter) => ({
- value: filter.key,
- label: filter.key,
- })) || [],
- );
- }
- }, [groupByFiltersData]);
-
- const onPaginationChange = (page: number, pageSize: number): void => {
- setCurrentPage(page);
- setPageSize(pageSize);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.StatefulSet,
- });
- };
-
- const showTableLoadingState =
- (isFetching || isLoading) && formattedStatefulSetsData.length === 0;
-
return (
- <div className="k8s-list">
- <K8sHeader
- isFiltersVisible={isFiltersVisible}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- defaultAddedColumns={defaultAddedColumns}
- handleFiltersChange={handleFiltersChange}
- groupByOptions={groupByOptions}
- isLoadingGroupByFilters={isLoadingGroupByFilters}
- handleGroupByChange={handleGroupByChange}
- selectedGroupBy={groupBy}
- entity={K8sCategory.STATEFULSETS}
- showAutoRefresh={!selectedStatefulSetData}
- />
- {isError && <Typography>{data?.error || 'Something went wrong'}</Typography>}
-
- <Table
- className={classNames('k8s-list-table', 'statefulSets-list-table', {
- 'expanded-statefulsets-list-table': isGroupedByAttribute,
- })}
- dataSource={showTableLoadingState ? [] : formattedStatefulSetsData}
- columns={columns}
- pagination={{
- current: currentPage,
- pageSize,
- total: totalCount,
- showSizeChanger: true,
- hideOnSinglePage: false,
- onChange: onPaginationChange,
- }}
- scroll={{ x: true }}
- loading={{
- spinning: showTableLoadingState,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- locale={{
- emptyText: showTableLoadingState ? null : (
- <div className="no-filtered-hosts-message-container">
- <div className="no-filtered-hosts-message-content">
- <img
- src={emptyStateUrl}
- alt="thinking-emoji"
- className="empty-state-svg"
- />
-
- <Typography.Text className="no-filtered-hosts-message">
- This query had no results. Edit your query and try again!
- </Typography.Text>
- </div>
- </div>
- ),
- }}
- tableLayout="fixed"
- onChange={handleTableChange}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => handleRowClick(record, event),
- className: 'clickable-row',
- })}
- expandable={{
- expandedRowRender: isGroupedByAttribute ? expandedRowRender : undefined,
- expandIcon: expandRowIconRenderer,
- expandedRowKeys,
- }}
+ <>
+ <K8sBaseList<K8sStatefulSetsData>
+ controlListPrefix={controlListPrefix}
+ entity={InfraMonitoringEntity.STATEFULSETS}
+ tableColumnsDefinitions={k8sStatefulSetsColumns}
+ tableColumns={k8sStatefulSetsColumnsConfig}
+ fetchListData={fetchListData}
+ renderRowData={k8sStatefulSetsRenderRowData}
+ eventCategory={InfraMonitoringEvents.StatefulSet}
/>
- <StatefulSetDetails
- statefulSet={selectedStatefulSetData}
- isModalTimeSelection
- onClose={handleCloseStatefulSetDetail}
+ <K8sBaseDetails<K8sStatefulSetsData>
+ category={InfraMonitoringEntity.STATEFULSETS}
+ eventCategory={InfraMonitoringEvents.StatefulSet}
+ getSelectedItemFilters={k8sStatefulSetGetSelectedItemFilters}
+ fetchEntityData={fetchEntityData}
+ getEntityName={k8sStatefulSetGetEntityName}
+ getInitialLogTracesFilters={k8sStatefulSetInitialLogTracesFilter}
+ getInitialEventsFilters={k8sStatefulSetInitialEventsFilter}
+ primaryFilterKeys={k8sStatefulSetInitialFilters}
+ metadataConfig={k8sStatefulSetDetailsMetadataConfig}
+ entityWidgetInfo={statefulSetWidgetInfo}
+ getEntityQueryPayload={getStatefulSetMetricsQueryPayload}
+ queryKeyPrefix="statefulSet"
/>
- </div>
+ </>
);
}
diff --git a/frontend/src/container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/StatefulSetDetails.interfaces.ts b/frontend/src/container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/StatefulSetDetails.interfaces.ts
deleted file mode 100644
index 135c2b2d1f..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/StatefulSetDetails.interfaces.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { K8sStatefulSetsData } from 'api/infraMonitoring/getsK8sStatefulSetsList';
-
-export type StatefulSetDetailsProps = {
- statefulSet: K8sStatefulSetsData | null;
- isModalTimeSelection: boolean;
- onClose: () => void;
-};
diff --git a/frontend/src/container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/StatefulSetDetails.tsx b/frontend/src/container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/StatefulSetDetails.tsx
deleted file mode 100644
index cb04b76c78..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/StatefulSetDetails.tsx
+++ /dev/null
@@ -1,658 +0,0 @@
-/* eslint-disable sonarjs/no-identical-functions */
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { Color, Spacing } from '@signozhq/design-tokens';
-import { Button, Divider, Drawer, Radio, Tooltip, Typography } from 'antd';
-import type { RadioChangeEvent } from 'antd/lib';
-import logEvent from 'api/common/logEvent';
-import { VIEW_TYPES, VIEWS } from 'components/HostMetricsDetail/constants';
-import { InfraMonitoringEvents } from 'constants/events';
-import { QueryParams } from 'constants/query';
-import {
- initialQueryBuilderFormValuesMap,
- initialQueryState,
-} from 'constants/queryBuilder';
-import ROUTES from 'constants/routes';
-import { filterDuplicateFilters } from 'container/InfraMonitoringK8s/commonUtils';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
-import EntityEvents from 'container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents';
-import EntityLogs from 'container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs';
-import EntityMetrics from 'container/InfraMonitoringK8s/EntityDetailsUtils/EntityMetrics';
-import EntityTraces from 'container/InfraMonitoringK8s/EntityDetailsUtils/EntityTraces';
-import { QUERY_KEYS } from 'container/InfraMonitoringK8s/EntityDetailsUtils/utils';
-import {
- useInfraMonitoringEventsFilters,
- useInfraMonitoringLogFilters,
- useInfraMonitoringTracesFilters,
- useInfraMonitoringView,
-} from 'container/InfraMonitoringK8s/hooks';
-import {
- CustomTimeType,
- Time,
-} from 'container/TopNav/DateTimeSelectionV2/types';
-import { useIsDarkMode } from 'hooks/useDarkMode';
-import useUrlQuery from 'hooks/useUrlQuery';
-import GetMinMax from 'lib/getMinMax';
-import {
- BarChart2,
- ChevronsLeftRight,
- Compass,
- DraftingCompass,
- ScrollText,
- X,
-} from 'lucide-react';
-import { AppState } from 'store/reducers';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import {
- IBuilderQuery,
- TagFilterItem,
-} from 'types/api/queryBuilder/queryBuilderData';
-import {
- LogsAggregatorOperator,
- TracesAggregatorOperator,
-} from 'types/common/queryBuilder';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { v4 as uuidv4 } from 'uuid';
-
-import {
- getStatefulSetMetricsQueryPayload,
- statefulSetWidgetInfo,
-} from './constants';
-import { StatefulSetDetailsProps } from './StatefulSetDetails.interfaces';
-
-import '../../EntityDetailsUtils/entityDetails.styles.scss';
-
-function StatefulSetDetails({
- statefulSet,
- onClose,
- isModalTimeSelection,
-}: StatefulSetDetailsProps): JSX.Element {
- const { maxTime, minTime, selectedTime } = useSelector<
- AppState,
- GlobalReducer
- >((state) => state.globalTime);
-
- const startMs = useMemo(() => Math.floor(Number(minTime) / 1000000000), [
- minTime,
- ]);
- const endMs = useMemo(() => Math.floor(Number(maxTime) / 1000000000), [
- maxTime,
- ]);
-
- const urlQuery = useUrlQuery();
-
- const [modalTimeRange, setModalTimeRange] = useState(() => ({
- startTime: startMs,
- endTime: endMs,
- }));
-
- const lastSelectedInterval = useRef<Time | null>(null);
-
- const [selectedInterval, setSelectedInterval] = useState<Time>(
- lastSelectedInterval.current
- ? lastSelectedInterval.current
- : (selectedTime as Time),
- );
-
- const [selectedView, setSelectedView] = useInfraMonitoringView();
- const [logFiltersParam, setLogFiltersParam] = useInfraMonitoringLogFilters();
- const [
- tracesFiltersParam,
- setTracesFiltersParam,
- ] = useInfraMonitoringTracesFilters();
- const [
- eventsFiltersParam,
- setEventsFiltersParam,
- ] = useInfraMonitoringEventsFilters();
- const isDarkMode = useIsDarkMode();
-
- const initialFilters = useMemo(() => {
- const filters =
- selectedView === VIEW_TYPES.LOGS ? logFiltersParam : tracesFiltersParam;
- if (filters) {
- return filters;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_STATEFUL_SET_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s_statefulset_name--string--resource--false',
- },
- op: '=',
- value: statefulSet?.meta.k8s_statefulset_name || '',
- },
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_NAMESPACE_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s_namespace_name--string--resource--false',
- },
- op: '=',
- value: statefulSet?.meta.k8s_namespace_name || '',
- },
- ],
- };
- }, [
- statefulSet?.meta.k8s_statefulset_name,
- statefulSet?.meta.k8s_namespace_name,
- selectedView,
- logFiltersParam,
- tracesFiltersParam,
- ]);
-
- const initialEventsFilters = useMemo(() => {
- if (eventsFiltersParam) {
- return eventsFiltersParam;
- }
- return {
- op: 'AND',
- items: [
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_KIND,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.kind--string--resource--false',
- },
- op: '=',
- value: 'StatefulSet',
- },
- {
- id: uuidv4(),
- key: {
- key: QUERY_KEYS.K8S_OBJECT_NAME,
- dataType: DataTypes.String,
- type: 'resource',
- id: 'k8s.object.name--string--resource--false',
- },
- op: '=',
- value: statefulSet?.meta.k8s_statefulset_name || '',
- },
- ],
- };
- }, [statefulSet?.meta.k8s_statefulset_name, eventsFiltersParam]);
-
- const [logAndTracesFilters, setLogAndTracesFilters] = useState<
- IBuilderQuery['filters']
- >(initialFilters);
-
- const [eventsFilters, setEventsFilters] = useState<IBuilderQuery['filters']>(
- initialEventsFilters,
- );
-
- useEffect(() => {
- if (statefulSet) {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.StatefulSet,
- });
- }
- }, [statefulSet]);
-
- useEffect(() => {
- setLogAndTracesFilters(initialFilters);
- setEventsFilters(initialEventsFilters);
- }, [initialFilters, initialEventsFilters]);
-
- useEffect(() => {
- const currentSelectedInterval = lastSelectedInterval.current || selectedTime;
- setSelectedInterval(currentSelectedInterval as Time);
-
- if (currentSelectedInterval !== 'custom') {
- const { maxTime, minTime } = GetMinMax(currentSelectedInterval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- }, [selectedTime, minTime, maxTime]);
-
- const handleTabChange = (e: RadioChangeEvent): void => {
- setSelectedView(e.target.value);
- setLogFiltersParam(null);
- setTracesFiltersParam(null);
- setEventsFiltersParam(null);
- logEvent(InfraMonitoringEvents.TabChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.StatefulSet,
- view: e.target.value,
- });
- };
-
- const handleTimeChange = useCallback(
- (interval: Time | CustomTimeType, dateTimeRange?: [number, number]): void => {
- lastSelectedInterval.current = interval as Time;
- setSelectedInterval(interval as Time);
-
- if (interval === 'custom' && dateTimeRange) {
- setModalTimeRange({
- startTime: Math.floor(dateTimeRange[0] / 1000),
- endTime: Math.floor(dateTimeRange[1] / 1000),
- });
- } else {
- const { maxTime, minTime } = GetMinMax(interval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
-
- logEvent(InfraMonitoringEvents.TimeUpdated, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.StatefulSet,
- interval,
- view: selectedView,
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeLogFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_STATEFUL_SET_NAME, QUERY_KEYS.K8S_NAMESPACE_NAME].includes(
- item.key?.key ?? '',
- ),
- );
- const paginationFilter = value?.items?.find(
- (item) => item.key?.key === 'id',
- );
- const newFilters = value?.items?.filter(
- (item) =>
- item.key?.key !== 'id' &&
- item.key?.key !== QUERY_KEYS.K8S_STATEFUL_SET_NAME,
- );
-
- if (newFilters && newFilters?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.StatefulSet,
- view: 'logs',
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(newFilters || []),
- ...(paginationFilter ? [paginationFilter] : []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setLogFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeTracesFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setLogAndTracesFilters((prevFilters) => {
- const primaryFilters = prevFilters?.items?.filter((item) =>
- [QUERY_KEYS.K8S_STATEFUL_SET_NAME, QUERY_KEYS.K8S_NAMESPACE_NAME].includes(
- item.key?.key ?? '',
- ),
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.StatefulSet,
- view: 'traces',
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: filterDuplicateFilters(
- [
- ...(primaryFilters || []),
- ...(value?.items?.filter(
- (item) => item.key?.key !== QUERY_KEYS.K8S_STATEFUL_SET_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- ),
- };
-
- setTracesFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleChangeEventsFilters = useCallback(
- (value: IBuilderQuery['filters'], view: VIEWS) => {
- setEventsFilters((prevFilters) => {
- const statefulSetKindFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_KIND,
- );
- const statefulSetNameFilter = prevFilters?.items?.find(
- (item) => item.key?.key === QUERY_KEYS.K8S_OBJECT_NAME,
- );
-
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.StatefulSet,
- view: 'logs',
- });
- }
-
- const updatedFilters = {
- op: 'AND',
- items: [
- statefulSetKindFilter,
- statefulSetNameFilter,
- ...(value?.items?.filter(
- (item) =>
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_KIND &&
- item.key?.key !== QUERY_KEYS.K8S_OBJECT_NAME,
- ) || []),
- ].filter((item): item is TagFilterItem => item !== undefined),
- };
-
- setEventsFiltersParam(updatedFilters);
- setSelectedView(view);
-
- return updatedFilters;
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
- );
-
- const handleExplorePagesRedirect = (): void => {
- if (selectedInterval !== 'custom') {
- urlQuery.set(QueryParams.relativeTime, selectedInterval);
- } else {
- urlQuery.delete(QueryParams.relativeTime);
- urlQuery.set(QueryParams.startTime, modalTimeRange.startTime.toString());
- urlQuery.set(QueryParams.endTime, modalTimeRange.endTime.toString());
- }
-
- logEvent(InfraMonitoringEvents.ExploreClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.StatefulSet,
- view: selectedView,
- });
-
- if (selectedView === VIEW_TYPES.LOGS) {
- const filtersWithoutPagination = {
- ...logAndTracesFilters,
- items:
- logAndTracesFilters?.items?.filter((item) => item.key?.key !== 'id') || [],
- };
-
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.logs,
- aggregateOperator: LogsAggregatorOperator.NOOP,
- filters: filtersWithoutPagination,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.LOGS_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- } else if (selectedView === VIEW_TYPES.TRACES) {
- const compositeQuery = {
- ...initialQueryState,
- queryType: 'builder',
- builder: {
- ...initialQueryState.builder,
- queryData: [
- {
- ...initialQueryBuilderFormValuesMap.traces,
- aggregateOperator: TracesAggregatorOperator.NOOP,
- filters: logAndTracesFilters,
- },
- ],
- },
- };
-
- urlQuery.set('compositeQuery', JSON.stringify(compositeQuery));
-
- window.open(
- `${window.location.origin}${ROUTES.TRACES_EXPLORER}?${urlQuery.toString()}`,
- '_blank',
- );
- }
- };
-
- const handleClose = (): void => {
- lastSelectedInterval.current = null;
- setSelectedInterval(selectedTime as Time);
-
- if (selectedTime !== 'custom') {
- const { maxTime, minTime } = GetMinMax(selectedTime);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- setSelectedView(VIEW_TYPES.METRICS);
- onClose();
- };
-
- return (
- <Drawer
- width="70%"
- title={
- <>
- <Divider type="vertical" />
- <Typography.Text className="title">
- {statefulSet?.meta.k8s_statefulset_name}
- </Typography.Text>
- </>
- }
- placement="right"
- onClose={handleClose}
- open={!!statefulSet}
- style={{
- overscrollBehavior: 'contain',
- background: isDarkMode ? Color.BG_INK_400 : Color.BG_VANILLA_100,
- }}
- className="entity-detail-drawer"
- destroyOnClose
- closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
- >
- {statefulSet && (
- <>
- <div className="entity-detail-drawer__entity">
- <div className="entity-details-grid">
- <div className="labels-row">
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Statefulset Name
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Namespace Name
- </Typography.Text>
- </div>
- <div className="values-row">
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={statefulSet.meta.k8s_statefulset_name}>
- {statefulSet.meta.k8s_statefulset_name}
- </Tooltip>
- </Typography.Text>
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={statefulSet.meta.k8s_namespace_name}>
- {statefulSet.meta.k8s_namespace_name}
- </Tooltip>
- </Typography.Text>
- </div>
- </div>
- </div>
-
- <div className="views-tabs-container">
- <Radio.Group
- className="views-tabs"
- onChange={handleTabChange}
- value={selectedView}
- >
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.METRICS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.METRICS}
- >
- <div className="view-title">
- <BarChart2 size={14} />
- Metrics
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.LOGS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.LOGS}
- >
- <div className="view-title">
- <ScrollText size={14} />
- Logs
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.TRACES ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.TRACES}
- >
- <div className="view-title">
- <DraftingCompass size={14} />
- Traces
- </div>
- </Radio.Button>
- <Radio.Button
- className={
- selectedView === VIEW_TYPES.EVENTS ? 'selected_view tab' : 'tab'
- }
- value={VIEW_TYPES.EVENTS}
- >
- <div className="view-title">
- <ChevronsLeftRight size={14} />
- Events
- </div>
- </Radio.Button>
- </Radio.Group>
-
- {(selectedView === VIEW_TYPES.LOGS ||
- selectedView === VIEW_TYPES.TRACES) && (
- <Button
- icon={<Compass size={18} />}
- className="compass-button"
- onClick={handleExplorePagesRedirect}
- />
- )}
- </div>
- {selectedView === VIEW_TYPES.METRICS && (
- <EntityMetrics
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- entity={statefulSet}
- entityWidgetInfo={statefulSetWidgetInfo}
- getEntityQueryPayload={getStatefulSetMetricsQueryPayload}
- category={K8sCategory.STATEFULSETS}
- queryKey="statefulsetMetrics"
- />
- )}
- {selectedView === VIEW_TYPES.LOGS && (
- <EntityLogs
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeLogFilters={handleChangeLogFilters}
- logFilters={logAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKey="statefulsetLogs"
- category={K8sCategory.STATEFULSETS}
- queryKeyFilters={[
- QUERY_KEYS.K8S_STATEFUL_SET_NAME,
- QUERY_KEYS.K8S_NAMESPACE_NAME,
- ]}
- />
- )}
- {selectedView === VIEW_TYPES.TRACES && (
- <EntityTraces
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- handleChangeTracesFilters={handleChangeTracesFilters}
- tracesFilters={logAndTracesFilters}
- selectedInterval={selectedInterval}
- queryKey="statefulsetTraces"
- category={InfraMonitoringEvents.StatefulSet}
- queryKeyFilters={[
- QUERY_KEYS.K8S_STATEFUL_SET_NAME,
- QUERY_KEYS.K8S_NAMESPACE_NAME,
- ]}
- />
- )}
- {selectedView === VIEW_TYPES.EVENTS && (
- <EntityEvents
- timeRange={modalTimeRange}
- handleChangeEventFilters={handleChangeEventsFilters}
- filters={eventsFilters}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- category={K8sCategory.STATEFULSETS}
- queryKey="statefulsetEvents"
- />
- )}
- </>
- )}
- </Drawer>
- );
-}
-
-export default StatefulSetDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/index.ts b/frontend/src/container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/index.ts
deleted file mode 100644
index efc0182463..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import StatefulSetDetails from './StatefulSetDetails';
-
-export default StatefulSetDetails;
diff --git a/frontend/src/api/infraMonitoring/getsK8sStatefulSetsList.ts b/frontend/src/container/InfraMonitoringK8s/StatefulSets/api.ts
similarity index 71%
rename from frontend/src/api/infraMonitoring/getsK8sStatefulSetsList.ts
rename to frontend/src/container/InfraMonitoringK8s/StatefulSets/api.ts
index 681eac80f6..06e1b8ad7b 100644
--- a/frontend/src/api/infraMonitoring/getsK8sStatefulSetsList.ts
+++ b/frontend/src/container/InfraMonitoringK8s/StatefulSets/api.ts
@@ -1,11 +1,12 @@
import axios from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
+import { UnderscoreToDotMap } from 'api/utils';
import { AxiosError } from 'axios';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
-import { UnderscoreToDotMap } from '../utils';
+import { K8sBaseFilters } from '../Base/types';
export interface K8sStatefulSetsListPayload {
filters: TagFilter;
@@ -47,6 +48,7 @@ export interface K8sStatefulSetsListResponse {
};
}
+// TODO(H4ad): Erase this whole file when migrating to openapi
export const statefulSetsMetaMap = [
{ dot: 'k8s.statefulset.name', under: 'k8s_statefulset_name' },
{ dot: 'k8s.namespace.name', under: 'k8s_namespace_name' },
@@ -66,42 +68,37 @@ export function mapStatefulSetsMeta(
}
export const getK8sStatefulSetsList = async (
- props: K8sStatefulSetsListPayload,
+ props: K8sBaseFilters,
signal?: AbortSignal,
headers?: Record<string, string>,
dotMetricsEnabled = false,
): Promise<SuccessResponse<K8sStatefulSetsListResponse> | ErrorResponse> => {
try {
- // Prepare filters
- const requestProps =
- dotMetricsEnabled && Array.isArray(props.filters?.items)
- ? {
- ...props,
- filters: {
- ...props.filters,
- items: props.filters.items.reduce<typeof props.filters.items>(
- (acc, item) => {
- if (item.value === undefined) {
- return acc;
- }
- if (
- item.key &&
- typeof item.key === 'object' &&
- 'key' in item.key &&
- typeof item.key.key === 'string'
- ) {
- const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
- acc.push({ ...item, key: { ...item.key, key: mappedKey } });
- } else {
- acc.push(item);
- }
- return acc;
- },
- [] as typeof props.filters.items,
- ),
- },
- }
- : props;
+ const requestProps = dotMetricsEnabled
+ ? {
+ ...props,
+ filters: {
+ ...props.filters,
+ items: props.filters.items.reduce<TagFilter['items']>((acc, item) => {
+ if (item.value === undefined) {
+ return acc;
+ }
+ if (
+ item.key &&
+ typeof item.key === 'object' &&
+ 'key' in item.key &&
+ typeof item.key.key === 'string'
+ ) {
+ const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
+ acc.push({ ...item, key: { ...item.key, key: mappedKey } });
+ } else {
+ acc.push(item);
+ }
+ return acc;
+ }, [] as TagFilter['items']),
+ },
+ }
+ : props;
const response = await axios.post('/statefulsets/list', requestProps, {
signal,
@@ -109,7 +106,6 @@ export const getK8sStatefulSetsList = async (
});
const payload: K8sStatefulSetsListResponse = response.data;
- // apply our helper
payload.data.records = payload.data.records.map((record) => ({
...record,
meta: mapStatefulSetsMeta(record.meta as Record<string, unknown>),
diff --git a/frontend/src/container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/constants.ts b/frontend/src/container/InfraMonitoringK8s/StatefulSets/constants.ts
similarity index 92%
rename from frontend/src/container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/constants.ts
rename to frontend/src/container/InfraMonitoringK8s/StatefulSets/constants.ts
index a4c2bfc1fb..1ad293589b 100644
--- a/frontend/src/container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/constants.ts
+++ b/frontend/src/container/InfraMonitoringK8s/StatefulSets/constants.ts
@@ -1,11 +1,72 @@
-import { K8sStatefulSetsData } from 'api/infraMonitoring/getsK8sStatefulSetsList';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { v4 } from 'uuid';
+import {
+ createFilterItem,
+ K8sDetailsMetadataConfig,
+} from '../Base/K8sBaseDetails';
+import { QUERY_KEYS } from '../EntityDetailsUtils/utils';
+import { K8sStatefulSetsData } from './api';
+
+export const k8sStatefulSetGetSelectedItemFilters = (
+ selectedItemId: string,
+): TagFilter => ({
+ op: 'AND',
+ items: [
+ {
+ id: 'k8s_statefulset_name',
+ key: {
+ key: 'k8s_statefulset_name',
+ type: null,
+ },
+ op: '=',
+ value: selectedItemId,
+ },
+ ],
+});
+
+export const k8sStatefulSetDetailsMetadataConfig: K8sDetailsMetadataConfig<K8sStatefulSetsData>[] = [
+ {
+ label: 'Statefulset Name',
+ getValue: (p): string => p.meta.k8s_statefulset_name,
+ },
+ {
+ label: 'Namespace Name',
+ getValue: (p): string => p.meta.k8s_namespace_name,
+ },
+];
+
+export const k8sStatefulSetInitialFilters = [
+ QUERY_KEYS.K8S_STATEFUL_SET_NAME,
+ QUERY_KEYS.K8S_NAMESPACE_NAME,
+];
+
+export const k8sStatefulSetInitialEventsFilter = (
+ item: K8sStatefulSetsData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_KIND, 'StatefulSet'),
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_NAME, item.meta.k8s_statefulset_name),
+];
+
+export const k8sStatefulSetInitialLogTracesFilter = (
+ item: K8sStatefulSetsData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(
+ QUERY_KEYS.K8S_STATEFUL_SET_NAME,
+ item.meta.k8s_statefulset_name,
+ ),
+ createFilterItem(QUERY_KEYS.K8S_NAMESPACE_NAME, item.meta.k8s_namespace_name),
+];
+
+export const k8sStatefulSetGetEntityName = (
+ item: K8sStatefulSetsData,
+): string => item.meta.k8s_statefulset_name;
+
export const statefulSetWidgetInfo = [
{
title: 'CPU usage, request, limits',
diff --git a/frontend/src/container/InfraMonitoringK8s/StatefulSets/table.config.tsx b/frontend/src/container/InfraMonitoringK8s/StatefulSets/table.config.tsx
new file mode 100644
index 0000000000..e9b973d25a
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/StatefulSets/table.config.tsx
@@ -0,0 +1,295 @@
+import { TableColumnType as ColumnType, Tooltip } from 'antd';
+import { Group } from 'lucide-react';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+
+import { K8sRenderedRowData } from '../Base/types';
+import { IEntityColumn } from '../Base/useInfraMonitoringTableColumnsStore';
+import { getGroupByEl, getGroupedByMeta, getRowKey } from '../Base/utils';
+import {
+ EntityProgressBar,
+ formatBytes,
+ ValidateColumnValueWrapper,
+} from '../commonUtils';
+import { InfraMonitoringEntity } from '../constants';
+import { K8sStatefulSetsData } from './api';
+
+import styles from './table.module.scss';
+
+export const k8sStatefulSetsColumns: IEntityColumn[] = [
+ {
+ label: 'StatefulSet Group',
+ value: 'statefulSetGroup',
+ id: 'statefulSetGroup',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-collapse',
+ },
+ {
+ label: 'StatefulSet Name',
+ value: 'statefulsetName',
+ id: 'statefulsetName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-expand',
+ },
+ {
+ label: 'Namespace Name',
+ value: 'namespaceName',
+ id: 'namespaceName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Available',
+ value: 'available_pods',
+ id: 'available_pods',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Desired',
+ value: 'desired_pods',
+ id: 'desired_pods',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Req Usage (%)',
+ value: 'cpu_request',
+ id: 'cpu_request',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Limit Usage (%)',
+ value: 'cpu_limit',
+ id: 'cpu_limit',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'CPU Usage (cores)',
+ value: 'cpu',
+ id: 'cpu',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Req Usage (%)',
+ value: 'memory_request',
+ id: 'memory_request',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Limit Usage (%)',
+ value: 'memory_limit',
+ id: 'memory_limit',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Mem Usage (WSS)',
+ value: 'memory',
+ id: 'memory',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+];
+
+export const k8sStatefulSetsColumnsConfig: ColumnType<K8sRenderedRowData>[] = [
+ {
+ title: (
+ <div className={styles.entityGroupHeader}>
+ <Group size={14} /> STATEFULSET GROUP
+ </div>
+ ),
+ dataIndex: 'statefulSetGroup',
+ key: 'statefulSetGroup',
+ ellipsis: true,
+ width: 150,
+ align: 'left',
+ sorter: false,
+ },
+ {
+ title: <div>StatefulSet Name</div>,
+ dataIndex: 'statefulsetName',
+ key: 'statefulsetName',
+ ellipsis: true,
+ width: 80,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>Namespace Name</div>,
+ dataIndex: 'namespaceName',
+ key: 'namespaceName',
+ ellipsis: true,
+ width: 80,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>Available</div>,
+ dataIndex: 'available_pods',
+ key: 'available_pods',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Desired</div>,
+ dataIndex: 'desired_pods',
+ key: 'desired_pods',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Req Usage (%)</div>,
+ dataIndex: 'cpu_request',
+ key: 'cpu_request',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Limit Usage (%)</div>,
+ dataIndex: 'cpu_limit',
+ key: 'cpu_limit',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>CPU Usage (cores)</div>,
+ dataIndex: 'cpu',
+ key: 'cpu',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Req Usage (%)</div>,
+ dataIndex: 'memory_request',
+ key: 'memory_request',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Limit Usage (%)</div>,
+ dataIndex: 'memory_limit',
+ key: 'memory_limit',
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Mem Usage (WSS)</div>,
+ dataIndex: 'memory',
+ key: 'memory',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+];
+
+export const k8sStatefulSetsRenderRowData = (
+ statefulSet: K8sStatefulSetsData,
+ groupBy: BaseAutocompleteData[],
+): K8sRenderedRowData => ({
+ key: getRowKey(
+ statefulSet,
+ () =>
+ statefulSet.statefulSetName || statefulSet.meta.k8s_statefulset_name || '',
+ groupBy,
+ ),
+ itemKey: statefulSet.meta.k8s_statefulset_name,
+ statefulsetName: (
+ <Tooltip title={statefulSet.meta.k8s_statefulset_name}>
+ {statefulSet.meta.k8s_statefulset_name || ''}
+ </Tooltip>
+ ),
+ namespaceName: (
+ <Tooltip title={statefulSet.meta.k8s_namespace_name}>
+ {statefulSet.meta.k8s_namespace_name || ''}
+ </Tooltip>
+ ),
+ cpu_request: (
+ <ValidateColumnValueWrapper
+ value={statefulSet.cpuRequest}
+ entity={InfraMonitoringEntity.STATEFULSETS}
+ attribute="CPU Request"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={statefulSet.cpuRequest} type="request" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ cpu_limit: (
+ <ValidateColumnValueWrapper
+ value={statefulSet.cpuLimit}
+ entity={InfraMonitoringEntity.STATEFULSETS}
+ attribute="CPU Limit"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={statefulSet.cpuLimit} type="limit" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ cpu: (
+ <ValidateColumnValueWrapper value={statefulSet.cpuUsage}>
+ {statefulSet.cpuUsage}
+ </ValidateColumnValueWrapper>
+ ),
+ memory_request: (
+ <ValidateColumnValueWrapper
+ value={statefulSet.memoryRequest}
+ entity={InfraMonitoringEntity.STATEFULSETS}
+ attribute="Memory Request"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={statefulSet.memoryRequest} type="request" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ memory_limit: (
+ <ValidateColumnValueWrapper
+ value={statefulSet.memoryLimit}
+ entity={InfraMonitoringEntity.STATEFULSETS}
+ attribute="Memory Limit"
+ >
+ <div className={styles.progressBar}>
+ <EntityProgressBar value={statefulSet.memoryLimit} type="limit" />
+ </div>
+ </ValidateColumnValueWrapper>
+ ),
+ memory: (
+ <ValidateColumnValueWrapper value={statefulSet.memoryUsage}>
+ {formatBytes(statefulSet.memoryUsage)}
+ </ValidateColumnValueWrapper>
+ ),
+ available_pods: (
+ <ValidateColumnValueWrapper value={statefulSet.availablePods}>
+ {statefulSet.availablePods}
+ </ValidateColumnValueWrapper>
+ ),
+ desired_pods: (
+ <ValidateColumnValueWrapper value={statefulSet.desiredPods}>
+ {statefulSet.desiredPods}
+ </ValidateColumnValueWrapper>
+ ),
+ statefulSetGroup: getGroupByEl(statefulSet, groupBy),
+ ...statefulSet.meta,
+ groupedByMeta: getGroupedByMeta(statefulSet, groupBy),
+});
diff --git a/frontend/src/container/InfraMonitoringK8s/StatefulSets/table.module.scss b/frontend/src/container/InfraMonitoringK8s/StatefulSets/table.module.scss
new file mode 100644
index 0000000000..908621e13e
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/StatefulSets/table.module.scss
@@ -0,0 +1,11 @@
+.entityGroupHeader {
+ display: flex;
+ align-items: center;
+ padding-left: var(--spacing-5);
+ gap: var(--spacing-5);
+}
+
+.progressBar {
+ display: flex;
+ justify-content: start;
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/StatefulSets/utils.tsx b/frontend/src/container/InfraMonitoringK8s/StatefulSets/utils.tsx
deleted file mode 100644
index 9129d163d9..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/StatefulSets/utils.tsx
+++ /dev/null
@@ -1,356 +0,0 @@
-import { Color } from '@signozhq/design-tokens';
-import { TableColumnType as ColumnType, Tag, Tooltip } from 'antd';
-import {
- K8sStatefulSetsData,
- K8sStatefulSetsListPayload,
-} from 'api/infraMonitoring/getsK8sStatefulSetsList';
-import { Group } from 'lucide-react';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-
-import {
- EntityProgressBar,
- formatBytes,
- ValidateColumnValueWrapper,
-} from '../commonUtils';
-import { K8sCategory } from '../constants';
-import { IEntityColumn } from '../utils';
-
-export const defaultAddedColumns: IEntityColumn[] = [
- {
- label: 'StatefulSet Name',
- value: 'statefulsetName',
- id: 'statefulsetName',
- canRemove: false,
- },
- {
- label: 'Namespace Name',
- value: 'namespaceName',
- id: 'namespaceName',
- canRemove: false,
- },
- {
- label: 'Available',
- value: 'available_pods',
- id: 'available_pods',
- canRemove: false,
- },
- {
- label: 'Desired',
- value: 'desired_pods',
- id: 'desired_pods',
- canRemove: false,
- },
- {
- label: 'CPU Req Usage (%)',
- value: 'cpu_request',
- id: 'cpu_request',
- canRemove: false,
- },
- {
- label: 'CPU Limit Usage (%)',
- value: 'cpu_limit',
- id: 'cpu_limit',
- canRemove: false,
- },
- {
- label: 'CPU Usage (cores)',
- value: 'cpu',
- id: 'cpu',
- canRemove: false,
- },
- {
- label: 'Mem Req Usage (%)',
- value: 'memory_request',
- id: 'memory_request',
- canRemove: false,
- },
- {
- label: 'Mem Limit Usage (%)',
- value: 'memory_limit',
- id: 'memory_limit',
- canRemove: false,
- },
- {
- label: 'Mem Usage (WSS)',
- value: 'memory',
- id: 'memory',
- canRemove: false,
- },
-];
-
-export interface K8sStatefulSetsRowData {
- key: string;
- statefulsetUID: string;
- statefulsetName: React.ReactNode;
- cpu_request: React.ReactNode;
- cpu_limit: React.ReactNode;
- cpu: React.ReactNode;
- memory_request: React.ReactNode;
- memory_limit: React.ReactNode;
- memory: React.ReactNode;
- desired_pods: React.ReactNode;
- available_pods: React.ReactNode;
- namespaceName: React.ReactNode;
- groupedByMeta?: any;
-}
-
-const statefulSetGroupColumnConfig = {
- title: (
- <div className="column-header entity-group-header">
- <Group size={14} /> STATEFULSET GROUP
- </div>
- ),
- dataIndex: 'statefulSetGroup',
- key: 'statefulSetGroup',
- ellipsis: true,
- width: 150,
- align: 'left',
- sorter: false,
- className: 'column entity-group-header',
-};
-
-export const getK8sStatefulSetsListQuery = (): K8sStatefulSetsListPayload => ({
- filters: {
- items: [],
- op: 'and',
- },
- orderBy: { columnName: 'cpu', order: 'desc' },
-});
-
-const columnProgressBarClassName = 'column-progress-bar';
-
-const columnsConfig = [
- {
- title: (
- <div className="column-header-left statefulset-name-header">
- StatefulSet Name
- </div>
- ),
- dataIndex: 'statefulsetName',
- key: 'statefulsetName',
- ellipsis: true,
- width: 80,
- sorter: false,
- align: 'left',
- },
- {
- title: (
- <div className="column-header-left namespace-name-header">
- Namespace Name
- </div>
- ),
- dataIndex: 'namespaceName',
- key: 'namespaceName',
- ellipsis: true,
- width: 80,
- sorter: false,
- align: 'left',
- },
- {
- title: <div className="column-header small-col">Available</div>,
- dataIndex: 'available_pods',
- key: 'available_pods',
- ellipsis: true,
- sorter: true,
- align: 'left',
- className: `column small-col`,
- },
- {
- title: <div className="column-header small-col">Desired</div>,
- dataIndex: 'desired_pods',
- key: 'desired_pods',
- sorter: true,
- align: 'left',
- className: `column small-col`,
- },
- {
- title: <div className="column-header med-col">CPU Req Usage (%)</div>,
- dataIndex: 'cpu_request',
- key: 'cpu_request',
- width: 180,
- ellipsis: true,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">CPU Limit Usage (%)</div>,
- dataIndex: 'cpu_limit',
- key: 'cpu_limit',
- width: 120,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header small-col">CPU Usage (cores)</div>,
- dataIndex: 'cpu',
- key: 'cpu',
- width: 80,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">Mem Req Usage (%)</div>,
- dataIndex: 'memory_request',
- key: 'memory_request',
- width: 120,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">Mem Limit Usage (%)</div>,
- dataIndex: 'memory_limit',
- key: 'memory_limit',
- width: 120,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">Mem Usage (WSS)</div>,
- dataIndex: 'memory',
- key: 'memory',
- width: 120,
- ellipsis: true,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
-];
-
-export const getK8sStatefulSetsListColumns = (
- groupBy: IBuilderQuery['groupBy'],
-): ColumnType<K8sStatefulSetsRowData>[] => {
- if (groupBy.length > 0) {
- const filteredColumns = [...columnsConfig].filter(
- (column) => column.key !== 'statefulsetName',
- );
- filteredColumns.unshift(statefulSetGroupColumnConfig);
- return filteredColumns as ColumnType<K8sStatefulSetsRowData>[];
- }
-
- return columnsConfig as ColumnType<K8sStatefulSetsRowData>[];
-};
-
-const dotToUnder: Record<string, keyof K8sStatefulSetsData['meta']> = {
- 'k8s.namespace.name': 'k8s_namespace_name',
- 'k8s.statefulset.name': 'k8s_statefulset_name',
-};
-
-const getGroupByEle = (
- statefulSet: K8sStatefulSetsData,
- groupBy: IBuilderQuery['groupBy'],
-): React.ReactNode => {
- const groupByValues: string[] = [];
-
- groupBy.forEach((group) => {
- const rawKey = group.key as string;
-
- // Choose mapped key if present, otherwise use rawKey
- const metaKey = (dotToUnder[rawKey] ??
- rawKey) as keyof typeof statefulSet.meta;
- const value = statefulSet.meta[metaKey];
-
- groupByValues.push(value);
- });
-
- return (
- <div className="pod-group">
- {groupByValues.map((value) => (
- <Tag key={value} color={Color.BG_SLATE_400} className="pod-group-tag-item">
- {value === '' ? '<no-value>' : value}
- </Tag>
- ))}
- </div>
- );
-};
-
-export const formatDataForTable = (
- data: K8sStatefulSetsData[],
- groupBy: IBuilderQuery['groupBy'],
-): K8sStatefulSetsRowData[] =>
- data.map((statefulSet, index) => ({
- key: index.toString(),
- statefulsetUID: statefulSet.statefulSetName,
- statefulsetName: (
- <Tooltip title={statefulSet.meta.k8s_statefulset_name}>
- {statefulSet.meta.k8s_statefulset_name || ''}
- </Tooltip>
- ),
- namespaceName: (
- <Tooltip title={statefulSet.meta.k8s_namespace_name}>
- {statefulSet.meta.k8s_namespace_name || ''}
- </Tooltip>
- ),
- cpu_request: (
- <ValidateColumnValueWrapper
- value={statefulSet.cpuRequest}
- entity={K8sCategory.STATEFULSETS}
- attribute="CPU Request"
- >
- <div className="progress-container">
- <EntityProgressBar value={statefulSet.cpuRequest} type="request" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- cpu_limit: (
- <ValidateColumnValueWrapper
- value={statefulSet.cpuLimit}
- entity={K8sCategory.STATEFULSETS}
- attribute="CPU Limit"
- >
- <div className="progress-container">
- <EntityProgressBar value={statefulSet.cpuLimit} type="limit" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- cpu: (
- <ValidateColumnValueWrapper value={statefulSet.cpuUsage}>
- {statefulSet.cpuUsage}
- </ValidateColumnValueWrapper>
- ),
- memory_request: (
- <ValidateColumnValueWrapper
- value={statefulSet.memoryRequest}
- entity={K8sCategory.STATEFULSETS}
- attribute="Memory Request"
- >
- <div className="progress-container">
- <EntityProgressBar value={statefulSet.memoryRequest} type="request" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- memory_limit: (
- <ValidateColumnValueWrapper
- value={statefulSet.memoryLimit}
- entity={K8sCategory.STATEFULSETS}
- attribute="Memory Limit"
- >
- <div className="progress-container">
- <EntityProgressBar value={statefulSet.memoryLimit} type="limit" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- memory: (
- <ValidateColumnValueWrapper value={statefulSet.memoryUsage}>
- {formatBytes(statefulSet.memoryUsage)}
- </ValidateColumnValueWrapper>
- ),
- available_pods: (
- <ValidateColumnValueWrapper value={statefulSet.availablePods}>
- {statefulSet.availablePods}
- </ValidateColumnValueWrapper>
- ),
- desired_pods: (
- <ValidateColumnValueWrapper value={statefulSet.desiredPods}>
- {statefulSet.desiredPods}
- </ValidateColumnValueWrapper>
- ),
- statefulSetGroup: getGroupByEle(statefulSet, groupBy),
- meta: statefulSet.meta,
- ...statefulSet.meta,
- groupedByMeta: statefulSet.meta,
- }));
diff --git a/frontend/src/container/InfraMonitoringK8s/Volumes/K8sVolumesList.styles.scss b/frontend/src/container/InfraMonitoringK8s/Volumes/K8sVolumesList.styles.scss
deleted file mode 100644
index 3d15c37f90..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Volumes/K8sVolumesList.styles.scss
+++ /dev/null
@@ -1,45 +0,0 @@
-.infra-monitoring-container {
- .volumes-list-table {
- .expanded-table-container {
- padding-left: 60px;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
- }
-}
-
-.ant-table-cell {
- &:has(.pvc-name-header) {
- min-width: 250px !important;
- max-width: 250px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.namespace-name-header) {
- min-width: 220px !important;
- max-width: 220px !important;
- }
-}
-
-.ant-table-cell {
- &:has(.small-col) {
- min-width: 120px !important;
- max-width: 120px !important;
- }
-}
-
-.expanded-volumes-list-table {
- .ant-table-cell {
- min-width: 223px !important;
- max-width: 223px !important;
- }
-
- .ant-table-row-expand-icon-cell {
- min-width: 30px !important;
- max-width: 30px !important;
- }
-}
diff --git a/frontend/src/container/InfraMonitoringK8s/Volumes/K8sVolumesList.tsx b/frontend/src/container/InfraMonitoringK8s/Volumes/K8sVolumesList.tsx
index 2d30ed22f4..977d9ad569 100644
--- a/frontend/src/container/InfraMonitoringK8s/Volumes/K8sVolumesList.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/Volumes/K8sVolumesList.tsx
@@ -1,676 +1,119 @@
-import React, { useCallback, useEffect, useMemo, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { LoadingOutlined } from '@ant-design/icons';
-import {
- Button,
- Spin,
- Table,
- TableColumnType as ColumnType,
- TablePaginationConfig,
- TableProps,
- Typography,
-} from 'antd';
-import type { SorterResult } from 'antd/es/table/interface';
-import logEvent from 'api/common/logEvent';
-import { K8sVolumesListPayload } from 'api/infraMonitoring/getK8sVolumesList';
-import classNames from 'classnames';
+import React, { useCallback } from 'react';
import { InfraMonitoringEvents } from 'constants/events';
import { FeatureKeys } from 'constants/features';
-import { useGetK8sVolumesList } from 'hooks/infraMonitoring/useGetK8sVolumesList';
-import { useGetAggregateKeys } from 'hooks/queryBuilder/useGetAggregateKeys';
-import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
-import { ChevronDown, ChevronRight } from 'lucide-react';
import { useAppContext } from 'providers/App/App';
-import { AppState } from 'store/reducers';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { buildAbsolutePath, isModifierKeyPressed } from 'utils/app';
-import { openInNewTab } from 'utils/navigation';
-
-import emptyStateUrl from '@/assets/Icons/emptyState.svg';
+import K8sBaseDetails, { K8sDetailsFilters } from '../Base/K8sBaseDetails';
+import { K8sBaseList } from '../Base/K8sBaseList';
+import { K8sBaseFilters } from '../Base/types';
+import { InfraMonitoringEntity } from '../constants';
+import { getK8sVolumesList, K8sVolumesData } from './api';
import {
- GetK8sEntityToAggregateAttribute,
- INFRA_MONITORING_K8S_PARAMS_KEYS,
- K8sCategory,
-} from '../constants';
-import {
- useInfraMonitoringCurrentPage,
- useInfraMonitoringGroupBy,
- useInfraMonitoringOrderBy,
- useInfraMonitoringVolumeUID,
-} from '../hooks';
-import K8sHeader from '../K8sHeader';
-import LoadingContainer from '../LoadingContainer';
-import { usePageSize } from '../utils';
+ getVolumeMetricsQueryPayload,
+ k8sVolumeDetailsMetadataConfig,
+ k8sVolumeGetEntityName,
+ k8sVolumeGetSelectedItemFilters,
+ k8sVolumeInitialEventsFilter,
+ k8sVolumeInitialFilters,
+ k8sVolumeInitialLogTracesFilter,
+ volumeWidgetInfo,
+} from './constants';
import {
- defaultAddedColumns,
- formatDataForTable,
- getK8sVolumesListColumns,
- getK8sVolumesListQuery,
- getVolumeListGroupedByRowDataQueryKey,
- getVolumesListQueryKey,
- K8sVolumesRowData,
-} from './utils';
-import VolumeDetails from './VolumeDetails';
-
-import '../InfraMonitoringK8s.styles.scss';
-import './K8sVolumesList.styles.scss';
+ k8sVolumesColumns,
+ k8sVolumesColumnsConfig,
+ k8sVolumesRenderRowData,
+} from './table.config';
function K8sVolumesList({
- isFiltersVisible,
- handleFilterVisibilityChange,
- quickFiltersLastUpdated,
+ controlListPrefix,
}: {
- isFiltersVisible: boolean;
- handleFilterVisibilityChange: () => void;
- quickFiltersLastUpdated: number;
+ controlListPrefix?: React.ReactNode;
}): JSX.Element {
- const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
- (state) => state.globalTime,
- );
-
- const [currentPage, setCurrentPage] = useInfraMonitoringCurrentPage();
- const [filtersInitialised, setFiltersInitialised] = useState(false);
-
- const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
-
- const [orderBy, setOrderBy] = useInfraMonitoringOrderBy();
-
- const [
- selectedVolumeUID,
- setselectedVolumeUID,
- ] = useInfraMonitoringVolumeUID();
-
- const { pageSize, setPageSize } = usePageSize(K8sCategory.VOLUMES);
-
- const [groupBy, setGroupBy] = useInfraMonitoringGroupBy();
-
- const [
- selectedRowData,
- setSelectedRowData,
- ] = useState<K8sVolumesRowData | null>(null);
-
- const [groupByOptions, setGroupByOptions] = useState<
- { value: string; label: string }[]
- >([]);
-
- const { currentQuery } = useQueryBuilder();
-
- const queryFilters = useMemo(
- () =>
- currentQuery?.builder?.queryData[0]?.filters || {
- items: [],
- op: 'and',
- },
- [currentQuery?.builder?.queryData],
- );
-
- // Reset pagination every time quick filters are changed
- useEffect(() => {
- if (quickFiltersLastUpdated !== -1) {
- setCurrentPage(1);
- }
- }, [quickFiltersLastUpdated, setCurrentPage]);
-
const { featureFlags } = useAppContext();
const dotMetricsEnabled =
featureFlags?.find((flag) => flag.name === FeatureKeys.DOT_METRICS_ENABLED)
?.active || false;
- const createFiltersForSelectedRowData = (
- selectedRowData: K8sVolumesRowData,
- groupBy: IBuilderQuery['groupBy'],
- ): IBuilderQuery['filters'] => {
- const baseFilters: IBuilderQuery['filters'] = {
- items: [...queryFilters.items],
- op: 'and',
- };
-
- if (!selectedRowData) {
- return baseFilters;
- }
-
- const { groupedByMeta } = selectedRowData;
-
- for (const key of groupBy) {
- baseFilters.items.push({
- key: {
- key: key.key,
- type: null,
- },
- op: '=',
- value: groupedByMeta[key.key],
- id: key.key,
- });
- }
-
- return baseFilters;
- };
-
- const fetchGroupedByRowDataQuery = useMemo(() => {
- if (!selectedRowData) {
- return null;
- }
-
- const baseQuery = getK8sVolumesListQuery();
-
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- return {
- ...baseQuery,
- limit: 10,
- offset: 0,
- filters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [minTime, maxTime, orderBy, selectedRowData, groupBy]);
-
- const groupedByRowDataQueryKey = useMemo(
- () =>
- getVolumeListGroupedByRowDataQueryKey(
- selectedRowData?.groupedByMeta,
- queryFilters,
- orderBy,
- groupBy,
- minTime,
- maxTime,
- ),
- [
- selectedRowData?.groupedByMeta,
- queryFilters,
- orderBy,
- groupBy,
- minTime,
- maxTime,
- ],
- );
-
- const {
- data: groupedByRowData,
- isFetching: isFetchingGroupedByRowData,
- isLoading: isLoadingGroupedByRowData,
- isError: isErrorGroupedByRowData,
- refetch: fetchGroupedByRowData,
- } = useGetK8sVolumesList(
- fetchGroupedByRowDataQuery as K8sVolumesListPayload,
- {
- queryKey: groupedByRowDataQueryKey,
- enabled: !!fetchGroupedByRowDataQuery && !!selectedRowData,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const {
- data: groupByFiltersData,
- isLoading: isLoadingGroupByFilters,
- } = useGetAggregateKeys(
- {
- dataSource: currentQuery.builder.queryData[0].dataSource,
- aggregateAttribute: GetK8sEntityToAggregateAttribute(
- K8sCategory.VOLUMES,
+ const fetchListData = useCallback(
+ async (filters: K8sBaseFilters, signal?: AbortSignal) => {
+ filters.orderBy ||= {
+ columnName: 'usage',
+ order: 'desc',
+ };
+
+ const response = await getK8sVolumesList(
+ filters,
+ signal,
+ undefined,
dotMetricsEnabled,
- ),
- aggregateOperator: 'noop',
- searchText: '',
- tagType: '',
- },
- {
- queryKey: [currentQuery.builder.queryData[0].dataSource, 'noop'],
- },
- true,
- K8sCategory.VOLUMES,
- );
-
- const query = useMemo(() => {
- const baseQuery = getK8sVolumesListQuery();
- const queryPayload = {
- ...baseQuery,
- limit: pageSize,
- offset: (currentPage - 1) * pageSize,
- filters: queryFilters,
- start: Math.floor(minTime / 1000000),
- end: Math.floor(maxTime / 1000000),
- orderBy: orderBy || baseQuery.orderBy,
- };
- if (groupBy.length > 0) {
- queryPayload.groupBy = groupBy;
- }
- return queryPayload;
- }, [pageSize, currentPage, queryFilters, minTime, maxTime, orderBy, groupBy]);
-
- const volumesListQueryKey = useMemo(() => {
- return getVolumesListQueryKey(
- selectedVolumeUID,
- pageSize,
- currentPage,
- queryFilters,
- orderBy,
- groupBy,
- minTime,
- maxTime,
- );
- }, [
- selectedVolumeUID,
- pageSize,
- currentPage,
- queryFilters,
- groupBy,
- orderBy,
- minTime,
- maxTime,
- ]);
-
- const formattedGroupedByVolumesData = useMemo(
- () =>
- formatDataForTable(groupedByRowData?.payload?.data?.records || [], groupBy),
- [groupedByRowData, groupBy],
- );
-
- const nestedVolumesData = useMemo(() => {
- if (!selectedRowData || !groupedByRowData?.payload?.data.records) {
- return [];
- }
- return groupedByRowData?.payload?.data?.records || [];
- }, [groupedByRowData, selectedRowData]);
-
- const { data, isFetching, isLoading, isError } = useGetK8sVolumesList(
- query as K8sVolumesListPayload,
- {
- queryKey: volumesListQueryKey,
- enabled: !!query,
- },
- undefined,
- dotMetricsEnabled,
- );
-
- const volumesData = useMemo(() => data?.payload?.data?.records || [], [data]);
- const totalCount = data?.payload?.data?.total || 0;
-
- const formattedVolumesData = useMemo(
- () => formatDataForTable(volumesData, groupBy),
- [volumesData, groupBy],
- );
-
- const columns = useMemo(() => getK8sVolumesListColumns(groupBy), [groupBy]);
-
- const handleGroupByRowClick = (record: K8sVolumesRowData): void => {
- setSelectedRowData(record);
-
- if (expandedRowKeys.includes(record.key)) {
- setExpandedRowKeys(expandedRowKeys.filter((key) => key !== record.key));
- } else {
- setExpandedRowKeys([record.key]);
- }
- };
-
- useEffect(() => {
- if (selectedRowData) {
- fetchGroupedByRowData();
- }
- }, [selectedRowData, fetchGroupedByRowData]);
-
- const handleTableChange: TableProps<K8sVolumesRowData>['onChange'] = useCallback(
- (
- pagination: TablePaginationConfig,
- _filters: Record<string, (string | number | boolean)[] | null>,
- sorter: SorterResult<K8sVolumesRowData> | SorterResult<K8sVolumesRowData>[],
- ): void => {
- if (pagination.current) {
- setCurrentPage(pagination.current);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Volumes,
- });
- }
-
- if ('field' in sorter && sorter.order) {
- setOrderBy({
- columnName: sorter.field as string,
- order: (sorter.order === 'ascend' ? 'asc' : 'desc') as 'asc' | 'desc',
- });
- } else {
- setOrderBy(null);
- }
- },
- [setCurrentPage, setOrderBy],
- );
-
- const { handleChangeQueryData } = useQueryOperations({
- index: 0,
- query: currentQuery.builder.queryData[0],
- entityVersion: '',
- });
-
- const handleFiltersChange = useCallback(
- (value: IBuilderQuery['filters']): void => {
- handleChangeQueryData('filters', value);
- if (filtersInitialised) {
- setCurrentPage(1);
- } else {
- setFiltersInitialised(true);
- }
+ );
- if (value?.items && value?.items?.length > 0) {
- logEvent(InfraMonitoringEvents.FilterApplied, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Volumes,
- });
- }
+ return {
+ data: response.payload?.data.records || [],
+ total: response.payload?.data.total || 0,
+ error: response.error,
+ rawData: response.payload?.data,
+ };
},
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Volumes,
- total: data?.payload?.data?.total,
- });
- }, [data?.payload?.data?.total]);
-
- const selectedVolumeData = useMemo(() => {
- if (!selectedVolumeUID) {
- return null;
- }
- if (groupBy.length > 0) {
- return (
- nestedVolumesData.find(
- (volume) => volume.persistentVolumeClaimName === selectedVolumeUID,
- ) || null
+ const fetchEntityData = useCallback(
+ async (
+ filters: K8sDetailsFilters,
+ signal?: AbortSignal,
+ ): Promise<{ data: K8sVolumesData | null; error?: string | null }> => {
+ const response = await getK8sVolumesList(
+ {
+ filters: filters.filters,
+ start: filters.start,
+ end: filters.end,
+ limit: 1,
+ offset: 0,
+ },
+ signal,
+ undefined,
+ dotMetricsEnabled,
);
- }
- return (
- volumesData.find(
- (volume) => volume.persistentVolumeClaimName === selectedVolumeUID,
- ) || null
- );
- }, [selectedVolumeUID, volumesData, groupBy.length, nestedVolumesData]);
-
- const openVolumeInNewTab = (record: K8sVolumesRowData): void => {
- const newParams = new URLSearchParams(document.location.search);
- newParams.set(INFRA_MONITORING_K8S_PARAMS_KEYS.VOLUME_UID, record.volumeUID);
- openInNewTab(
- buildAbsolutePath({
- relativePath: '',
- urlQueryString: newParams.toString(),
- }),
- );
- };
-
- const handleRowClick = (
- record: K8sVolumesRowData,
- event: React.MouseEvent,
- ): void => {
- if (event && isModifierKeyPressed(event)) {
- openVolumeInNewTab(record);
- return;
- }
- if (groupBy.length === 0) {
- setSelectedRowData(null);
- setselectedVolumeUID(record.volumeUID);
- } else {
- handleGroupByRowClick(record);
- }
-
- logEvent(InfraMonitoringEvents.ItemClicked, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Volumes,
- });
- };
-
- const nestedColumns = useMemo(() => getK8sVolumesListColumns([]), []);
-
- const isGroupedByAttribute = groupBy.length > 0;
- const handleExpandedRowViewAllClick = (): void => {
- if (!selectedRowData) {
- return;
- }
+ const records = response.payload?.data.records || [];
- const filters = createFiltersForSelectedRowData(selectedRowData, groupBy);
-
- handleFiltersChange(filters);
-
- setCurrentPage(1);
- setSelectedRowData(null);
- setGroupBy([]);
- setOrderBy(null);
- };
-
- const expandedRowRender = (): JSX.Element => (
- <div className="expanded-table-container">
- {isErrorGroupedByRowData && (
- <Typography>{groupedByRowData?.error || 'Something went wrong'}</Typography>
- )}
- {isFetchingGroupedByRowData || isLoadingGroupedByRowData ? (
- <LoadingContainer />
- ) : (
- <div className="expanded-table">
- <Table
- columns={nestedColumns as ColumnType<K8sVolumesRowData>[]}
- dataSource={formattedGroupedByVolumesData}
- pagination={false}
- scroll={{ x: true }}
- tableLayout="fixed"
- size="small"
- loading={{
- spinning: isFetchingGroupedByRowData || isLoadingGroupedByRowData,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- showHeader={false}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => {
- if (event && isModifierKeyPressed(event)) {
- openVolumeInNewTab(record);
- return;
- }
- setselectedVolumeUID(record.volumeUID);
- },
- className: 'expanded-clickable-row',
- })}
- />
-
- {groupedByRowData?.payload?.data?.total &&
- groupedByRowData?.payload?.data?.total > 10 ? (
- <div className="expanded-table-footer">
- <Button
- type="default"
- size="small"
- className="periscope-btn secondary"
- onClick={handleExpandedRowViewAllClick}
- >
- View All
- </Button>
- </div>
- ) : null}
- </div>
- )}
- </div>
- );
-
- const expandRowIconRenderer = ({
- expanded,
- onExpand,
- record,
- }: {
- expanded: boolean;
- onExpand: (
- record: K8sVolumesRowData,
- e: React.MouseEvent<HTMLButtonElement>,
- ) => void;
- record: K8sVolumesRowData;
- }): JSX.Element | null => {
- if (!isGroupedByAttribute) {
- return null;
- }
-
- return expanded ? (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronDown size={14} />
- </Button>
- ) : (
- <Button
- className="periscope-btn ghost"
- onClick={(e: React.MouseEvent<HTMLButtonElement>): void =>
- onExpand(record, e)
- }
- role="button"
- >
- <ChevronRight size={14} />
- </Button>
- );
- };
-
- const handleCloseVolumeDetail = (): void => {
- setselectedVolumeUID(null);
- };
-
- const handleGroupByChange = useCallback(
- (value: IBuilderQuery['groupBy']) => {
- const groupBy = [];
-
- for (let index = 0; index < value.length; index++) {
- const element = (value[index] as unknown) as string;
-
- const key = groupByFiltersData?.payload?.attributeKeys?.find(
- (key) => key.key === element,
- );
-
- if (key) {
- groupBy.push(key);
- }
- }
-
- setCurrentPage(1);
- setGroupBy(groupBy);
- setExpandedRowKeys([]);
-
- logEvent(InfraMonitoringEvents.GroupByChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Volumes,
- });
+ return {
+ data: records.length > 0 ? records[0] : null,
+ error: response.error,
+ };
},
- [groupByFiltersData?.payload?.attributeKeys, setCurrentPage, setGroupBy],
+ [dotMetricsEnabled],
);
- useEffect(() => {
- if (groupByFiltersData?.payload) {
- setGroupByOptions(
- groupByFiltersData?.payload?.attributeKeys?.map((filter) => ({
- value: filter.key,
- label: filter.key,
- })) || [],
- );
- }
- }, [groupByFiltersData]);
-
- const onPaginationChange = (page: number, pageSize: number): void => {
- setCurrentPage(page);
- setPageSize(pageSize);
- logEvent(InfraMonitoringEvents.PageNumberChanged, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.ListPage,
- category: InfraMonitoringEvents.Volumes,
- });
- };
-
- const showTableLoadingState =
- (isFetching || isLoading) && formattedVolumesData.length === 0;
-
return (
- <div className="k8s-list">
- <K8sHeader
- isFiltersVisible={isFiltersVisible}
- handleFilterVisibilityChange={handleFilterVisibilityChange}
- defaultAddedColumns={defaultAddedColumns}
- handleFiltersChange={handleFiltersChange}
- groupByOptions={groupByOptions}
- isLoadingGroupByFilters={isLoadingGroupByFilters}
- handleGroupByChange={handleGroupByChange}
- selectedGroupBy={groupBy}
- entity={K8sCategory.VOLUMES}
- showAutoRefresh={!selectedVolumeData}
- />
- {isError && <Typography>{data?.error || 'Something went wrong'}</Typography>}
-
- <Table
- className={classNames('k8s-list-table', 'volumes-list-table', {
- 'expanded-volumes-list-table': isGroupedByAttribute,
- })}
- dataSource={showTableLoadingState ? [] : formattedVolumesData}
- columns={columns}
- pagination={{
- current: currentPage,
- pageSize,
- total: totalCount,
- showSizeChanger: true,
- hideOnSinglePage: false,
- onChange: onPaginationChange,
- }}
- scroll={{ x: true }}
- loading={{
- spinning: showTableLoadingState,
- indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
- }}
- locale={{
- emptyText: showTableLoadingState ? null : (
- <div className="no-filtered-hosts-message-container">
- <div className="no-filtered-hosts-message-content">
- <img
- src={emptyStateUrl}
- alt="thinking-emoji"
- className="empty-state-svg"
- />
-
- <Typography.Text className="no-filtered-hosts-message">
- This query had no results. Edit your query and try again!
- </Typography.Text>
- </div>
- </div>
- ),
- }}
- tableLayout="fixed"
- onChange={handleTableChange}
- onRow={(
- record,
- ): { onClick: (event: React.MouseEvent) => void; className: string } => ({
- onClick: (event: React.MouseEvent): void => handleRowClick(record, event),
- className: 'clickable-row',
- })}
- expandable={{
- expandedRowRender: isGroupedByAttribute ? expandedRowRender : undefined,
- expandIcon: expandRowIconRenderer,
- expandedRowKeys,
- }}
+ <>
+ <K8sBaseList<K8sVolumesData>
+ controlListPrefix={controlListPrefix}
+ entity={InfraMonitoringEntity.VOLUMES}
+ tableColumnsDefinitions={k8sVolumesColumns}
+ tableColumns={k8sVolumesColumnsConfig}
+ fetchListData={fetchListData}
+ renderRowData={k8sVolumesRenderRowData}
+ eventCategory={InfraMonitoringEvents.Volumes}
/>
- <VolumeDetails
- volume={selectedVolumeData}
- isModalTimeSelection
- onClose={handleCloseVolumeDetail}
+ <K8sBaseDetails<K8sVolumesData>
+ category={InfraMonitoringEntity.VOLUMES}
+ eventCategory={InfraMonitoringEvents.Volume}
+ getSelectedItemFilters={k8sVolumeGetSelectedItemFilters}
+ fetchEntityData={fetchEntityData}
+ getEntityName={k8sVolumeGetEntityName}
+ getInitialLogTracesFilters={k8sVolumeInitialLogTracesFilter}
+ getInitialEventsFilters={k8sVolumeInitialEventsFilter}
+ primaryFilterKeys={k8sVolumeInitialFilters}
+ metadataConfig={k8sVolumeDetailsMetadataConfig}
+ entityWidgetInfo={volumeWidgetInfo}
+ getEntityQueryPayload={getVolumeMetricsQueryPayload}
+ queryKeyPrefix="volume"
+ hideDetailViewTabs
/>
- </div>
+ </>
);
}
diff --git a/frontend/src/container/InfraMonitoringK8s/Volumes/VolumeDetails/VolumeDetails.tsx b/frontend/src/container/InfraMonitoringK8s/Volumes/VolumeDetails/VolumeDetails.tsx
deleted file mode 100644
index 65b261aa52..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Volumes/VolumeDetails/VolumeDetails.tsx
+++ /dev/null
@@ -1,208 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-// eslint-disable-next-line no-restricted-imports
-import { useSelector } from 'react-redux';
-import { Color, Spacing } from '@signozhq/design-tokens';
-import { Divider, Drawer, Tooltip, Typography } from 'antd';
-import logEvent from 'api/common/logEvent';
-import { InfraMonitoringEvents } from 'constants/events';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
-import {
- CustomTimeType,
- Time,
-} from 'container/TopNav/DateTimeSelectionV2/types';
-import { useIsDarkMode } from 'hooks/useDarkMode';
-import GetMinMax from 'lib/getMinMax';
-import { X } from 'lucide-react';
-import { AppState } from 'store/reducers';
-import { GlobalReducer } from 'types/reducer/globalTime';
-
-import VolumeMetrics from '../../EntityDetailsUtils/EntityMetrics';
-import { getVolumeQueryPayload, volumeWidgetInfo } from './constants';
-import { VolumeDetailsProps } from './VoumeDetails.interfaces';
-
-import '../../EntityDetailsUtils/entityDetails.styles.scss';
-
-function VolumeDetails({
- volume,
- onClose,
- isModalTimeSelection,
-}: VolumeDetailsProps): JSX.Element {
- const { maxTime, minTime, selectedTime } = useSelector<
- AppState,
- GlobalReducer
- >((state) => state.globalTime);
-
- const startMs = useMemo(() => Math.floor(Number(minTime) / 1000000000), [
- minTime,
- ]);
- const endMs = useMemo(() => Math.floor(Number(maxTime) / 1000000000), [
- maxTime,
- ]);
-
- const [modalTimeRange, setModalTimeRange] = useState(() => ({
- startTime: startMs,
- endTime: endMs,
- }));
-
- const lastSelectedInterval = useRef<Time | null>(null);
-
- const [selectedInterval, setSelectedInterval] = useState<Time>(
- lastSelectedInterval.current
- ? lastSelectedInterval.current
- : (selectedTime as Time),
- );
-
- const isDarkMode = useIsDarkMode();
-
- useEffect(() => {
- if (volume) {
- logEvent(InfraMonitoringEvents.PageVisited, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Volume,
- });
- }
- }, [volume]);
-
- useEffect(() => {
- const currentSelectedInterval = lastSelectedInterval.current || selectedTime;
- setSelectedInterval(currentSelectedInterval as Time);
-
- if (currentSelectedInterval !== 'custom') {
- const { maxTime, minTime } = GetMinMax(currentSelectedInterval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- }, [selectedTime, minTime, maxTime]);
-
- const handleTimeChange = useCallback(
- (interval: Time | CustomTimeType, dateTimeRange?: [number, number]): void => {
- lastSelectedInterval.current = interval as Time;
- setSelectedInterval(interval as Time);
-
- if (interval === 'custom' && dateTimeRange) {
- setModalTimeRange({
- startTime: Math.floor(dateTimeRange[0] / 1000),
- endTime: Math.floor(dateTimeRange[1] / 1000),
- });
- } else {
- const { maxTime, minTime } = GetMinMax(interval);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
-
- logEvent(InfraMonitoringEvents.TimeUpdated, {
- entity: InfraMonitoringEvents.K8sEntity,
- page: InfraMonitoringEvents.DetailedPage,
- category: InfraMonitoringEvents.Volume,
- interval,
- });
- },
- [],
- );
-
- const handleClose = (): void => {
- lastSelectedInterval.current = null;
- setSelectedInterval(selectedTime as Time);
-
- if (selectedTime !== 'custom') {
- const { maxTime, minTime } = GetMinMax(selectedTime);
-
- setModalTimeRange({
- startTime: Math.floor(minTime / 1000000000),
- endTime: Math.floor(maxTime / 1000000000),
- });
- }
- onClose();
- };
-
- return (
- <Drawer
- width="70%"
- title={
- <>
- <Divider type="vertical" />
- <Typography.Text className="title">
- {volume?.persistentVolumeClaimName}
- </Typography.Text>
- </>
- }
- placement="right"
- onClose={handleClose}
- open={!!volume}
- style={{
- overscrollBehavior: 'contain',
- background: isDarkMode ? Color.BG_INK_400 : Color.BG_VANILLA_100,
- }}
- className="entity-detail-drawer"
- destroyOnClose
- closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
- >
- {volume && (
- <>
- <div className="entity-detail-drawer__entity">
- <div className="entity-details-grid">
- <div className="labels-row">
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- PVC Name
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Cluster Name
- </Typography.Text>
- <Typography.Text
- type="secondary"
- className="entity-details-metadata-label"
- >
- Namespace Name
- </Typography.Text>
- </div>
- <div className="values-row">
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={volume.persistentVolumeClaimName}>
- {volume.persistentVolumeClaimName}
- </Tooltip>
- </Typography.Text>
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={volume.meta.k8s_cluster_name}>
- {volume.meta.k8s_cluster_name}
- </Tooltip>
- </Typography.Text>
- <Typography.Text className="entity-details-metadata-value">
- <Tooltip title={volume.meta.k8s_namespace_name}>
- {volume.meta.k8s_namespace_name}
- </Tooltip>
- </Typography.Text>
- </div>
- </div>
- </div>
-
- <VolumeMetrics
- timeRange={modalTimeRange}
- isModalTimeSelection={isModalTimeSelection}
- handleTimeChange={handleTimeChange}
- selectedInterval={selectedInterval}
- entity={volume}
- entityWidgetInfo={volumeWidgetInfo}
- getEntityQueryPayload={getVolumeQueryPayload}
- queryKey="volumeMetrics"
- category={K8sCategory.VOLUMES}
- />
- </>
- )}
- </Drawer>
- );
-}
-
-export default VolumeDetails;
diff --git a/frontend/src/container/InfraMonitoringK8s/Volumes/VolumeDetails/VoumeDetails.interfaces.ts b/frontend/src/container/InfraMonitoringK8s/Volumes/VolumeDetails/VoumeDetails.interfaces.ts
deleted file mode 100644
index 427ef59da0..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Volumes/VolumeDetails/VoumeDetails.interfaces.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { K8sVolumesData } from 'api/infraMonitoring/getK8sVolumesList';
-
-export type VolumeDetailsProps = {
- volume: K8sVolumesData | null;
- isModalTimeSelection: boolean;
- onClose: () => void;
-};
diff --git a/frontend/src/container/InfraMonitoringK8s/Volumes/VolumeDetails/index.ts b/frontend/src/container/InfraMonitoringK8s/Volumes/VolumeDetails/index.ts
deleted file mode 100644
index 36bfaf26c4..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Volumes/VolumeDetails/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import VolumeDetails from './VolumeDetails';
-
-export default VolumeDetails;
diff --git a/frontend/src/api/infraMonitoring/getK8sVolumesList.ts b/frontend/src/container/InfraMonitoringK8s/Volumes/api.ts
similarity index 64%
rename from frontend/src/api/infraMonitoring/getK8sVolumesList.ts
rename to frontend/src/container/InfraMonitoringK8s/Volumes/api.ts
index c36eb60257..617b0166e5 100644
--- a/frontend/src/api/infraMonitoring/getK8sVolumesList.ts
+++ b/frontend/src/container/InfraMonitoringK8s/Volumes/api.ts
@@ -1,22 +1,10 @@
import axios from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
+import { UnderscoreToDotMap } from 'api/utils';
import { AxiosError } from 'axios';
import { ErrorResponse, SuccessResponse } from 'types/api';
-import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
-import { UnderscoreToDotMap } from '../utils';
-
-export interface K8sVolumesListPayload {
- filters: TagFilter;
- groupBy?: BaseAutocompleteData[];
- offset?: number;
- limit?: number;
- orderBy?: {
- columnName: string;
- order: 'asc' | 'desc';
- };
-}
+import { K8sBaseFilters } from '../Base/types';
export interface K8sVolumesData {
persistentVolumeClaimName: string;
@@ -49,6 +37,7 @@ export interface K8sVolumesListResponse {
};
}
+// TODO(H4ad): Erase this whole file when migrating to openapi
export const volumesMetaMap: Array<{
dot: keyof Record<string, unknown>;
under: keyof K8sVolumesData['meta'];
@@ -68,10 +57,8 @@ export const volumesMetaMap: Array<{
export function mapVolumesMeta(
rawMeta: Record<string, unknown>,
): K8sVolumesData['meta'] {
- // start with everything that was already there
const out: Record<string, unknown> = { ...rawMeta };
- // for each dot→under rule, if the raw has the dot, overwrite the underscore
volumesMetaMap.forEach(({ dot, under }) => {
if (dot in rawMeta) {
const val = rawMeta[dot];
@@ -83,42 +70,47 @@ export function mapVolumesMeta(
}
export const getK8sVolumesList = async (
- props: K8sVolumesListPayload,
+ props: K8sBaseFilters,
signal?: AbortSignal,
headers?: Record<string, string>,
dotMetricsEnabled = false,
): Promise<SuccessResponse<K8sVolumesListResponse> | ErrorResponse> => {
try {
- // Prepare filters
- const requestProps =
- dotMetricsEnabled && Array.isArray(props.filters?.items)
- ? {
- ...props,
- filters: {
- ...props.filters,
- items: props.filters.items.reduce<typeof props.filters.items>(
- (acc, item) => {
- if (item.value === undefined) {
- return acc;
- }
- if (
- item.key &&
- typeof item.key === 'object' &&
- 'key' in item.key &&
- typeof item.key.key === 'string'
- ) {
- const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
- acc.push({ ...item, key: { ...item.key, key: mappedKey } });
- } else {
- acc.push(item);
- }
+ const { orderBy, ...rest } = props;
+ const basePayload = {
+ ...rest,
+ filters: props.filters ?? { items: [], op: 'and' },
+ ...(orderBy != null ? { orderBy } : {}),
+ };
+
+ const requestProps = dotMetricsEnabled
+ ? {
+ ...basePayload,
+ filters: {
+ ...basePayload.filters,
+ items: basePayload.filters.items.reduce<typeof basePayload.filters.items>(
+ (acc, item) => {
+ if (item.value === undefined) {
return acc;
- },
- [] as typeof props.filters.items,
- ),
- },
- }
- : props;
+ }
+ if (
+ item.key &&
+ typeof item.key === 'object' &&
+ 'key' in item.key &&
+ typeof item.key.key === 'string'
+ ) {
+ const mappedKey = UnderscoreToDotMap[item.key.key] ?? item.key.key;
+ acc.push({ ...item, key: { ...item.key, key: mappedKey } });
+ } else {
+ acc.push(item);
+ }
+ return acc;
+ },
+ [] as typeof basePayload.filters.items,
+ ),
+ },
+ }
+ : basePayload;
const response = await axios.post('/pvcs/list', requestProps, {
signal,
diff --git a/frontend/src/container/InfraMonitoringK8s/Volumes/VolumeDetails/constants.ts b/frontend/src/container/InfraMonitoringK8s/Volumes/constants.ts
similarity index 88%
rename from frontend/src/container/InfraMonitoringK8s/Volumes/VolumeDetails/constants.ts
rename to frontend/src/container/InfraMonitoringK8s/Volumes/constants.ts
index 30f2da72e2..bf9d4051c4 100644
--- a/frontend/src/container/InfraMonitoringK8s/Volumes/VolumeDetails/constants.ts
+++ b/frontend/src/container/InfraMonitoringK8s/Volumes/constants.ts
@@ -1,11 +1,75 @@
-import { K8sVolumesData } from 'api/infraMonitoring/getK8sVolumesList';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { v4 } from 'uuid';
+import {
+ createFilterItem,
+ K8sDetailsMetadataConfig,
+} from '../Base/K8sBaseDetails';
+import { QUERY_KEYS } from '../EntityDetailsUtils/utils';
+import { K8sVolumesData } from './api';
+
+export const k8sVolumeGetSelectedItemFilters = (
+ selectedItemId: string,
+): TagFilter => ({
+ op: 'AND',
+ items: [
+ {
+ id: 'k8s_persistentvolumeclaim_name',
+ key: {
+ key: 'k8s_persistentvolumeclaim_name',
+ type: null,
+ },
+ op: '=',
+ value: selectedItemId,
+ },
+ ],
+});
+
+export const k8sVolumeDetailsMetadataConfig: K8sDetailsMetadataConfig<K8sVolumesData>[] = [
+ {
+ label: 'PVC Name',
+ getValue: (p): string => p.persistentVolumeClaimName,
+ },
+ {
+ label: 'Cluster Name',
+ getValue: (p): string => p.meta.k8s_cluster_name,
+ },
+ {
+ label: 'Namespace Name',
+ getValue: (p): string => p.meta.k8s_namespace_name,
+ },
+];
+
+export const k8sVolumeInitialFilters = [
+ QUERY_KEYS.K8S_PERSISTENT_VOLUME_CLAIM_NAME,
+ QUERY_KEYS.K8S_NAMESPACE_NAME,
+];
+
+export const k8sVolumeInitialEventsFilter = (
+ item: K8sVolumesData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_KIND, 'PersistentVolumeClaim'),
+ createFilterItem(QUERY_KEYS.K8S_OBJECT_NAME, item.persistentVolumeClaimName),
+];
+
+export const k8sVolumeInitialLogTracesFilter = (
+ item: K8sVolumesData,
+): ReturnType<typeof createFilterItem>[] => [
+ createFilterItem(
+ QUERY_KEYS.K8S_PERSISTENT_VOLUME_CLAIM_NAME,
+ item.meta.k8s_persistentvolumeclaim_name,
+ ),
+ createFilterItem(QUERY_KEYS.K8S_NAMESPACE_NAME, item.meta.k8s_namespace_name),
+];
+
+export const k8sVolumeGetEntityName = (item: K8sVolumesData): string =>
+ item.persistentVolumeClaimName;
+
export const volumeWidgetInfo = [
{
title: 'Volume available',
@@ -29,7 +93,7 @@ export const volumeWidgetInfo = [
},
];
-export const getVolumeQueryPayload = (
+export const getVolumeMetricsQueryPayload = (
volume: K8sVolumesData,
start: number,
end: number,
diff --git a/frontend/src/container/InfraMonitoringK8s/Volumes/table.config.tsx b/frontend/src/container/InfraMonitoringK8s/Volumes/table.config.tsx
new file mode 100644
index 0000000000..964f3d2007
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Volumes/table.config.tsx
@@ -0,0 +1,164 @@
+import { TableColumnType as ColumnType, Tooltip } from 'antd';
+import { Group } from 'lucide-react';
+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
+
+import { K8sRenderedRowData } from '../Base/types';
+import { IEntityColumn } from '../Base/useInfraMonitoringTableColumnsStore';
+import { getGroupByEl, getGroupedByMeta, getRowKey } from '../Base/utils';
+import { formatBytes, ValidateColumnValueWrapper } from '../commonUtils';
+import { K8sVolumesData } from './api';
+
+import styles from './table.module.scss';
+
+export const k8sVolumesColumns: IEntityColumn[] = [
+ {
+ label: 'Volume Group',
+ value: 'volumeGroup',
+ id: 'volumeGroup',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-collapse',
+ },
+ {
+ label: 'PVC Name',
+ value: 'pvcName',
+ id: 'pvcName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'hidden-on-expand',
+ },
+ {
+ label: 'Namespace Name',
+ value: 'namespaceName',
+ id: 'namespaceName',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Volume Capacity',
+ value: 'capacity',
+ id: 'capacity',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Volume Utilization',
+ value: 'usage',
+ id: 'usage',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+ {
+ label: 'Volume Available',
+ value: 'available',
+ id: 'available',
+ canBeHidden: false,
+ defaultVisibility: true,
+ behavior: 'always-visible',
+ },
+];
+
+export const k8sVolumesColumnsConfig: ColumnType<K8sRenderedRowData>[] = [
+ {
+ title: (
+ <div className={styles.entityGroupHeader}>
+ <Group size={14} /> VOLUME GROUP
+ </div>
+ ),
+ dataIndex: 'volumeGroup',
+ key: 'volumeGroup',
+ ellipsis: true,
+ width: 150,
+ align: 'left',
+ sorter: false,
+ },
+ {
+ title: <div>PVC Name</div>,
+ dataIndex: 'pvcName',
+ key: 'pvcName',
+ ellipsis: true,
+ width: 120,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>Namespace Name</div>,
+ dataIndex: 'namespaceName',
+ key: 'namespaceName',
+ ellipsis: true,
+ width: 120,
+ sorter: false,
+ align: 'left',
+ },
+ {
+ title: <div>Volume Capacity</div>,
+ dataIndex: 'capacity',
+ key: 'capacity',
+ ellipsis: true,
+ width: 120,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Volume Utilization</div>,
+ dataIndex: 'usage',
+ key: 'usage',
+ width: 100,
+ sorter: true,
+ align: 'left',
+ },
+ {
+ title: <div>Volume Available</div>,
+ dataIndex: 'available',
+ key: 'available',
+ width: 80,
+ sorter: true,
+ align: 'left',
+ },
+];
+
+export const k8sVolumesRenderRowData = (
+ volume: K8sVolumesData,
+ groupBy: BaseAutocompleteData[],
+): K8sRenderedRowData => ({
+ key: getRowKey(
+ volume,
+ () =>
+ volume.persistentVolumeClaimName ||
+ volume.meta.k8s_persistentvolumeclaim_name ||
+ '',
+ groupBy,
+ ),
+ itemKey: volume.persistentVolumeClaimName,
+ pvcName: (
+ <Tooltip title={volume.persistentVolumeClaimName}>
+ {volume.persistentVolumeClaimName || ''}
+ </Tooltip>
+ ),
+ namespaceName: (
+ <Tooltip title={volume.meta.k8s_namespace_name}>
+ {volume.meta.k8s_namespace_name || ''}
+ </Tooltip>
+ ),
+ available: (
+ <ValidateColumnValueWrapper value={volume.volumeAvailable}>
+ {formatBytes(volume.volumeAvailable)}
+ </ValidateColumnValueWrapper>
+ ),
+ capacity: (
+ <ValidateColumnValueWrapper value={volume.volumeCapacity}>
+ {formatBytes(volume.volumeCapacity)}
+ </ValidateColumnValueWrapper>
+ ),
+ usage: (
+ <ValidateColumnValueWrapper value={volume.volumeUsage}>
+ {formatBytes(volume.volumeUsage)}
+ </ValidateColumnValueWrapper>
+ ),
+ volumeGroup: getGroupByEl(volume, groupBy),
+ ...volume.meta,
+ groupedByMeta: getGroupedByMeta(volume, groupBy),
+});
diff --git a/frontend/src/container/InfraMonitoringK8s/Volumes/table.module.scss b/frontend/src/container/InfraMonitoringK8s/Volumes/table.module.scss
new file mode 100644
index 0000000000..b1fb6dd7c2
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/Volumes/table.module.scss
@@ -0,0 +1,6 @@
+.entityGroupHeader {
+ padding-left: var(--spacing-5);
+ gap: var(--spacing-5);
+ display: flex;
+ align-items: center;
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/Volumes/utils.tsx b/frontend/src/container/InfraMonitoringK8s/Volumes/utils.tsx
deleted file mode 100644
index c4bf62bff3..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/Volumes/utils.tsx
+++ /dev/null
@@ -1,285 +0,0 @@
-import { Color } from '@signozhq/design-tokens';
-import { TableColumnType as ColumnType, Tag, Tooltip } from 'antd';
-import {
- K8sVolumesData,
- K8sVolumesListPayload,
-} from 'api/infraMonitoring/getK8sVolumesList';
-import { Group } from 'lucide-react';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-
-import { formatBytes, ValidateColumnValueWrapper } from '../commonUtils';
-import { IEntityColumn } from '../utils';
-
-export const defaultAddedColumns: IEntityColumn[] = [
- {
- label: 'PVC Name',
- value: 'pvcName',
- id: 'pvcName',
- canRemove: false,
- },
- {
- label: 'Namespace Name',
- value: 'namespaceName',
- id: 'namespaceName',
- canRemove: false,
- },
- {
- label: 'Volume Capacity',
- value: 'capacity',
- id: 'capacity',
- canRemove: false,
- },
- {
- label: 'Volume Utilization',
- value: 'usage',
- id: 'usage',
- canRemove: false,
- },
- {
- label: 'Volume Available',
- value: 'available',
- id: 'available',
- canRemove: false,
- },
-];
-
-export interface K8sVolumesRowData {
- key: string;
- volumeUID: string;
- pvcName: React.ReactNode;
- namespaceName: React.ReactNode;
- capacity: React.ReactNode;
- usage: React.ReactNode;
- available: React.ReactNode;
- groupedByMeta?: any;
-}
-
-const volumeGroupColumnConfig = {
- title: (
- <div className="column-header entity-group-header">
- <Group size={14} /> VOLUME GROUP
- </div>
- ),
- dataIndex: 'volumeGroup',
- key: 'volumeGroup',
- ellipsis: true,
- width: 150,
- align: 'left',
- sorter: false,
- className: 'column entity-group-header',
-};
-
-export const getK8sVolumesListQuery = (): K8sVolumesListPayload => ({
- filters: {
- items: [],
- op: 'and',
- },
- orderBy: { columnName: 'usage', order: 'desc' },
-});
-
-export const getVolumeListGroupedByRowDataQueryKey = (
- groupedByMeta: K8sVolumesData['meta'] | undefined,
- queryFilters: IBuilderQuery['filters'],
- orderBy: { columnName: string; order: 'asc' | 'desc' } | null,
- groupBy: IBuilderQuery['groupBy'],
- minTime: number,
- maxTime: number,
-): (string | undefined)[] => {
- // When we have grouped by metadata defined
- // We need to leave out the min/max time
- // Otherwise it will cause a loop
- const groupedByMetaStr = JSON.stringify(groupedByMeta || undefined) ?? '';
- if (groupedByMetaStr) {
- return [
- 'volumeList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- groupedByMetaStr,
- ];
- }
- return [
- 'volumeList',
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- groupedByMetaStr,
- String(minTime),
- String(maxTime),
- ];
-};
-
-export const getVolumesListQueryKey = (
- selectedVolumeUID: string | null,
- pageSize: number,
- currentPage: number,
- queryFilters: IBuilderQuery['filters'],
- orderBy: { columnName: string; order: 'asc' | 'desc' } | null,
- groupBy: IBuilderQuery['groupBy'],
- minTime: number,
- maxTime: number,
-): (string | undefined)[] => {
- // When selected volume is defined
- // We need to leave out the min/max time
- // Otherwise it will cause a loop
- if (selectedVolumeUID) {
- return [
- 'volumeList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- ];
- }
-
- return [
- 'volumeList',
- String(pageSize),
- String(currentPage),
- JSON.stringify(queryFilters),
- JSON.stringify(orderBy),
- JSON.stringify(groupBy),
- String(minTime),
- String(maxTime),
- ];
-};
-
-const columnsConfig = [
- {
- title: <div className="column-header-left pvc-name-header">PVC Name</div>,
- dataIndex: 'pvcName',
- key: 'pvcName',
- ellipsis: true,
- width: 120,
- sorter: false,
- align: 'left',
- },
- {
- title: (
- <div className="column-header-left namespace-name-header">
- Namespace Name
- </div>
- ),
- dataIndex: 'namespaceName',
- key: 'namespaceName',
- ellipsis: true,
- width: 120,
- sorter: false,
- align: 'left',
- },
- {
- title: <div className="column-header-left small-col">Volume Capacity</div>,
- dataIndex: 'capacity',
- key: 'capacity',
- ellipsis: true,
- width: 120,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header-left small-col">Volume Utilization</div>,
- dataIndex: 'usage',
- key: 'usage',
- width: 100,
- sorter: true,
- align: 'left',
- },
- {
- title: <div className="column-header-left small-col">Volume Available</div>,
- dataIndex: 'available',
- key: 'available',
- width: 80,
- sorter: true,
- align: 'left',
- },
-];
-
-export const getK8sVolumesListColumns = (
- groupBy: IBuilderQuery['groupBy'],
-): ColumnType<K8sVolumesRowData>[] => {
- if (groupBy.length > 0) {
- const filteredColumns = [...columnsConfig].filter(
- (column) => column.key !== 'pvcName',
- );
- filteredColumns.unshift(volumeGroupColumnConfig);
- return filteredColumns as ColumnType<K8sVolumesRowData>[];
- }
-
- return columnsConfig as ColumnType<K8sVolumesRowData>[];
-};
-
-const dotToUnder: Record<string, keyof K8sVolumesData['meta']> = {
- 'k8s.namespace.name': 'k8s_namespace_name',
- 'k8s.node.name': 'k8s_node_name',
- 'k8s.pod.name': 'k8s_pod_name',
- 'k8s.pod.uid': 'k8s_pod_uid',
- 'k8s.statefulset.name': 'k8s_statefulset_name',
- 'k8s.cluster.name': 'k8s_cluster_name',
- 'k8s.persistentvolumeclaim.name': 'k8s_persistentvolumeclaim_name',
-};
-
-const getGroupByEle = (
- volume: K8sVolumesData,
- groupBy: IBuilderQuery['groupBy'],
-): React.ReactNode => {
- const groupByValues: string[] = [];
-
- groupBy.forEach((group) => {
- const rawKey = group.key as string;
-
- const metaKey = (dotToUnder[rawKey] ?? rawKey) as keyof typeof volume.meta;
-
- const value = volume.meta[metaKey];
-
- groupByValues.push(value);
- });
-
- return (
- <div className="pod-group">
- {groupByValues.map((value) => (
- <Tag key={value} color={Color.BG_SLATE_400} className="pod-group-tag-item">
- {value === '' ? '<no-value>' : value}
- </Tag>
- ))}
- </div>
- );
-};
-
-export const formatDataForTable = (
- data: K8sVolumesData[],
- groupBy: IBuilderQuery['groupBy'],
-): K8sVolumesRowData[] =>
- data.map((volume, index) => ({
- key: index.toString(),
- volumeUID: volume.persistentVolumeClaimName,
- pvcName: (
- <Tooltip title={volume.persistentVolumeClaimName}>
- {volume.persistentVolumeClaimName || ''}
- </Tooltip>
- ),
- namespaceName: (
- <Tooltip title={volume.meta.k8s_namespace_name}>
- {volume.meta.k8s_namespace_name || ''}
- </Tooltip>
- ),
- available: (
- <ValidateColumnValueWrapper value={volume.volumeAvailable}>
- {formatBytes(volume.volumeAvailable)}
- </ValidateColumnValueWrapper>
- ),
- capacity: (
- <ValidateColumnValueWrapper value={volume.volumeCapacity}>
- {formatBytes(volume.volumeCapacity)}
- </ValidateColumnValueWrapper>
- ),
- usage: (
- <ValidateColumnValueWrapper value={volume.volumeUsage}>
- {formatBytes(volume.volumeUsage)}
- </ValidateColumnValueWrapper>
- ),
- volumeGroup: getGroupByEle(volume, groupBy),
- meta: volume.meta,
- ...volume.meta,
- groupedByMeta: volume.meta,
- }));
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/Clusters/ClusterDetails/ClusterDetails.test.tsx b/frontend/src/container/InfraMonitoringK8s/__tests__/Clusters/ClusterDetails/ClusterDetails.test.tsx
deleted file mode 100644
index 7ffec37d73..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/__tests__/Clusters/ClusterDetails/ClusterDetails.test.tsx
+++ /dev/null
@@ -1,143 +0,0 @@
-import setupCommonMocks from '../../commonMocks';
-
-setupCommonMocks();
-
-import { QueryClient, QueryClientProvider } from 'react-query';
-// eslint-disable-next-line no-restricted-imports
-import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
-import { fireEvent, render, screen } from '@testing-library/react';
-import ClusterDetails from 'container/InfraMonitoringK8s/Clusters/ClusterDetails/ClusterDetails';
-import { withNuqsTestingAdapter } from 'nuqs/adapters/testing';
-import store from 'store';
-
-const queryClient = new QueryClient();
-
-const Wrapper = withNuqsTestingAdapter({ searchParams: {} });
-
-describe('ClusterDetails', () => {
- const mockCluster = {
- meta: {
- k8s_cluster_name: 'test-cluster',
- },
- } as any;
- const mockOnClose = jest.fn();
-
- it('should render modal with relevant metadata', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <ClusterDetails
- cluster={mockCluster}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const clusterNameElements = screen.getAllByText('test-cluster');
- expect(clusterNameElements.length).toBeGreaterThan(0);
- expect(clusterNameElements[0]).toBeInTheDocument();
- });
-
- it('should render modal with 4 tabs', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <ClusterDetails
- cluster={mockCluster}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByText('Metrics');
- expect(metricsTab).toBeInTheDocument();
-
- const eventsTab = screen.getByText('Events');
- expect(eventsTab).toBeInTheDocument();
-
- const logsTab = screen.getByText('Logs');
- expect(logsTab).toBeInTheDocument();
-
- const tracesTab = screen.getByText('Traces');
- expect(tracesTab).toBeInTheDocument();
- });
-
- it('default tab should be metrics', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <ClusterDetails
- cluster={mockCluster}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByRole('radio', { name: 'Metrics' });
- expect(metricsTab).toBeChecked();
- });
-
- it('should switch to events tab when events tab is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <ClusterDetails
- cluster={mockCluster}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const eventsTab = screen.getByRole('radio', { name: 'Events' });
- expect(eventsTab).not.toBeChecked();
- fireEvent.click(eventsTab);
- expect(eventsTab).toBeChecked();
- });
-
- it('should close modal when close button is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <ClusterDetails
- cluster={mockCluster}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const closeButton = screen.getByRole('button', { name: 'Close' });
- fireEvent.click(closeButton);
- expect(mockOnClose).toHaveBeenCalled();
- });
-});
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/DaemonSets/DaemonSetDetails/DaemonSetDetails.test.tsx b/frontend/src/container/InfraMonitoringK8s/__tests__/DaemonSets/DaemonSetDetails/DaemonSetDetails.test.tsx
deleted file mode 100644
index 868124197c..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/__tests__/DaemonSets/DaemonSetDetails/DaemonSetDetails.test.tsx
+++ /dev/null
@@ -1,153 +0,0 @@
-import setupCommonMocks from '../../commonMocks';
-
-setupCommonMocks();
-
-import { QueryClient, QueryClientProvider } from 'react-query';
-// eslint-disable-next-line no-restricted-imports
-import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
-import { fireEvent, render, screen } from '@testing-library/react';
-import DaemonSetDetails from 'container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/DaemonSetDetails';
-import { withNuqsTestingAdapter } from 'nuqs/adapters/testing';
-import store from 'store';
-
-const queryClient = new QueryClient();
-
-const Wrapper = withNuqsTestingAdapter({ searchParams: {} });
-
-describe('DaemonSetDetails', () => {
- const mockDaemonSet = {
- meta: {
- k8s_daemonset_name: 'test-daemon-set',
- k8s_cluster_name: 'test-cluster',
- k8s_namespace_name: 'test-namespace',
- },
- } as any;
- const mockOnClose = jest.fn();
-
- it('should render modal with relevant metadata', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <DaemonSetDetails
- daemonSet={mockDaemonSet}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const daemonSetNameElements = screen.getAllByText('test-daemon-set');
- expect(daemonSetNameElements.length).toBeGreaterThan(0);
- expect(daemonSetNameElements[0]).toBeInTheDocument();
-
- const clusterNameElements = screen.getAllByText('test-cluster');
- expect(clusterNameElements.length).toBeGreaterThan(0);
- expect(clusterNameElements[0]).toBeInTheDocument();
-
- const namespaceNameElements = screen.getAllByText('test-namespace');
- expect(namespaceNameElements.length).toBeGreaterThan(0);
- expect(namespaceNameElements[0]).toBeInTheDocument();
- });
-
- it('should render modal with 4 tabs', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <DaemonSetDetails
- daemonSet={mockDaemonSet}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByText('Metrics');
- expect(metricsTab).toBeInTheDocument();
-
- const eventsTab = screen.getByText('Events');
- expect(eventsTab).toBeInTheDocument();
-
- const logsTab = screen.getByText('Logs');
- expect(logsTab).toBeInTheDocument();
-
- const tracesTab = screen.getByText('Traces');
- expect(tracesTab).toBeInTheDocument();
- });
-
- it('default tab should be metrics', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <DaemonSetDetails
- daemonSet={mockDaemonSet}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByRole('radio', { name: 'Metrics' });
- expect(metricsTab).toBeChecked();
- });
-
- it('should switch to events tab when events tab is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <DaemonSetDetails
- daemonSet={mockDaemonSet}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const eventsTab = screen.getByRole('radio', { name: 'Events' });
- expect(eventsTab).not.toBeChecked();
- fireEvent.click(eventsTab);
- expect(eventsTab).toBeChecked();
- });
-
- it('should close modal when close button is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <DaemonSetDetails
- daemonSet={mockDaemonSet}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const closeButton = screen.getByRole('button', { name: 'Close' });
- fireEvent.click(closeButton);
- expect(mockOnClose).toHaveBeenCalled();
- });
-});
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/Deployments/DeploymentDetails/DeploymentDetails.test.tsx b/frontend/src/container/InfraMonitoringK8s/__tests__/Deployments/DeploymentDetails/DeploymentDetails.test.tsx
deleted file mode 100644
index d6fcec81a9..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/__tests__/Deployments/DeploymentDetails/DeploymentDetails.test.tsx
+++ /dev/null
@@ -1,153 +0,0 @@
-import setupCommonMocks from '../../commonMocks';
-
-setupCommonMocks();
-
-import { QueryClient, QueryClientProvider } from 'react-query';
-// eslint-disable-next-line no-restricted-imports
-import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
-import { fireEvent, render, screen } from '@testing-library/react';
-import DeploymentDetails from 'container/InfraMonitoringK8s/Deployments/DeploymentDetails/DeploymentDetails';
-import { withNuqsTestingAdapter } from 'nuqs/adapters/testing';
-import store from 'store';
-
-const queryClient = new QueryClient();
-
-const Wrapper = withNuqsTestingAdapter({ searchParams: {} });
-
-describe('DeploymentDetails', () => {
- const mockDeployment = {
- meta: {
- k8s_deployment_name: 'test-deployment',
- k8s_cluster_name: 'test-cluster',
- k8s_namespace_name: 'test-namespace',
- },
- } as any;
- const mockOnClose = jest.fn();
-
- it('should render modal with relevant metadata', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <DeploymentDetails
- deployment={mockDeployment}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const deploymentNameElements = screen.getAllByText('test-deployment');
- expect(deploymentNameElements.length).toBeGreaterThan(0);
- expect(deploymentNameElements[0]).toBeInTheDocument();
-
- const clusterNameElements = screen.getAllByText('test-cluster');
- expect(clusterNameElements.length).toBeGreaterThan(0);
- expect(clusterNameElements[0]).toBeInTheDocument();
-
- const namespaceNameElements = screen.getAllByText('test-namespace');
- expect(namespaceNameElements.length).toBeGreaterThan(0);
- expect(namespaceNameElements[0]).toBeInTheDocument();
- });
-
- it('should render modal with 4 tabs', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <DeploymentDetails
- deployment={mockDeployment}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByText('Metrics');
- expect(metricsTab).toBeInTheDocument();
-
- const eventsTab = screen.getByText('Events');
- expect(eventsTab).toBeInTheDocument();
-
- const logsTab = screen.getByText('Logs');
- expect(logsTab).toBeInTheDocument();
-
- const tracesTab = screen.getByText('Traces');
- expect(tracesTab).toBeInTheDocument();
- });
-
- it('default tab should be metrics', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <DeploymentDetails
- deployment={mockDeployment}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByRole('radio', { name: 'Metrics' });
- expect(metricsTab).toBeChecked();
- });
-
- it('should switch to events tab when events tab is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <DeploymentDetails
- deployment={mockDeployment}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const eventsTab = screen.getByRole('radio', { name: 'Events' });
- expect(eventsTab).not.toBeChecked();
- fireEvent.click(eventsTab);
- expect(eventsTab).toBeChecked();
- });
-
- it('should close modal when close button is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <DeploymentDetails
- deployment={mockDeployment}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const closeButton = screen.getByRole('button', { name: 'Close' });
- fireEvent.click(closeButton);
- expect(mockOnClose).toHaveBeenCalled();
- });
-});
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/Jobs/JobDetails/JobDetails.test.tsx b/frontend/src/container/InfraMonitoringK8s/__tests__/Jobs/JobDetails/JobDetails.test.tsx
deleted file mode 100644
index e615413420..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/__tests__/Jobs/JobDetails/JobDetails.test.tsx
+++ /dev/null
@@ -1,128 +0,0 @@
-import setupCommonMocks from '../../commonMocks';
-
-setupCommonMocks();
-
-import { QueryClient, QueryClientProvider } from 'react-query';
-// eslint-disable-next-line no-restricted-imports
-import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
-import { fireEvent, render, screen } from '@testing-library/react';
-import JobDetails from 'container/InfraMonitoringK8s/Jobs/JobDetails/JobDetails';
-import { withNuqsTestingAdapter } from 'nuqs/adapters/testing';
-import store from 'store';
-
-const queryClient = new QueryClient();
-
-const Wrapper = withNuqsTestingAdapter({ searchParams: {} });
-
-describe('JobDetails', () => {
- const mockJob = {
- meta: {
- k8s_job_name: 'test-job',
- k8s_namespace_name: 'test-namespace',
- },
- } as any;
- const mockOnClose = jest.fn();
-
- it('should render modal with relevant metadata', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <JobDetails job={mockJob} isModalTimeSelection onClose={mockOnClose} />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const jobNameElements = screen.getAllByText('test-job');
- expect(jobNameElements.length).toBeGreaterThan(0);
- expect(jobNameElements[0]).toBeInTheDocument();
-
- const namespaceNameElements = screen.getAllByText('test-namespace');
- expect(namespaceNameElements.length).toBeGreaterThan(0);
- expect(namespaceNameElements[0]).toBeInTheDocument();
- });
-
- it('should render modal with 4 tabs', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <JobDetails job={mockJob} isModalTimeSelection onClose={mockOnClose} />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByText('Metrics');
- expect(metricsTab).toBeInTheDocument();
-
- const eventsTab = screen.getByText('Events');
- expect(eventsTab).toBeInTheDocument();
-
- const logsTab = screen.getByText('Logs');
- expect(logsTab).toBeInTheDocument();
-
- const tracesTab = screen.getByText('Traces');
- expect(tracesTab).toBeInTheDocument();
- });
-
- it('default tab should be metrics', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <JobDetails job={mockJob} isModalTimeSelection onClose={mockOnClose} />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByRole('radio', { name: 'Metrics' });
- expect(metricsTab).toBeChecked();
- });
-
- it('should switch to events tab when events tab is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <JobDetails job={mockJob} isModalTimeSelection onClose={mockOnClose} />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const eventsTab = screen.getByRole('radio', { name: 'Events' });
- expect(eventsTab).not.toBeChecked();
- fireEvent.click(eventsTab);
- expect(eventsTab).toBeChecked();
- });
-
- it('should close modal when close button is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <JobDetails job={mockJob} isModalTimeSelection onClose={mockOnClose} />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const closeButton = screen.getByRole('button', { name: 'Close' });
- fireEvent.click(closeButton);
- expect(mockOnClose).toHaveBeenCalled();
- });
-});
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/K8sHeader.test.tsx b/frontend/src/container/InfraMonitoringK8s/__tests__/K8sHeader.test.tsx
deleted file mode 100644
index 2f82774c0d..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/__tests__/K8sHeader.test.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-import setupCommonMocks from './commonMocks';
-
-setupCommonMocks();
-
-import { QueryClient, QueryClientProvider } from 'react-query';
-// eslint-disable-next-line no-restricted-imports
-import { MemoryRouter } from 'react-router-dom';
-import { render, screen } from '@testing-library/react';
-import K8sHeader from 'container/InfraMonitoringK8s/K8sHeader';
-import { withNuqsTestingAdapter } from 'nuqs/adapters/testing';
-
-import { INFRA_MONITORING_K8S_PARAMS_KEYS, K8sCategory } from '../constants';
-
-const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- },
-});
-
-describe('K8sHeader URL Parameter Parsing', () => {
- const defaultProps = {
- selectedGroupBy: [],
- groupByOptions: [],
- isLoadingGroupByFilters: false,
- handleFiltersChange: jest.fn(),
- handleGroupByChange: jest.fn(),
- defaultAddedColumns: [],
- handleFilterVisibilityChange: jest.fn(),
- isFiltersVisible: true,
- entity: K8sCategory.PODS,
- showAutoRefresh: true,
- };
-
- const renderComponent = (
- searchParams?: string | Record<string, string>,
- ): ReturnType<typeof render> => {
- const Wrapper = withNuqsTestingAdapter({ searchParams: searchParams ?? {} });
- return render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <MemoryRouter>
- <K8sHeader {...defaultProps} />
- </MemoryRouter>
- </QueryClientProvider>
- </Wrapper>,
- );
- };
-
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('should render without crashing when no URL params', () => {
- expect(() => renderComponent()).not.toThrow();
- expect(screen.getByText('Group by')).toBeInTheDocument();
- });
-
- it('should render without crashing with valid filters in URL', () => {
- const filters = {
- items: [
- {
- id: '1',
- key: { key: 'k8s_namespace_name' },
- op: '=',
- value: 'kube-system',
- },
- ],
- op: 'AND',
- };
-
- expect(() =>
- renderComponent({
- [INFRA_MONITORING_K8S_PARAMS_KEYS.FILTERS]: JSON.stringify(filters),
- }),
- ).not.toThrow();
- });
-
- it('should render without crashing with malformed filters JSON', () => {
- const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
-
- expect(() =>
- renderComponent({
- [INFRA_MONITORING_K8S_PARAMS_KEYS.FILTERS]: 'invalid-json',
- }),
- ).not.toThrow();
-
- consoleSpy.mockRestore();
- });
-
- it('should handle filters with K8s container image values', () => {
- const filters = {
- items: [
- {
- id: '1',
- key: { key: 'k8s_container_image' },
- op: '=',
- value: 'registry.k8s.io/coredns/coredns:v1.10.1',
- },
- ],
- op: 'AND',
- };
-
- expect(() =>
- renderComponent({
- [INFRA_MONITORING_K8S_PARAMS_KEYS.FILTERS]: JSON.stringify(filters),
- }),
- ).not.toThrow();
- });
-
- it('should handle filters with percent signs in values', () => {
- const filters = {
- items: [
- {
- id: '1',
- key: { key: 'k8s_label' },
- op: '=',
- value: 'cpu-usage-50%',
- },
- ],
- op: 'AND',
- };
-
- expect(() =>
- renderComponent({
- [INFRA_MONITORING_K8S_PARAMS_KEYS.FILTERS]: JSON.stringify(filters),
- }),
- ).not.toThrow();
- });
-});
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/Namespaces/NamespaceDetails/NamespaceDetails.test.tsx b/frontend/src/container/InfraMonitoringK8s/__tests__/Namespaces/NamespaceDetails/NamespaceDetails.test.tsx
deleted file mode 100644
index b6c8a71ee6..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/__tests__/Namespaces/NamespaceDetails/NamespaceDetails.test.tsx
+++ /dev/null
@@ -1,148 +0,0 @@
-import setupCommonMocks from '../../commonMocks';
-
-setupCommonMocks();
-
-import { QueryClient, QueryClientProvider } from 'react-query';
-// eslint-disable-next-line no-restricted-imports
-import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
-import { fireEvent, render, screen } from '@testing-library/react';
-import NamespaceDetails from 'container/InfraMonitoringK8s/Namespaces/NamespaceDetails/NamespaceDetails';
-import { withNuqsTestingAdapter } from 'nuqs/adapters/testing';
-import store from 'store';
-
-const queryClient = new QueryClient();
-
-const Wrapper = withNuqsTestingAdapter({ searchParams: {} });
-
-describe('NamespaceDetails', () => {
- const mockNamespace = {
- namespaceName: 'test-namespace',
- meta: {
- k8s_cluster_name: 'test-cluster',
- },
- } as any;
- const mockOnClose = jest.fn();
-
- it('should render modal with relevant metadata', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <NamespaceDetails
- namespace={mockNamespace}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const namespaceNameElements = screen.getAllByText('test-namespace');
- expect(namespaceNameElements.length).toBeGreaterThan(0);
- expect(namespaceNameElements[0]).toBeInTheDocument();
-
- const clusterNameElements = screen.getAllByText('test-cluster');
- expect(clusterNameElements.length).toBeGreaterThan(0);
- expect(clusterNameElements[0]).toBeInTheDocument();
- });
-
- it('should render modal with 4 tabs', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <NamespaceDetails
- namespace={mockNamespace}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByText('Metrics');
- expect(metricsTab).toBeInTheDocument();
-
- const eventsTab = screen.getByText('Events');
- expect(eventsTab).toBeInTheDocument();
-
- const logsTab = screen.getByText('Logs');
- expect(logsTab).toBeInTheDocument();
-
- const tracesTab = screen.getByText('Traces');
- expect(tracesTab).toBeInTheDocument();
- });
-
- it('default tab should be metrics', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <NamespaceDetails
- namespace={mockNamespace}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByRole('radio', { name: 'Metrics' });
- expect(metricsTab).toBeChecked();
- });
-
- it('should switch to events tab when events tab is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <NamespaceDetails
- namespace={mockNamespace}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const eventsTab = screen.getByRole('radio', { name: 'Events' });
- expect(eventsTab).not.toBeChecked();
- fireEvent.click(eventsTab);
- expect(eventsTab).toBeChecked();
- });
-
- it('should close modal when close button is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <NamespaceDetails
- namespace={mockNamespace}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const closeButton = screen.getByRole('button', { name: 'Close' });
- fireEvent.click(closeButton);
- expect(mockOnClose).toHaveBeenCalled();
- });
-});
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/Nodes/NodeDetails/NodeDetails.test.tsx b/frontend/src/container/InfraMonitoringK8s/__tests__/Nodes/NodeDetails/NodeDetails.test.tsx
deleted file mode 100644
index f50444e934..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/__tests__/Nodes/NodeDetails/NodeDetails.test.tsx
+++ /dev/null
@@ -1,148 +0,0 @@
-import setupCommonMocks from '../../commonMocks';
-
-setupCommonMocks();
-
-import { QueryClient, QueryClientProvider } from 'react-query';
-// eslint-disable-next-line no-restricted-imports
-import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
-import { fireEvent, render, screen } from '@testing-library/react';
-import NodeDetails from 'container/InfraMonitoringK8s/Nodes/NodeDetails/NodeDetails';
-import { withNuqsTestingAdapter } from 'nuqs/adapters/testing';
-import store from 'store';
-
-const queryClient = new QueryClient();
-
-const Wrapper = withNuqsTestingAdapter({ searchParams: {} });
-
-describe('NodeDetails', () => {
- const mockNode = {
- meta: {
- k8s_node_name: 'test-node',
- k8s_cluster_name: 'test-cluster',
- },
- } as any;
- const mockOnClose = jest.fn();
-
- it('should render modal with relevant metadata', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <NodeDetails
- node={mockNode}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const nodeNameElements = screen.getAllByText('test-node');
- expect(nodeNameElements.length).toBeGreaterThan(0);
- expect(nodeNameElements[0]).toBeInTheDocument();
-
- const clusterNameElements = screen.getAllByText('test-cluster');
- expect(clusterNameElements.length).toBeGreaterThan(0);
- expect(clusterNameElements[0]).toBeInTheDocument();
- });
-
- it('should render modal with 4 tabs', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <NodeDetails
- node={mockNode}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByText('Metrics');
- expect(metricsTab).toBeInTheDocument();
-
- const eventsTab = screen.getByText('Events');
- expect(eventsTab).toBeInTheDocument();
-
- const logsTab = screen.getByText('Logs');
- expect(logsTab).toBeInTheDocument();
-
- const tracesTab = screen.getByText('Traces');
- expect(tracesTab).toBeInTheDocument();
- });
-
- it('default tab should be metrics', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <NodeDetails
- node={mockNode}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByRole('radio', { name: 'Metrics' });
- expect(metricsTab).toBeChecked();
- });
-
- it('should switch to events tab when events tab is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <NodeDetails
- node={mockNode}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const eventsTab = screen.getByRole('radio', { name: 'Events' });
- expect(eventsTab).not.toBeChecked();
- fireEvent.click(eventsTab);
- expect(eventsTab).toBeChecked();
- });
-
- it('should close modal when close button is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <NodeDetails
- node={mockNode}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const closeButton = screen.getByRole('button', { name: 'Close' });
- fireEvent.click(closeButton);
- expect(mockOnClose).toHaveBeenCalled();
- });
-});
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/Pods/K8sPodsList.test.tsx b/frontend/src/container/InfraMonitoringK8s/__tests__/Pods/K8sPodsList.test.tsx
deleted file mode 100644
index 328d1fa5c7..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/__tests__/Pods/K8sPodsList.test.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-/**
- * Tests for URL parameter parsing in K8s Infra Monitoring components.
- *
- * These tests verify the fix for the double URL decoding bug where
- * components were calling decodeURIComponent() on values already
- * decoded by URLSearchParams.get(), causing crashes on K8s parameters
- * with special characters.
- */
-
-import { getFiltersFromParams } from '../../commonUtils';
-
-describe('K8sPodsList URL Parameter Parsing', () => {
- describe('getFiltersFromParams', () => {
- it('should return null when no filters in params', () => {
- const searchParams = new URLSearchParams();
- const result = getFiltersFromParams(searchParams, 'filters');
- expect(result).toBeNull();
- });
-
- it('should parse filters from URL params', () => {
- const filters = {
- items: [
- {
- id: '1',
- key: { key: 'k8s_namespace_name' },
- op: '=',
- value: 'default',
- },
- ],
- op: 'AND',
- };
- const searchParams = new URLSearchParams();
- searchParams.set('filters', JSON.stringify(filters));
-
- const result = getFiltersFromParams(searchParams, 'filters');
- expect(result).toEqual(filters);
- });
-
- it('should handle URL-encoded filters (auto-decoded by URLSearchParams)', () => {
- const filters = {
- items: [
- {
- id: '1',
- key: { key: 'k8s_pod_name' },
- op: 'contains',
- value: 'api-server',
- },
- ],
- op: 'AND',
- };
- const encodedValue = encodeURIComponent(JSON.stringify(filters));
- const searchParams = new URLSearchParams(`filters=${encodedValue}`);
-
- const result = getFiltersFromParams(searchParams, 'filters');
- expect(result).toEqual(filters);
- });
-
- it('should return null on malformed JSON instead of crashing', () => {
- const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
- const searchParams = new URLSearchParams();
- searchParams.set('filters', '{invalid-json}');
-
- const result = getFiltersFromParams(searchParams, 'filters');
- expect(result).toBeNull();
- consoleSpy.mockRestore();
- });
-
- it('should handle filters with K8s container image names', () => {
- const filters = {
- items: [
- {
- id: '1',
- key: { key: 'k8s_container_name' },
- op: '=',
- value: 'registry.k8s.io/coredns/coredns:v1.10.1',
- },
- ],
- op: 'AND',
- };
- const encodedValue = encodeURIComponent(JSON.stringify(filters));
- const searchParams = new URLSearchParams(`filters=${encodedValue}`);
-
- const result = getFiltersFromParams(searchParams, 'filters');
- expect(result).toEqual(filters);
- });
- });
-
- describe('regression: double decoding issue', () => {
- it('should not crash when URL params are already decoded by URLSearchParams', () => {
- // The key bug: URLSearchParams.get() auto-decodes, so encoding once in URL
- // means .get() returns decoded value. Old code called decodeURIComponent()
- // again which could crash on certain characters.
-
- const filters = {
- items: [
- {
- id: '1',
- key: { key: 'k8s_namespace_name' },
- op: '=',
- value: 'kube-system',
- },
- ],
- op: 'AND',
- };
-
- const encodedValue = encodeURIComponent(JSON.stringify(filters));
- const searchParams = new URLSearchParams(`filters=${encodedValue}`);
-
- // This should work without crashing
- const result = getFiltersFromParams(searchParams, 'filters');
- expect(result).toEqual(filters);
- });
-
- it('should handle values with percent signs in labels', () => {
- // K8s labels might contain literal "%" characters like "cpu-usage-50%"
- const filters = {
- items: [
- {
- id: '1',
- key: { key: 'k8s_label' },
- op: '=',
- value: 'cpu-50%',
- },
- ],
- op: 'AND',
- };
-
- const encodedValue = encodeURIComponent(JSON.stringify(filters));
- const searchParams = new URLSearchParams(`filters=${encodedValue}`);
-
- const result = getFiltersFromParams(searchParams, 'filters');
- expect(result).toEqual(filters);
- });
-
- it('should handle complex K8s deployment names with special chars', () => {
- const filters = {
- items: [
- {
- id: '1',
- key: { key: 'k8s_deployment_name' },
- op: '=',
- value: 'nginx-ingress-controller',
- },
- ],
- op: 'AND',
- };
-
- const encodedValue = encodeURIComponent(JSON.stringify(filters));
- const searchParams = new URLSearchParams(`filters=${encodedValue}`);
-
- const result = getFiltersFromParams(searchParams, 'filters');
- expect(result).toEqual(filters);
- });
- });
-});
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/Pods/PodDetails/PodDetails.test.tsx b/frontend/src/container/InfraMonitoringK8s/__tests__/Pods/PodDetails/PodDetails.test.tsx
deleted file mode 100644
index 90f8536087..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/__tests__/Pods/PodDetails/PodDetails.test.tsx
+++ /dev/null
@@ -1,134 +0,0 @@
-import setupCommonMocks from '../../commonMocks';
-
-setupCommonMocks();
-
-import { QueryClient, QueryClientProvider } from 'react-query';
-// eslint-disable-next-line no-restricted-imports
-import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
-import { fireEvent, render, screen } from '@testing-library/react';
-import PodDetails from 'container/InfraMonitoringK8s/Pods/PodDetails/PodDetails';
-import { withNuqsTestingAdapter } from 'nuqs/adapters/testing';
-import store from 'store';
-
-const queryClient = new QueryClient();
-
-const Wrapper = withNuqsTestingAdapter({ searchParams: {} });
-
-describe('PodDetails', () => {
- const mockPod = {
- podName: 'test-pod',
- meta: {
- k8s_cluster_name: 'test-cluster',
- k8s_namespace_name: 'test-namespace',
- k8s_node_name: 'test-node',
- },
- } as any;
- const mockOnClose = jest.fn();
-
- it('should render modal with relevant metadata', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <PodDetails pod={mockPod} isModalTimeSelection onClose={mockOnClose} />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const clusterNameElements = screen.getAllByText('test-cluster');
- expect(clusterNameElements.length).toBeGreaterThan(0);
- expect(clusterNameElements[0]).toBeInTheDocument();
-
- const namespaceNameElements = screen.getAllByText('test-namespace');
- expect(namespaceNameElements.length).toBeGreaterThan(0);
- expect(namespaceNameElements[0]).toBeInTheDocument();
-
- const nodeNameElements = screen.getAllByText('test-node');
- expect(nodeNameElements.length).toBeGreaterThan(0);
- expect(nodeNameElements[0]).toBeInTheDocument();
- });
-
- it('should render modal with 4 tabs', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <PodDetails pod={mockPod} isModalTimeSelection onClose={mockOnClose} />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByText('Metrics');
- expect(metricsTab).toBeInTheDocument();
-
- const eventsTab = screen.getByText('Events');
- expect(eventsTab).toBeInTheDocument();
-
- const logsTab = screen.getByText('Logs');
- expect(logsTab).toBeInTheDocument();
-
- const tracesTab = screen.getByText('Traces');
- expect(tracesTab).toBeInTheDocument();
- });
-
- it('default tab should be metrics', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <PodDetails pod={mockPod} isModalTimeSelection onClose={mockOnClose} />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByRole('radio', { name: 'Metrics' });
- expect(metricsTab).toBeChecked();
- });
-
- it('should switch to events tab when events tab is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <PodDetails pod={mockPod} isModalTimeSelection onClose={mockOnClose} />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const eventsTab = screen.getByRole('radio', { name: 'Events' });
- expect(eventsTab).not.toBeChecked();
- fireEvent.click(eventsTab);
- expect(eventsTab).toBeChecked();
- });
-
- it('should close modal when close button is clicked', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <PodDetails pod={mockPod} isModalTimeSelection onClose={mockOnClose} />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const closeButton = screen.getByRole('button', { name: 'Close' });
- fireEvent.click(closeButton);
- expect(mockOnClose).toHaveBeenCalled();
- });
-});
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/StatefulSets/StatefulSetDetails/StatefulSetDetails.test.tsx b/frontend/src/container/InfraMonitoringK8s/__tests__/StatefulSets/StatefulSetDetails/StatefulSetDetails.test.tsx
deleted file mode 100644
index 85139c7d22..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/__tests__/StatefulSets/StatefulSetDetails/StatefulSetDetails.test.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import setupCommonMocks from '../../commonMocks';
-
-setupCommonMocks();
-
-import { QueryClient, QueryClientProvider } from 'react-query';
-// eslint-disable-next-line no-restricted-imports
-import { MemoryRouter } from 'react-router-dom';
-import { render, screen } from '@testing-library/react';
-import StatefulSetDetails from 'container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/StatefulSetDetails';
-import { withNuqsTestingAdapter } from 'nuqs/adapters/testing';
-import { userEvent } from 'tests/test-utils';
-
-const queryClient = new QueryClient();
-
-const Wrapper = withNuqsTestingAdapter({ searchParams: {} });
-
-describe('StatefulSetDetails', () => {
- const mockStatefulSet = {
- meta: {
- k8s_namespace_name: 'test-namespace',
- k8s_statefulset_name: 'test-stateful-set',
- },
- } as any;
- const mockOnClose = jest.fn();
-
- it('should render modal with relevant metadata', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <MemoryRouter>
- <StatefulSetDetails
- statefulSet={mockStatefulSet}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const statefulSetNameElements = screen.getAllByText('test-stateful-set');
- expect(statefulSetNameElements.length).toBeGreaterThan(0);
- expect(statefulSetNameElements[0]).toBeInTheDocument();
-
- const namespaceNameElements = screen.getAllByText('test-namespace');
- expect(namespaceNameElements.length).toBeGreaterThan(0);
- expect(namespaceNameElements[0]).toBeInTheDocument();
- });
-
- it('should render modal with 4 tabs', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <MemoryRouter>
- <StatefulSetDetails
- statefulSet={mockStatefulSet}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByText('Metrics');
- expect(metricsTab).toBeInTheDocument();
-
- const eventsTab = screen.getByText('Events');
- expect(eventsTab).toBeInTheDocument();
-
- const logsTab = screen.getByText('Logs');
- expect(logsTab).toBeInTheDocument();
-
- const tracesTab = screen.getByText('Traces');
- expect(tracesTab).toBeInTheDocument();
- });
-
- it('default tab should be metrics', () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <MemoryRouter>
- <StatefulSetDetails
- statefulSet={mockStatefulSet}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const metricsTab = screen.getByRole('radio', { name: 'Metrics' });
- expect(metricsTab).toBeChecked();
- });
-
- it('should switch to events tab when events tab is clicked', async () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <MemoryRouter>
- <StatefulSetDetails
- statefulSet={mockStatefulSet}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const eventsTab = screen.getByRole('radio', { name: 'Events' });
- expect(eventsTab).not.toBeChecked();
- await userEvent.click(eventsTab, { pointerEventsCheck: 0 });
- expect(eventsTab).toBeChecked();
- });
-
- it('should close modal when close button is clicked', async () => {
- render(
- <Wrapper>
- <QueryClientProvider client={queryClient}>
- <MemoryRouter>
- <StatefulSetDetails
- statefulSet={mockStatefulSet}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </QueryClientProvider>
- </Wrapper>,
- );
-
- const closeButton = screen.getByRole('button', { name: 'Close' });
- await userEvent.click(closeButton);
- expect(mockOnClose).toHaveBeenCalled();
- });
-});
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/Volumes/K8sVolumesList.test.tsx b/frontend/src/container/InfraMonitoringK8s/__tests__/Volumes/K8sVolumesList.test.tsx
deleted file mode 100644
index 228da1ac6a..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/__tests__/Volumes/K8sVolumesList.test.tsx
+++ /dev/null
@@ -1,390 +0,0 @@
-import { QueryClient, QueryClientProvider } from 'react-query';
-// eslint-disable-next-line no-restricted-imports
-import { MemoryRouter } from 'react-router-dom-v5-compat';
-import { FeatureKeys } from 'constants/features';
-import K8sVolumesList from 'container/InfraMonitoringK8s/Volumes/K8sVolumesList';
-import { rest, server } from 'mocks-server/server';
-import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
-import { IAppContext, IUser } from 'providers/App/types';
-import { QueryBuilderProvider } from 'providers/QueryBuilder';
-// eslint-disable-next-line no-restricted-imports
-import { applyMiddleware, legacy_createStore as createStore } from 'redux';
-import thunk from 'redux-thunk';
-import reducers from 'store/reducers';
-import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
-import { UPDATE_TIME_INTERVAL } from 'types/actions/globalTime';
-import { LicenseResModel } from 'types/api/licensesV3/getActive';
-
-import { INFRA_MONITORING_K8S_PARAMS_KEYS } from '../../constants';
-
-const SERVER_URL = 'http://localhost/api';
-
-// jsdom does not implement IntersectionObserver — provide a no-op stub
-const mockObserver = {
- observe: jest.fn(),
- unobserve: jest.fn(),
- disconnect: jest.fn(),
-};
-global.IntersectionObserver = jest
- .fn()
- .mockImplementation(() => mockObserver) as any;
-
-const mockVolume = {
- persistentVolumeClaimName: 'test-pvc',
- volumeAvailable: 1000000,
- volumeCapacity: 5000000,
- volumeInodes: 100,
- volumeInodesFree: 50,
- volumeInodesUsed: 50,
- volumeUsage: 4000000,
- meta: {
- k8s_cluster_name: 'test-cluster',
- k8s_namespace_name: 'test-namespace',
- k8s_node_name: 'test-node',
- k8s_persistentvolumeclaim_name: 'test-pvc',
- k8s_pod_name: 'test-pod',
- k8s_pod_uid: 'test-pod-uid',
- k8s_statefulset_name: '',
- },
-};
-
-const mockVolumesResponse = {
- status: 'success',
- data: {
- type: '',
- records: [mockVolume],
- groups: null,
- total: 1,
- sentAnyHostMetricsData: false,
- isSendingK8SAgentMetrics: false,
- },
-};
-
-/** Renders K8sVolumesList with a real Redux store so dispatched actions affect state. */
-function renderWithRealStore(
- initialEntries?: Record<string, any>,
-): { testStore: ReturnType<typeof createStore> } {
- const testStore = createStore(reducers, applyMiddleware(thunk as any));
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- });
-
- render(
- <NuqsTestingAdapter searchParams={initialEntries}>
- <QueryClientProvider client={queryClient}>
- <QueryBuilderProvider>
- <MemoryRouter>
- <K8sVolumesList
- isFiltersVisible={false}
- handleFilterVisibilityChange={jest.fn()}
- quickFiltersLastUpdated={-1}
- />
- </MemoryRouter>
- </QueryBuilderProvider>
- </QueryClientProvider>
- </NuqsTestingAdapter>,
- );
-
- return { testStore };
-}
-
-describe('K8sVolumesList - useGetAggregateKeys Category Regression', () => {
- let requestsMade: Array<{
- url: string;
- params: URLSearchParams;
- body?: any;
- }> = [];
-
- beforeEach(() => {
- requestsMade = [];
-
- server.use(
- rest.get(`${SERVER_URL}/v3/autocomplete/attribute_keys`, (req, res, ctx) => {
- const url = req.url.toString();
- const params = req.url.searchParams;
-
- requestsMade.push({
- url,
- params,
- });
-
- return res(
- ctx.status(200),
- ctx.json({
- status: 'success',
- data: {
- attributeKeys: [],
- },
- }),
- );
- }),
- rest.post(`${SERVER_URL}/v1/pvcs/list`, (req, res, ctx) =>
- res(
- ctx.status(200),
- ctx.json({
- status: 'success',
- data: {
- type: 'list',
- records: [],
- groups: null,
- total: 0,
- sentAnyHostMetricsData: false,
- isSendingK8SAgentMetrics: false,
- },
- }),
- ),
- ),
- );
- });
-
- afterEach(() => {
- server.resetHandlers();
- });
-
- it('should call aggregate keys API with k8s_volume_capacity', async () => {
- renderWithRealStore();
-
- await waitFor(() => {
- expect(requestsMade.length).toBeGreaterThan(0);
- });
-
- // Find the attribute_keys request
- const attributeKeysRequest = requestsMade.find((req) =>
- req.url.includes('/autocomplete/attribute_keys'),
- );
-
- expect(attributeKeysRequest).toBeDefined();
-
- const aggregateAttribute = attributeKeysRequest?.params.get(
- 'aggregateAttribute',
- );
-
- expect(aggregateAttribute).toBe('k8s_volume_capacity');
- });
-
- it('should call aggregate keys API with k8s.volume.capacity when dotMetrics enabled', async () => {
- jest
- .spyOn(await import('providers/App/App'), 'useAppContext')
- .mockReturnValue({
- featureFlags: [
- {
- name: FeatureKeys.DOT_METRICS_ENABLED,
- active: true,
- usage: 0,
- usage_limit: 0,
- route: '',
- },
- ],
- user: { role: 'ADMIN' } as IUser,
- activeLicense: (null as unknown) as LicenseResModel,
- } as IAppContext);
-
- renderWithRealStore();
-
- await waitFor(() => {
- expect(requestsMade.length).toBeGreaterThan(0);
- });
-
- const attributeKeysRequest = requestsMade.find((req) =>
- req.url.includes('/autocomplete/attribute_keys'),
- );
-
- expect(attributeKeysRequest).toBeDefined();
-
- const aggregateAttribute = attributeKeysRequest?.params.get(
- 'aggregateAttribute',
- );
-
- expect(aggregateAttribute).toBe('k8s.volume.capacity');
- });
-});
-
-describe('K8sVolumesList', () => {
- beforeEach(() => {
- server.use(
- rest.post('http://localhost/api/v1/pvcs/list', (_req, res, ctx) =>
- res(ctx.status(200), ctx.json(mockVolumesResponse)),
- ),
- rest.get(
- 'http://localhost/api/v3/autocomplete/attribute_keys',
- (_req, res, ctx) =>
- res(ctx.status(200), ctx.json({ data: { attributeKeys: [] } })),
- ),
- );
- });
-
- it('renders volume rows from API response', async () => {
- renderWithRealStore();
-
- await waitFor(async () => {
- const elements = await screen.findAllByText('test-pvc');
-
- expect(elements.length).toBeGreaterThan(0);
- });
- });
-
- it('opens VolumeDetails when a volume row is clicked', async () => {
- const user = userEvent.setup();
- renderWithRealStore();
-
- const pvcCells = await screen.findAllByText('test-pvc');
- expect(pvcCells.length).toBeGreaterThan(0);
-
- const row = pvcCells[0].closest('tr');
- expect(row).not.toBeNull();
- await user.click(row!);
-
- await waitFor(async () => {
- const cells = await screen.findAllByText('test-pvc');
- expect(cells.length).toBeGreaterThan(1);
- });
- });
-
- it.skip('closes VolumeDetails when the close button is clicked', async () => {
- const user = userEvent.setup();
- renderWithRealStore();
-
- const pvcCells = await screen.findAllByText('test-pvc');
- expect(pvcCells.length).toBeGreaterThan(0);
-
- const row = pvcCells[0].closest('tr');
- await user.click(row!);
-
- await waitFor(() => {
- expect(screen.getByRole('button', { name: 'Close' })).toBeInTheDocument();
- });
-
- await user.click(screen.getByRole('button', { name: 'Close' }));
-
- await waitFor(() => {
- expect(
- screen.queryByRole('button', { name: 'Close' }),
- ).not.toBeInTheDocument();
- });
- });
-
- it('does not re-fetch the volumes list when time range changes after selecting a volume', async () => {
- const user = userEvent.setup();
- let apiCallCount = 0;
- server.use(
- rest.post('http://localhost/api/v1/pvcs/list', async (_req, res, ctx) => {
- apiCallCount += 1;
- return res(ctx.status(200), ctx.json(mockVolumesResponse));
- }),
- );
-
- const { testStore } = renderWithRealStore();
-
- await waitFor(() => expect(apiCallCount).toBe(1));
-
- const pvcCells = await screen.findAllByText('test-pvc');
- const row = pvcCells[0].closest('tr');
- await user.click(row!);
- await waitFor(async () => {
- const cells = await screen.findAllByText('test-pvc');
- expect(cells.length).toBeGreaterThan(1);
- });
-
- // Wait for nuqs URL state to fully propagate to the component
- // The selectedVolumeUID is managed via nuqs (async URL state),
- // so we need to ensure the state has settled before dispatching time changes
- await act(async () => {
- await new Promise((resolve) => {
- setTimeout(resolve, 0);
- });
- });
-
- const countAfterClick = apiCallCount;
-
- // There's a specific component causing the min/max time to be updated
- // After the volume loads, it triggers the change again
- // And then the query to fetch data for the selected volume enters in a loop
- act(() => {
- testStore.dispatch({
- type: UPDATE_TIME_INTERVAL,
- payload: {
- minTime: Date.now() * 1000000 - 30 * 60 * 1000 * 1000000,
- maxTime: Date.now() * 1000000,
- selectedTime: '30m',
- },
- } as any);
- });
-
- // Allow any potential re-fetch to settle
- await new Promise((resolve) => {
- setTimeout(resolve, 500);
- });
-
- expect(apiCallCount).toBe(countAfterClick);
- });
-
- it('does not re-fetch groupedByRowData when time range changes after expanding a volume row with groupBy', async () => {
- const user = userEvent.setup();
- const groupByValue = [{ key: 'k8s_namespace_name' }];
-
- let groupedByRowDataCallCount = 0;
- server.use(
- rest.post('http://localhost/api/v1/pvcs/list', async (req, res, ctx) => {
- const body = await req.json();
- // Check for both underscore and dot notation keys since dotMetricsEnabled
- // may be true or false depending on test order
- const isGroupedByRowDataRequest = body.filters?.items?.some(
- (item: { key?: { key?: string }; value?: string }) =>
- (item.key?.key === 'k8s_namespace_name' ||
- item.key?.key === 'k8s.namespace.name') &&
- item.value === 'test-namespace',
- );
- if (isGroupedByRowDataRequest) {
- groupedByRowDataCallCount += 1;
- }
- return res(ctx.status(200), ctx.json(mockVolumesResponse));
- }),
- rest.get(
- 'http://localhost/api/v3/autocomplete/attribute_keys',
- (_req, res, ctx) =>
- res(
- ctx.status(200),
- ctx.json({
- data: {
- attributeKeys: [{ key: 'k8s_namespace_name', dataType: 'string' }],
- },
- }),
- ),
- ),
- );
-
- const { testStore } = renderWithRealStore({
- [INFRA_MONITORING_K8S_PARAMS_KEYS.GROUP_BY]: JSON.stringify(groupByValue),
- });
-
- await waitFor(async () => {
- const elements = await screen.findAllByText('test-namespace');
- return expect(elements.length).toBeGreaterThan(0);
- });
-
- const row = (await screen.findAllByText('test-namespace'))[0].closest('tr');
- expect(row).not.toBeNull();
- user.click(row as HTMLElement);
- await waitFor(() => expect(groupedByRowDataCallCount).toBe(1));
-
- const countAfterExpand = groupedByRowDataCallCount;
-
- act(() => {
- testStore.dispatch({
- type: UPDATE_TIME_INTERVAL,
- payload: {
- minTime: Date.now() * 1000000 - 30 * 60 * 1000 * 1000000,
- maxTime: Date.now() * 1000000,
- selectedTime: '30m',
- },
- } as any);
- });
-
- // Allow any potential re-fetch to settle
- await new Promise((resolve) => {
- setTimeout(resolve, 500);
- });
-
- expect(groupedByRowDataCallCount).toBe(countAfterExpand);
- });
-});
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/Volumes/VolumeDetails/VolumeDetails.test.tsx b/frontend/src/container/InfraMonitoringK8s/__tests__/Volumes/VolumeDetails/VolumeDetails.test.tsx
deleted file mode 100644
index 0c3995ae56..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/__tests__/Volumes/VolumeDetails/VolumeDetails.test.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import setupCommonMocks from '../../commonMocks';
-
-setupCommonMocks();
-
-import { QueryClient, QueryClientProvider } from 'react-query';
-// eslint-disable-next-line no-restricted-imports
-import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
-import { fireEvent, render, screen } from '@testing-library/react';
-import VolumeDetails from 'container/InfraMonitoringK8s/Volumes/VolumeDetails/VolumeDetails';
-import store from 'store';
-
-const queryClient = new QueryClient();
-
-describe('VolumeDetails', () => {
- const mockVolume = {
- persistentVolumeClaimName: 'test-volume',
- meta: {
- k8s_cluster_name: 'test-cluster',
- k8s_namespace_name: 'test-namespace',
- },
- } as any;
- const mockOnClose = jest.fn();
-
- it('should render modal with relevant metadata', () => {
- render(
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <VolumeDetails
- volume={mockVolume}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>,
- );
-
- const volumeNameElements = screen.getAllByText('test-volume');
- expect(volumeNameElements.length).toBeGreaterThan(0);
- expect(volumeNameElements[0]).toBeInTheDocument();
-
- const clusterNameElements = screen.getAllByText('test-cluster');
- expect(clusterNameElements.length).toBeGreaterThan(0);
- expect(clusterNameElements[0]).toBeInTheDocument();
-
- const namespaceNameElements = screen.getAllByText('test-namespace');
- expect(namespaceNameElements.length).toBeGreaterThan(0);
- expect(namespaceNameElements[0]).toBeInTheDocument();
- });
-
- it('should close modal when close button is clicked', () => {
- render(
- <QueryClientProvider client={queryClient}>
- <Provider store={store}>
- <MemoryRouter>
- <VolumeDetails
- volume={mockVolume}
- isModalTimeSelection
- onClose={mockOnClose}
- />
- </MemoryRouter>
- </Provider>
- </QueryClientProvider>,
- );
-
- const closeButton = screen.getByRole('button', { name: 'Close' });
- fireEvent.click(closeButton);
- expect(mockOnClose).toHaveBeenCalled();
- });
-});
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/commonMocks.ts b/frontend/src/container/InfraMonitoringK8s/__tests__/commonMocks.ts
deleted file mode 100644
index 8216e5ca68..0000000000
--- a/frontend/src/container/InfraMonitoringK8s/__tests__/commonMocks.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import { createElement } from 'react';
-import * as appContextHooks from 'providers/App/App';
-import * as timezoneHooks from 'providers/Timezone';
-import { LicenseEvent } from 'types/api/licensesV3/getActive';
-
-const setupCommonMocks = (): void => {
- const createMockObserver = (): {
- observe: jest.Mock;
- unobserve: jest.Mock;
- disconnect: jest.Mock;
- } => ({
- observe: jest.fn(),
- unobserve: jest.fn(),
- disconnect: jest.fn(),
- });
-
- global.IntersectionObserver = jest.fn().mockImplementation(createMockObserver);
- global.ResizeObserver = jest.fn().mockImplementation(createMockObserver);
-
- jest.mock('react-redux', () => ({
- ...jest.requireActual('react-redux'),
- useSelector: jest.fn(() => ({
- globalTime: {
- selectedTime: {
- startTime: 1713734400000,
- endTime: 1713738000000,
- },
- maxTime: 1713738000000,
- minTime: 1713734400000,
- },
- })),
- }));
-
- jest.mock('uplot', () => ({
- paths: {
- spline: jest.fn(),
- bars: jest.fn(),
- },
- default: jest.fn(() => ({
- paths: {
- spline: jest.fn(),
- bars: jest.fn(),
- },
- })),
- }));
-
- jest.mock('react-router-dom-v5-compat', () => ({
- ...jest.requireActual('react-router-dom-v5-compat'),
- useNavigationType: (): any => 'PUSH',
- }));
-
- jest.mock('lib/getMinMax', () => ({
- __esModule: true,
- default: jest.fn().mockImplementation(() => ({
- minTime: 1713734400000,
- maxTime: 1713738000000,
- })),
- isValidShortHandDateTimeFormat: jest.fn().mockReturnValue(true),
- }));
-
- jest.spyOn(appContextHooks, 'useAppContext').mockReturnValue({
- user: {
- role: 'admin',
- },
- activeLicenseV3: {
- event_queue: {
- created_at: '0',
- event: LicenseEvent.NO_EVENT,
- scheduled_at: '0',
- status: '',
- updated_at: '0',
- },
- license: {
- license_key: 'test-license-key',
- license_type: 'trial',
- org_id: 'test-org-id',
- plan_id: 'test-plan-id',
- plan_name: 'test-plan-name',
- plan_type: 'trial',
- plan_version: 'test-plan-version',
- },
- },
- } as any);
-
- jest.spyOn(timezoneHooks, 'useTimezone').mockReturnValue({
- timezone: {
- offset: 0,
- },
- browserTimezone: {
- offset: 0,
- },
- } as any);
-
- jest.mock('hooks/useSafeNavigate', () => ({
- useSafeNavigate: (): any => ({
- safeNavigate: jest.fn(),
- }),
- }));
-
- // TODO: Remove this when https://github.com/SigNoz/engineering-pod/issues/4253
- jest.mock('container/TopNav/DateTimeSelectionV2', () => {
- return {
- __esModule: true,
- default: (): React.ReactElement =>
- createElement('div', { 'data-testid': 'datetime-selection' }),
- };
- });
-};
-
-export default setupCommonMocks;
diff --git a/frontend/src/container/InfraMonitoringK8s/__tests__/commonUtils.test.tsx b/frontend/src/container/InfraMonitoringK8s/__tests__/commonUtils.test.tsx
new file mode 100644
index 0000000000..036c201ec3
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/__tests__/commonUtils.test.tsx
@@ -0,0 +1,49 @@
+import { render, screen } from '@testing-library/react';
+
+import { EntityProgressBar, EventContents } from '../commonUtils';
+
+jest.mock('../commonUtils.module.scss', () => ({
+ __esModule: true,
+ default: {
+ entityProgressBar: 'entity-progress-bar-module',
+ progressBar: 'progress-bar-module',
+ eventContentContainer: 'event-content-container-module',
+ },
+}));
+
+jest.mock('components/ResizeTable', () => ({
+ ResizeTable: ({ className, dataSource }: any): JSX.Element => (
+ <div data-testid="resize-table" className={className}>
+ {JSON.stringify(dataSource)}
+ </div>
+ ),
+}));
+
+jest.mock('container/LogDetailedView/FieldRenderer', () => ({
+ __esModule: true,
+ default: ({ field }: { field: string }): JSX.Element => <span>{field}</span>,
+}));
+
+describe('commonUtils', () => {
+ it('renders EntityProgressBar with module classes', () => {
+ const { container } = render(
+ <EntityProgressBar value={0.5} type="request" />,
+ );
+
+ expect(container.firstChild).toHaveClass('entity-progress-bar-module');
+ expect(container.querySelector('.progress-bar-module')).toBeInTheDocument();
+ expect(screen.getByText('50%')).toBeInTheDocument();
+ });
+
+ it('renders EventContents with the module-scoped table class', () => {
+ render(
+ <EventContents data={{ namespace: 'default', cluster: 'prod-cluster' }} />,
+ );
+
+ const resizeTable = screen.getByTestId('resize-table');
+
+ expect(resizeTable).toHaveClass('event-content-container-module');
+ expect(resizeTable).toHaveTextContent('namespace');
+ expect(resizeTable).toHaveTextContent('prod-cluster');
+ });
+});
diff --git a/frontend/src/container/InfraMonitoringK8s/commonUtils.module.scss b/frontend/src/container/InfraMonitoringK8s/commonUtils.module.scss
new file mode 100644
index 0000000000..f5b26b4c0e
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/commonUtils.module.scss
@@ -0,0 +1,91 @@
+.entityProgressBar {
+ display: flex;
+ align-items: center;
+}
+
+.progressBar {
+ flex: 1;
+ margin-right: 8px;
+ margin-bottom: 0;
+ min-width: 100px;
+}
+
+.eventContentContainer {
+ :global(.ant-table) {
+ background: var(--l1-background);
+
+ :global(.ant-table-row:hover) {
+ :global(.ant-table-cell .value-field .action-btn) {
+ display: flex;
+ position: absolute;
+ top: 50%;
+ right: 16px;
+ transform: translateY(-50%);
+ gap: 4px;
+ }
+ }
+
+ :global(.ant-table-cell) {
+ border: 1px solid var(--l2-border);
+ }
+
+ :global(.attribute-name .ant-btn:hover) {
+ background-color: transparent !important;
+ }
+
+ :global(.attribute-pin) {
+ cursor: pointer;
+ padding: 0;
+ vertical-align: middle;
+ text-align: center;
+ }
+
+ :global(.attribute-pin .log-attribute-pin) {
+ padding: 8px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ }
+
+ :global(.attribute-pin .pin-attribute-icon) {
+ border: none;
+ }
+
+ :global(.attribute-pin .pin-attribute-icon.pinned svg) {
+ fill: var(--bg-robin-500);
+ }
+
+ :global(.value-field-container) {
+ background: var(--l3-background);
+ }
+
+ :global(.attribute-pin.value-field-container) {
+ background: var(--l1-background);
+ }
+
+ :global(.value-field-container .value-field) {
+ font-family: 'Geist Mono';
+ position: relative;
+ }
+
+ :global(.value-field-container .action-btn) {
+ display: none;
+ width: max-content;
+ position: absolute;
+ right: 0;
+ }
+
+ :global(.value-field-container .action-btn .filter-btn) {
+ display: flex;
+ align-items: center;
+ border: none;
+ box-shadow: none;
+ border-radius: 2px;
+ background: var(--l3-background);
+ padding: 2px 3px;
+ gap: 3px;
+ height: 18px;
+ width: 20px;
+ }
+ }
+}
diff --git a/frontend/src/container/InfraMonitoringK8s/commonUtils.tsx b/frontend/src/container/InfraMonitoringK8s/commonUtils.tsx
index 1cda94fa05..610db4b321 100644
--- a/frontend/src/container/InfraMonitoringK8s/commonUtils.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/commonUtils.tsx
@@ -12,7 +12,9 @@ import {
TagFilterItem,
} from 'types/api/queryBuilder/queryBuilderData';
-import { getInvalidValueTooltipText, K8sCategory } from './constants';
+import { getInvalidValueTooltipText, InfraMonitoringEntity } from './constants';
+
+import styles from './commonUtils.module.scss';
/**
* Converts size in bytes to a human-readable string with appropriate units
@@ -40,7 +42,7 @@ export function ValidateColumnValueWrapper({
}: {
children: React.ReactNode;
value: number;
- entity?: K8sCategory;
+ entity?: InfraMonitoringEntity;
attribute?: string;
}): JSX.Element {
if (value === -1) {
@@ -101,9 +103,6 @@ export function getStrokeColorForLimitUtilization(value: number): string {
return Color.BG_SAKURA_500;
}
-export const getProgressBarText = (percent: number): React.ReactNode =>
- `${percent}%`;
-
export function EntityProgressBar({
value,
type,
@@ -114,7 +113,7 @@ export function EntityProgressBar({
const percentage = Number((value * 100).toFixed(1));
return (
- <div className="entity-progress-bar">
+ <div className={styles.entityProgressBar}>
<Progress
percent={percentage}
strokeLinecap="butt"
@@ -125,7 +124,7 @@ export function EntityProgressBar({
? getStrokeColorForLimitUtilization(value)
: getStrokeColorForRequestUtilization(value)
}
- className="progress-bar"
+ className={styles.progressBar}
showInfo={false}
/>
<Typography.Text style={{ fontSize: '10px' }}>{percentage}%</Typography.Text>
@@ -173,7 +172,7 @@ export function EventContents({
dataSource={tableData}
pagination={false}
showHeader={false}
- className="event-content-container"
+ className={styles.eventContentContainer}
/>
);
}
diff --git a/frontend/src/container/InfraMonitoringK8s/constants.ts b/frontend/src/container/InfraMonitoringK8s/constants.ts
index 2962c6c726..32de38e856 100644
--- a/frontend/src/container/InfraMonitoringK8s/constants.ts
+++ b/frontend/src/container/InfraMonitoringK8s/constants.ts
@@ -7,7 +7,7 @@ import { DataSource } from 'types/common/queryBuilder';
export const DEFAULT_PAGE_SIZE = 10;
-export enum K8sCategory {
+export enum InfraMonitoringEntity {
HOSTS = 'hosts',
PODS = 'pods',
NODES = 'nodes',
@@ -21,6 +21,24 @@ export enum K8sCategory {
VOLUMES = 'volumes',
}
+export enum VIEWS {
+ METRICS = 'metrics',
+ LOGS = 'logs',
+ TRACES = 'traces',
+ CONTAINERS = 'containers',
+ PROCESSES = 'processes',
+ EVENTS = 'events',
+}
+
+export const VIEW_TYPES = {
+ METRICS: VIEWS.METRICS,
+ LOGS: VIEWS.LOGS,
+ TRACES: VIEWS.TRACES,
+ CONTAINERS: VIEWS.CONTAINERS,
+ PROCESSES: VIEWS.PROCESSES,
+ EVENTS: VIEWS.EVENTS,
+};
+
export const K8sCategories = {
HOSTS: 'hosts',
PODS: 'pods',
@@ -36,35 +54,35 @@ export const K8sCategories = {
};
export const underscoreMap = {
- [K8sCategory.HOSTS]: 'system_cpu_load_average_15m',
- [K8sCategory.PODS]: 'k8s_pod_cpu_usage',
- [K8sCategory.NODES]: 'k8s_node_cpu_usage',
- [K8sCategory.NAMESPACES]: 'k8s_pod_cpu_usage',
- [K8sCategory.CLUSTERS]: 'k8s_node_cpu_usage',
- [K8sCategory.DEPLOYMENTS]: 'k8s_pod_cpu_usage',
- [K8sCategory.STATEFULSETS]: 'k8s_pod_cpu_usage',
- [K8sCategory.DAEMONSETS]: 'k8s_pod_cpu_usage',
- [K8sCategory.CONTAINERS]: 'k8s_pod_cpu_usage',
- [K8sCategory.JOBS]: 'k8s_job_desired_successful_pods',
- [K8sCategory.VOLUMES]: 'k8s_volume_capacity',
+ [InfraMonitoringEntity.HOSTS]: 'system_cpu_load_average_15m',
+ [InfraMonitoringEntity.PODS]: 'k8s_pod_cpu_usage',
+ [InfraMonitoringEntity.NODES]: 'k8s_node_cpu_usage',
+ [InfraMonitoringEntity.NAMESPACES]: 'k8s_pod_cpu_usage',
+ [InfraMonitoringEntity.CLUSTERS]: 'k8s_node_cpu_usage',
+ [InfraMonitoringEntity.DEPLOYMENTS]: 'k8s_pod_cpu_usage',
+ [InfraMonitoringEntity.STATEFULSETS]: 'k8s_pod_cpu_usage',
+ [InfraMonitoringEntity.DAEMONSETS]: 'k8s_pod_cpu_usage',
+ [InfraMonitoringEntity.CONTAINERS]: 'k8s_pod_cpu_usage',
+ [InfraMonitoringEntity.JOBS]: 'k8s_job_desired_successful_pods',
+ [InfraMonitoringEntity.VOLUMES]: 'k8s_volume_capacity',
};
export const dotMap = {
- [K8sCategory.HOSTS]: 'system.cpu.load_average.15m',
- [K8sCategory.PODS]: 'k8s.pod.cpu.usage',
- [K8sCategory.NODES]: 'k8s.node.cpu.usage',
- [K8sCategory.NAMESPACES]: 'k8s.pod.cpu.usage',
- [K8sCategory.CLUSTERS]: 'k8s.node.cpu.usage',
- [K8sCategory.DEPLOYMENTS]: 'k8s.pod.cpu.usage',
- [K8sCategory.STATEFULSETS]: 'k8s.pod.cpu.usage',
- [K8sCategory.DAEMONSETS]: 'k8s.pod.cpu.usage',
- [K8sCategory.CONTAINERS]: 'k8s.pod.cpu.usage',
- [K8sCategory.JOBS]: 'k8s.job.desired_successful_pods',
- [K8sCategory.VOLUMES]: 'k8s.volume.capacity',
+ [InfraMonitoringEntity.HOSTS]: 'system.cpu.load_average.15m',
+ [InfraMonitoringEntity.PODS]: 'k8s.pod.cpu.usage',
+ [InfraMonitoringEntity.NODES]: 'k8s.node.cpu.usage',
+ [InfraMonitoringEntity.NAMESPACES]: 'k8s.pod.cpu.usage',
+ [InfraMonitoringEntity.CLUSTERS]: 'k8s.node.cpu.usage',
+ [InfraMonitoringEntity.DEPLOYMENTS]: 'k8s.pod.cpu.usage',
+ [InfraMonitoringEntity.STATEFULSETS]: 'k8s.pod.cpu.usage',
+ [InfraMonitoringEntity.DAEMONSETS]: 'k8s.pod.cpu.usage',
+ [InfraMonitoringEntity.CONTAINERS]: 'k8s.pod.cpu.usage',
+ [InfraMonitoringEntity.JOBS]: 'k8s.job.desired_successful_pods',
+ [InfraMonitoringEntity.VOLUMES]: 'k8s.volume.capacity',
};
export function GetK8sEntityToAggregateAttribute(
- category: K8sCategory,
+ category: InfraMonitoringEntity,
dotMetricsEnabled: boolean,
): string {
return dotMetricsEnabled ? dotMap[category] : underscoreMap[category];
@@ -767,22 +785,13 @@ export function GetJobsQuickFiltersConfig(
}
export const getInvalidValueTooltipText = (
- entity: K8sCategory,
+ entity: InfraMonitoringEntity,
attribute: string,
): string => `Some ${entity} do not have ${attribute}s.`;
export const INFRA_MONITORING_K8S_PARAMS_KEYS = {
CATEGORY: 'category',
VIEW: 'view',
- CLUSTER_NAME: 'clusterName',
- DAEMONSET_UID: 'daemonSetUID',
- DEPLOYMENT_UID: 'deploymentUID',
- JOB_UID: 'jobUID',
- NAMESPACE_UID: 'namespaceUID',
- NODE_UID: 'nodeUID',
- POD_UID: 'podUID',
- STATEFULSET_UID: 'statefulsetUID',
- VOLUME_UID: 'volumeUID',
FILTERS: 'filters',
GROUP_BY: 'groupBy',
ORDER_BY: 'orderBy',
@@ -791,4 +800,5 @@ export const INFRA_MONITORING_K8S_PARAMS_KEYS = {
EVENTS_FILTERS: 'eventsFilters',
HOSTS_FILTERS: 'hostsFilters',
CURRENT_PAGE: 'currentPage',
+ SELECTED_ITEM: 'selectedItem',
};
diff --git a/frontend/src/container/InfraMonitoringK8s/hooks.ts b/frontend/src/container/InfraMonitoringK8s/hooks.ts
index bf6f689eb4..c6d6ab98b9 100644
--- a/frontend/src/container/InfraMonitoringK8s/hooks.ts
+++ b/frontend/src/container/InfraMonitoringK8s/hooks.ts
@@ -1,4 +1,3 @@
-import { VIEWS } from 'components/HostMetricsDetail/constants';
import {
Options,
parseAsInteger,
@@ -14,10 +13,10 @@ import {
} from 'types/api/queryBuilder/queryBuilderData';
import { parseAsJsonNoValidate } from 'utils/nuqsParsers';
+import { VIEWS } from './constants';
import { INFRA_MONITORING_K8S_PARAMS_KEYS, K8sCategories } from './constants';
import { orderBySchema, OrderBySchemaType } from './schemas';
-const defaultFilters: IBuilderQuery['filters'] = { items: [], op: 'and' };
const defaultNuqsOptions: Options = {
history: 'push',
};
@@ -40,20 +39,6 @@ export const useInfraMonitoringOrderBy = (): UseQueryStateReturn<
parseAsJson(orderBySchema).withOptions(defaultNuqsOptions),
);
-export const useInfraMonitoringOrderByHosts = (): UseQueryStateReturn<
- OrderBySchemaType,
- OrderBySchemaType
-> =>
- useQueryState(
- INFRA_MONITORING_K8S_PARAMS_KEYS.ORDER_BY,
- parseAsJson(orderBySchema)
- .withDefault({
- columnName: 'cpu',
- order: 'desc',
- })
- .withOptions(defaultNuqsOptions),
- );
-
export const useInfraMonitoringGroupBy = (): UseQueryStateReturn<
BaseAutocompleteData[],
[]
@@ -114,15 +99,6 @@ export const useInfraMonitoringCategory = (): UseQueryStateReturn<
);
export const useInfraMonitoringFilters = (): UseQueryStateReturn<
- string,
- string
-> =>
- useQueryState(
- INFRA_MONITORING_K8S_PARAMS_KEYS.FILTERS,
- parseAsString.withDefault('').withOptions(defaultNuqsOptions),
- );
-
-export const useInfraMonitoringFiltersK8s = (): UseQueryStateReturn<
TagFilter,
undefined
> =>
@@ -131,94 +107,12 @@ export const useInfraMonitoringFiltersK8s = (): UseQueryStateReturn<
parseAsJsonNoValidate<TagFilter>().withOptions(defaultNuqsOptions),
);
-export const useInfraMonitoringFiltersHosts = (): UseQueryStateReturn<
- TagFilter,
- TagFilter | undefined
-> =>
- useQueryState(
- INFRA_MONITORING_K8S_PARAMS_KEYS.FILTERS,
- parseAsJsonNoValidate<IBuilderQuery['filters']>()
- .withDefault(defaultFilters)
- .withOptions(defaultNuqsOptions),
- );
-
-export const useInfraMonitoringClusterName = (): UseQueryStateReturn<
- string,
- string
-> =>
- useQueryState(
- INFRA_MONITORING_K8S_PARAMS_KEYS.CLUSTER_NAME,
- parseAsString.withDefault('').withOptions(defaultNuqsOptions),
- );
-
-export const useInfraMonitoringDaemonSetUID = (): UseQueryStateReturn<
- string,
- undefined
-> =>
- useQueryState(
- INFRA_MONITORING_K8S_PARAMS_KEYS.DAEMONSET_UID,
- parseAsString.withOptions(defaultNuqsOptions),
- );
-
-export const useInfraMonitoringDeploymentUID = (): UseQueryStateReturn<
- string,
- undefined
-> =>
- useQueryState(
- INFRA_MONITORING_K8S_PARAMS_KEYS.DEPLOYMENT_UID,
- parseAsString.withOptions(defaultNuqsOptions),
- );
-
-export const useInfraMonitoringJobUID = (): UseQueryStateReturn<
+export const useInfraMonitoringSelectedItem = (): UseQueryStateReturn<
string,
- undefined
-> =>
- useQueryState(
- INFRA_MONITORING_K8S_PARAMS_KEYS.JOB_UID,
- parseAsString.withOptions(defaultNuqsOptions),
- );
-
-export const useInfraMonitoringNamespaceUID = (): UseQueryStateReturn<
- string,
- undefined
-> =>
- useQueryState(
- INFRA_MONITORING_K8S_PARAMS_KEYS.NAMESPACE_UID,
- parseAsString.withOptions(defaultNuqsOptions),
- );
-
-export const useInfraMonitoringNodeUID = (): UseQueryStateReturn<
- string,
- undefined
-> =>
- useQueryState(
- INFRA_MONITORING_K8S_PARAMS_KEYS.NODE_UID,
- parseAsString.withOptions(defaultNuqsOptions),
- );
-
-export const useInfraMonitoringPodUID = (): UseQueryStateReturn<
- string,
- undefined
-> =>
- useQueryState(
- INFRA_MONITORING_K8S_PARAMS_KEYS.POD_UID,
- parseAsString.withOptions(defaultNuqsOptions),
- );
-
-export const useInfraMonitoringStatefulSetUID = (): UseQueryStateReturn<
- string,
- undefined
-> =>
- useQueryState(
- INFRA_MONITORING_K8S_PARAMS_KEYS.STATEFULSET_UID,
- parseAsString.withOptions(defaultNuqsOptions),
- );
-
-export const useInfraMonitoringVolumeUID = (): UseQueryStateReturn<
- string,
- undefined
-> =>
- useQueryState(
- INFRA_MONITORING_K8S_PARAMS_KEYS.VOLUME_UID,
- parseAsString.withOptions(defaultNuqsOptions),
+ string | undefined
+> => {
+ return useQueryState(
+ INFRA_MONITORING_K8S_PARAMS_KEYS.SELECTED_ITEM,
+ parseAsString,
);
+};
diff --git a/frontend/src/container/InfraMonitoringK8s/utils.tsx b/frontend/src/container/InfraMonitoringK8s/utils.tsx
index d97a145523..4955ddc511 100644
--- a/frontend/src/container/InfraMonitoringK8s/utils.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/utils.tsx
@@ -1,24 +1,8 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { Color } from '@signozhq/design-tokens';
-import { TableColumnType as ColumnType, Tag, Tooltip } from 'antd';
import get from 'api/browser/localstorage/get';
import set from 'api/browser/localstorage/set';
-import {
- K8sPodsData,
- K8sPodsListPayload,
-} from 'api/infraMonitoring/getK8sPodsList';
-import { Group } from 'lucide-react';
-import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
-import {
- EntityProgressBar,
- formatBytes,
- ValidateColumnValueWrapper,
-} from './commonUtils';
-import { DEFAULT_PAGE_SIZE, K8sCategory } from './constants';
-import { OrderBySchemaType } from './schemas';
-
-import './InfraMonitoringK8s.styles.scss';
+import { DEFAULT_PAGE_SIZE } from './constants';
export interface IEntityColumn {
label: string;
@@ -26,404 +10,6 @@ export interface IEntityColumn {
id: string;
canRemove: boolean;
}
-
-const columnProgressBarClassName = 'column-progress-bar';
-
-export const defaultAddedColumns: IEntityColumn[] = [
- {
- label: 'Pod name',
- value: 'podName',
- id: 'podName',
- canRemove: false,
- },
- {
- label: 'CPU Req Usage (%)',
- value: 'cpu_request',
- id: 'cpu_request',
- canRemove: false,
- },
- {
- label: 'CPU Limit Usage (%)',
- value: 'cpu_limit',
- id: 'cpu_limit',
- canRemove: false,
- },
- {
- label: 'CPU Usage (cores)',
- value: 'cpu',
- id: 'cpu',
- canRemove: false,
- },
- {
- label: 'Mem Req Usage (%)',
- value: 'memory_request',
- id: 'memory_request',
- canRemove: false,
- },
- {
- label: 'Mem Limit Usage (%)',
- value: 'memory_limit',
- id: 'memory_limit',
- canRemove: false,
- },
- {
- label: 'Mem Usage (WSS)',
- value: 'memory',
- id: 'memory',
- canRemove: false,
- },
- // TODO - Re-enable the column once backend issue is fixed
- // {
- // label: 'Restarts',
- // value: 'restarts',
- // id: 'restarts',
- // canRemove: false,
- // },
-];
-
-export const defaultAvailableColumns = [
- {
- label: 'Namespace name',
- value: 'namespace',
- id: 'namespace',
- canRemove: true,
- },
- {
- label: 'Node name',
- value: 'node',
- id: 'node',
- canRemove: true,
- },
- {
- label: 'Cluster name',
- value: 'cluster',
- id: 'cluster',
- canRemove: true,
- },
-];
-
-export interface K8sPodsRowData {
- key: string;
- podName: React.ReactNode;
- podUID: string;
- cpu_request: React.ReactNode;
- cpu_limit: React.ReactNode;
- cpu: React.ReactNode;
- memory_request: React.ReactNode;
- memory_limit: React.ReactNode;
- memory: React.ReactNode;
- restarts: React.ReactNode;
- groupedByMeta?: any;
-}
-
-export const getK8sPodsListQuery = (): K8sPodsListPayload => ({
- filters: {
- items: [],
- op: 'and',
- },
- orderBy: { columnName: 'cpu', order: 'desc' },
-});
-
-const podGroupColumnConfig = {
- title: (
- <div className="column-header entity-group-header">
- <Group size={14} /> POD GROUP
- </div>
- ),
- dataIndex: 'podGroup',
- key: 'podGroup',
- ellipsis: true,
- width: 180,
- sorter: false,
- className: 'column entity-group-header',
-};
-
-export const dummyColumnConfig = {
- title: <div className="column-header dummy-column">&nbsp;</div>,
- dataIndex: 'dummy',
- key: 'dummy',
- width: 40,
- sorter: false,
- align: 'left',
- className: 'column column-dummy',
-};
-
-const columnsConfig: ColumnType<K8sPodsRowData>[] = [
- {
- title: <div className="column-header pod-name-header">Pod Name</div>,
- dataIndex: 'podName',
- key: 'podName',
- width: 180,
- ellipsis: true,
- sorter: false,
- className: 'column column-pod-name',
- },
- {
- title: <div className="column-header med-col">CPU Req Usage (%)</div>,
- dataIndex: 'cpu_request',
- key: 'cpu_request',
- width: 180,
- ellipsis: true,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">CPU Limit Usage (%)</div>,
- dataIndex: 'cpu_limit',
- key: 'cpu_limit',
- width: 120,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header">CPU Usage (cores)</div>,
- dataIndex: 'cpu',
- key: 'cpu',
- width: 80,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-heade med-col">Mem Req Usage (%)</div>,
- dataIndex: 'memory_request',
- key: 'memory_request',
- width: 120,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">Mem Limit Usage (%)</div>,
- dataIndex: 'memory_limit',
- key: 'memory_limit',
- width: 120,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- {
- title: <div className="column-header med-col">Mem Usage (WSS)</div>,
- dataIndex: 'memory',
- key: 'memory',
- width: 120,
- ellipsis: true,
- sorter: true,
- align: 'left',
- className: `column ${columnProgressBarClassName}`,
- },
- // TODO - Re-enable the column once backend issue is fixed
- // {
- // title: (
- // <div className="column-header">
- // <Tooltip title="Container Restarts">Restarts</Tooltip>
- // </div>
- // ),
- // dataIndex: 'restarts',
- // key: 'restarts',
- // width: 40,
- // ellipsis: true,
- // sorter: true,
- // align: 'left',
- // className: `column ${columnProgressBarClassName}`,
- // },
-];
-
-export const namespaceColumnConfig: ColumnType<K8sPodsRowData> = {
- title: <div className="column-header">Namespace</div>,
- dataIndex: 'namespace',
- key: 'namespace',
- width: 100,
- sorter: false,
- ellipsis: true,
- align: 'left',
- className: 'column column-namespace',
-};
-
-export const nodeColumnConfig: ColumnType<K8sPodsRowData> = {
- title: <div className="column-header">Node</div>,
- dataIndex: 'node',
- key: 'node',
- width: 100,
- sorter: false,
- ellipsis: true,
- align: 'left',
- className: 'column column-node',
-};
-
-export const clusterColumnConfig: ColumnType<K8sPodsRowData> = {
- title: <div className="column-header">Cluster</div>,
- dataIndex: 'cluster',
- key: 'cluster',
- width: 100,
- sorter: false,
- ellipsis: true,
- align: 'left',
- className: 'column column-cluster',
-};
-
-export const columnConfigMap: Record<string, ColumnType<K8sPodsRowData>> = {
- namespace: namespaceColumnConfig,
- node: nodeColumnConfig,
- cluster: clusterColumnConfig,
-};
-
-export const getK8sPodsListColumns = (
- addedColumns: IEntityColumn[],
- groupBy: IBuilderQuery['groupBy'],
- defaultOrderBy: OrderBySchemaType,
-): ColumnType<K8sPodsRowData>[] => {
- const updatedColumnsConfig: ColumnType<K8sPodsRowData>[] = [...columnsConfig];
-
- for (const column of addedColumns) {
- const config = columnConfigMap[column.id as keyof typeof columnConfigMap];
- if (config) {
- updatedColumnsConfig.push(config);
- }
- }
-
- if (groupBy.length > 0) {
- const filteredColumns = [...updatedColumnsConfig].filter(
- (column) => column.key !== 'podName',
- );
-
- filteredColumns.unshift(podGroupColumnConfig);
-
- return filteredColumns as ColumnType<K8sPodsRowData>[];
- }
-
- for (const column of updatedColumnsConfig) {
- if (column.sorter && column.key === defaultOrderBy?.columnName) {
- column.defaultSortOrder =
- defaultOrderBy?.order === 'asc' ? 'ascend' : 'descend';
- }
- }
-
- return updatedColumnsConfig;
-};
-
-const dotToUnder: Record<string, keyof K8sPodsData['meta']> = {
- 'k8s.cronjob.name': 'k8s_cronjob_name',
- 'k8s.daemonset.name': 'k8s_daemonset_name',
- 'k8s.deployment.name': 'k8s_deployment_name',
- 'k8s.job.name': 'k8s_job_name',
- 'k8s.namespace.name': 'k8s_namespace_name',
- 'k8s.node.name': 'k8s_node_name',
- 'k8s.pod.name': 'k8s_pod_name',
- 'k8s.pod.uid': 'k8s_pod_uid',
- 'k8s.statefulset.name': 'k8s_statefulset_name',
- 'k8s.cluster.name': 'k8s_cluster_name',
-};
-
-const getGroupByEle = (
- pod: K8sPodsData,
- groupBy: IBuilderQuery['groupBy'],
-): React.ReactNode => {
- const groupByValues: string[] = [];
-
- groupBy.forEach((group) => {
- const rawKey = group.key as string;
-
- // Choose mapped key if present, otherwise use rawKey
- const metaKey = (dotToUnder[rawKey] ?? rawKey) as keyof typeof pod.meta;
- const value = pod.meta[metaKey];
-
- groupByValues.push(value);
- });
-
- return (
- <div className="pod-group">
- {groupByValues.map((value) => (
- <Tag key={value} color={Color.BG_SLATE_400} className="pod-group-tag-item">
- {value === '' ? '<no-value>' : value}
- </Tag>
- ))}
- </div>
- );
-};
-
-export const formatDataForTable = (
- data: K8sPodsData[],
- groupBy: IBuilderQuery['groupBy'],
-): K8sPodsRowData[] =>
- data.map((pod, index) => ({
- key: `${pod.podUID}-${index}`,
- podName: (
- <Tooltip title={pod.meta.k8s_pod_name || ''}>
- {pod.meta.k8s_pod_name || ''}
- </Tooltip>
- ),
- podUID: pod.podUID || '',
- cpu_request: (
- <ValidateColumnValueWrapper
- value={pod.podCPURequest}
- entity={K8sCategory.PODS}
- attribute="CPU Request"
- >
- <div className="progress-container">
- <EntityProgressBar value={pod.podCPURequest} type="request" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- cpu_limit: (
- <ValidateColumnValueWrapper
- value={pod.podCPULimit}
- entity={K8sCategory.PODS}
- attribute="CPU Limit"
- >
- <div className="progress-container">
- <EntityProgressBar value={pod.podCPULimit} type="limit" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- cpu: (
- <ValidateColumnValueWrapper value={pod.podCPU}>
- {pod.podCPU}
- </ValidateColumnValueWrapper>
- ),
- memory_request: (
- <ValidateColumnValueWrapper
- value={pod.podMemoryRequest}
- entity={K8sCategory.PODS}
- attribute="Memory Request"
- >
- <div className="progress-container">
- <EntityProgressBar value={pod.podMemoryRequest} type="request" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- memory_limit: (
- <ValidateColumnValueWrapper
- value={pod.podMemoryLimit}
- entity={K8sCategory.PODS}
- attribute="Memory Limit"
- >
- <div className="progress-container">
- <EntityProgressBar value={pod.podMemoryLimit} type="limit" />
- </div>
- </ValidateColumnValueWrapper>
- ),
- memory: (
- <ValidateColumnValueWrapper value={pod.podMemory}>
- {formatBytes(pod.podMemory)}
- </ValidateColumnValueWrapper>
- ),
- restarts: (
- <ValidateColumnValueWrapper value={pod.restartCount}>
- {pod.restartCount}
- </ValidateColumnValueWrapper>
- ),
- namespace: pod.meta.k8s_namespace_name,
- node: pod.meta.k8s_node_name,
- cluster: pod.meta.k8s_job_name,
- meta: pod.meta,
- podGroup: getGroupByEle(pod, groupBy),
- ...pod.meta,
- groupedByMeta: pod.meta,
- }));
-
/**
* Custom hook to manage the page size for a table.
* The page size is stored in local storage and is retrieved on initialization.
diff --git a/frontend/src/container/QueryBuilder/filters/QueryBuilderSearch/index.tsx b/frontend/src/container/QueryBuilder/filters/QueryBuilderSearch/index.tsx
index ec1e2fbf1f..0f347cd5c2 100644
--- a/frontend/src/container/QueryBuilder/filters/QueryBuilderSearch/index.tsx
+++ b/frontend/src/container/QueryBuilder/filters/QueryBuilderSearch/index.tsx
@@ -14,7 +14,7 @@ import cx from 'classnames';
import { OPERATORS } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import { LogsExplorerShortcuts } from 'constants/shortcuts/logsExplorerShortcuts';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
import { getDataTypes } from 'container/LogDetailedView/utils';
import { useKeyboardHotkeys } from 'hooks/hotkeys/useKeyboardHotkeys';
import {
@@ -517,7 +517,8 @@ interface QueryBuilderSearchProps {
suffixIcon?: React.ReactNode;
isInfraMonitoring?: boolean;
disableNavigationShortcuts?: boolean;
- entity?: K8sCategory | null;
+ // TODO: Remove the dependency of InfraMonitoring from this code
+ entity?: InfraMonitoringEntity | null;
isMetricsExplorer?: boolean;
}
diff --git a/frontend/src/hooks/infraMonitoring/useGetK8sClustersList.ts b/frontend/src/hooks/infraMonitoring/useGetK8sClustersList.ts
deleted file mode 100644
index 6f0d1965d5..0000000000
--- a/frontend/src/hooks/infraMonitoring/useGetK8sClustersList.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useMemo } from 'react';
-import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
-import {
- getK8sClustersList,
- K8sClustersListPayload,
- K8sClustersListResponse,
-} from 'api/infraMonitoring/getK8sClustersList';
-import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-
-type UseGetK8sClustersList = (
- requestData: K8sClustersListPayload,
-
- options?: UseQueryOptions<
- SuccessResponse<K8sClustersListResponse> | ErrorResponse,
- Error
- >,
-
- headers?: Record<string, string>,
- dotMetricsEnabled?: boolean,
-) => UseQueryResult<
- SuccessResponse<K8sClustersListResponse> | ErrorResponse,
- Error
->;
-
-export const useGetK8sClustersList: UseGetK8sClustersList = (
- requestData,
-
- options,
-
- headers,
- dotMetricsEnabled?: boolean,
-) => {
- const queryKey = useMemo(() => {
- if (options?.queryKey && Array.isArray(options.queryKey)) {
- return [...options.queryKey];
- }
-
- if (options?.queryKey && typeof options.queryKey === 'string') {
- return options.queryKey;
- }
-
- return [REACT_QUERY_KEY.GET_CLUSTER_LIST, requestData];
- }, [options?.queryKey, requestData]);
-
- return useQuery<
- SuccessResponse<K8sClustersListResponse> | ErrorResponse,
- Error
- >({
- queryFn: ({ signal }) =>
- getK8sClustersList(requestData, signal, headers, dotMetricsEnabled),
-
- ...options,
-
- queryKey,
- });
-};
diff --git a/frontend/src/hooks/infraMonitoring/useGetK8sDaemonSetsList.ts b/frontend/src/hooks/infraMonitoring/useGetK8sDaemonSetsList.ts
deleted file mode 100644
index 428400572c..0000000000
--- a/frontend/src/hooks/infraMonitoring/useGetK8sDaemonSetsList.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useMemo } from 'react';
-import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
-import {
- getK8sDaemonSetsList,
- K8sDaemonSetsListPayload,
- K8sDaemonSetsListResponse,
-} from 'api/infraMonitoring/getK8sDaemonSetsList';
-import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-
-type UseGetK8sDaemonSetsList = (
- requestData: K8sDaemonSetsListPayload,
-
- options?: UseQueryOptions<
- SuccessResponse<K8sDaemonSetsListResponse> | ErrorResponse,
- Error
- >,
-
- headers?: Record<string, string>,
- dotMetricsEnabled?: boolean,
-) => UseQueryResult<
- SuccessResponse<K8sDaemonSetsListResponse> | ErrorResponse,
- Error
->;
-
-export const useGetK8sDaemonSetsList: UseGetK8sDaemonSetsList = (
- requestData,
-
- options,
-
- headers,
- dotMetricsEnabled,
-) => {
- const queryKey = useMemo(() => {
- if (options?.queryKey && Array.isArray(options.queryKey)) {
- return [...options.queryKey];
- }
-
- if (options?.queryKey && typeof options.queryKey === 'string') {
- return options.queryKey;
- }
-
- return [REACT_QUERY_KEY.GET_DAEMONSET_LIST, requestData];
- }, [options?.queryKey, requestData]);
-
- return useQuery<
- SuccessResponse<K8sDaemonSetsListResponse> | ErrorResponse,
- Error
- >({
- queryFn: ({ signal }) =>
- getK8sDaemonSetsList(requestData, signal, headers, dotMetricsEnabled),
-
- ...options,
-
- queryKey,
- });
-};
diff --git a/frontend/src/hooks/infraMonitoring/useGetK8sDeploymentsList.ts b/frontend/src/hooks/infraMonitoring/useGetK8sDeploymentsList.ts
deleted file mode 100644
index 93c18db2a8..0000000000
--- a/frontend/src/hooks/infraMonitoring/useGetK8sDeploymentsList.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { useMemo } from 'react';
-import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
-import {
- getK8sDeploymentsList,
- K8sDeploymentsListPayload,
- K8sDeploymentsListResponse,
-} from 'api/infraMonitoring/getK8sDeploymentsList';
-import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-
-type UseGetK8sDeploymentsList = (
- requestData: K8sDeploymentsListPayload,
- options?: UseQueryOptions<
- SuccessResponse<K8sDeploymentsListResponse> | ErrorResponse,
- Error
- >,
- headers?: Record<string, string>,
- dotMetricsEnabled?: boolean,
-) => UseQueryResult<
- SuccessResponse<K8sDeploymentsListResponse> | ErrorResponse,
- Error
->;
-
-export const useGetK8sDeploymentsList: UseGetK8sDeploymentsList = (
- requestData,
- options,
- headers,
- dotMetricsEnabled,
-) => {
- const queryKey = useMemo(() => {
- if (options?.queryKey && Array.isArray(options.queryKey)) {
- return [...options.queryKey];
- }
-
- if (options?.queryKey && typeof options.queryKey === 'string') {
- return options.queryKey;
- }
-
- return [REACT_QUERY_KEY.GET_DEPLOYMENT_LIST, requestData];
- }, [options?.queryKey, requestData]);
-
- return useQuery<
- SuccessResponse<K8sDeploymentsListResponse> | ErrorResponse,
- Error
- >({
- queryFn: ({ signal }) =>
- getK8sDeploymentsList(requestData, signal, headers, dotMetricsEnabled),
- ...options,
- queryKey,
- });
-};
diff --git a/frontend/src/hooks/infraMonitoring/useGetK8sJobsList.ts b/frontend/src/hooks/infraMonitoring/useGetK8sJobsList.ts
deleted file mode 100644
index 240e3a058c..0000000000
--- a/frontend/src/hooks/infraMonitoring/useGetK8sJobsList.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { useMemo } from 'react';
-import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
-import {
- getK8sJobsList,
- K8sJobsListPayload,
- K8sJobsListResponse,
-} from 'api/infraMonitoring/getK8sJobsList';
-import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-
-type UseGetK8sJobsList = (
- requestData: K8sJobsListPayload,
-
- options?: UseQueryOptions<
- SuccessResponse<K8sJobsListResponse> | ErrorResponse,
- Error
- >,
-
- headers?: Record<string, string>,
- dotMetricsEnabled?: boolean,
-) => UseQueryResult<
- SuccessResponse<K8sJobsListResponse> | ErrorResponse,
- Error
->;
-
-export const useGetK8sJobsList: UseGetK8sJobsList = (
- requestData,
-
- options,
-
- headers,
- dotMetricsEnabled,
-) => {
- const queryKey = useMemo(() => {
- if (options?.queryKey && Array.isArray(options.queryKey)) {
- return [...options.queryKey];
- }
-
- if (options?.queryKey && typeof options.queryKey === 'string') {
- return options.queryKey;
- }
-
- return [REACT_QUERY_KEY.GET_JOB_LIST, requestData];
- }, [options?.queryKey, requestData]);
-
- return useQuery<SuccessResponse<K8sJobsListResponse> | ErrorResponse, Error>({
- queryFn: ({ signal }) =>
- getK8sJobsList(requestData, signal, headers, dotMetricsEnabled),
-
- ...options,
-
- queryKey,
- });
-};
diff --git a/frontend/src/hooks/infraMonitoring/useGetK8sNamespacesList.ts b/frontend/src/hooks/infraMonitoring/useGetK8sNamespacesList.ts
deleted file mode 100644
index 13fde89801..0000000000
--- a/frontend/src/hooks/infraMonitoring/useGetK8sNamespacesList.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { useMemo } from 'react';
-import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
-import {
- getK8sNamespacesList,
- K8sNamespacesListPayload,
- K8sNamespacesListResponse,
-} from 'api/infraMonitoring/getK8sNamespacesList';
-import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-
-type UseGetK8sNamespacesList = (
- requestData: K8sNamespacesListPayload,
- options?: UseQueryOptions<
- SuccessResponse<K8sNamespacesListResponse> | ErrorResponse,
- Error
- >,
- headers?: Record<string, string>,
- dotMetricsEnabled?: boolean,
-) => UseQueryResult<
- SuccessResponse<K8sNamespacesListResponse> | ErrorResponse,
- Error
->;
-
-export const useGetK8sNamespacesList: UseGetK8sNamespacesList = (
- requestData,
- options,
- headers,
- dotMetricsEnabled,
-) => {
- const queryKey = useMemo(() => {
- if (options?.queryKey && Array.isArray(options.queryKey)) {
- return [...options.queryKey];
- }
-
- if (options?.queryKey && typeof options.queryKey === 'string') {
- return options.queryKey;
- }
-
- return [REACT_QUERY_KEY.GET_NAMESPACE_LIST, requestData];
- }, [options?.queryKey, requestData]);
-
- return useQuery<
- SuccessResponse<K8sNamespacesListResponse> | ErrorResponse,
- Error
- >({
- queryFn: ({ signal }) =>
- getK8sNamespacesList(requestData, signal, headers, dotMetricsEnabled),
- ...options,
- queryKey,
- });
-};
diff --git a/frontend/src/hooks/infraMonitoring/useGetK8sNodesList.ts b/frontend/src/hooks/infraMonitoring/useGetK8sNodesList.ts
deleted file mode 100644
index e43dc1249e..0000000000
--- a/frontend/src/hooks/infraMonitoring/useGetK8sNodesList.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { useMemo } from 'react';
-import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
-import {
- getK8sNodesList,
- K8sNodesListPayload,
- K8sNodesListResponse,
-} from 'api/infraMonitoring/getK8sNodesList';
-import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-
-type UseGetK8sNodesList = (
- requestData: K8sNodesListPayload,
- options?: UseQueryOptions<
- SuccessResponse<K8sNodesListResponse> | ErrorResponse,
- Error
- >,
- headers?: Record<string, string>,
- dotMetricsEnabled?: boolean,
-) => UseQueryResult<
- SuccessResponse<K8sNodesListResponse> | ErrorResponse,
- Error
->;
-
-export const useGetK8sNodesList: UseGetK8sNodesList = (
- requestData,
- options,
- headers,
- dotMetricsEnabled,
-) => {
- const queryKey = useMemo(() => {
- if (options?.queryKey && Array.isArray(options.queryKey)) {
- return [...options.queryKey];
- }
-
- if (options?.queryKey && typeof options.queryKey === 'string') {
- return options.queryKey;
- }
-
- return [REACT_QUERY_KEY.GET_NODE_LIST, requestData];
- }, [options?.queryKey, requestData]);
-
- return useQuery<SuccessResponse<K8sNodesListResponse> | ErrorResponse, Error>({
- queryFn: ({ signal }) =>
- getK8sNodesList(requestData, signal, headers, dotMetricsEnabled),
- ...options,
- queryKey,
- });
-};
diff --git a/frontend/src/hooks/infraMonitoring/useGetK8sPodsList.ts b/frontend/src/hooks/infraMonitoring/useGetK8sPodsList.ts
deleted file mode 100644
index 6d587663bf..0000000000
--- a/frontend/src/hooks/infraMonitoring/useGetK8sPodsList.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { useMemo } from 'react';
-import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
-import {
- getK8sPodsList,
- K8sPodsListPayload,
- K8sPodsListResponse,
-} from 'api/infraMonitoring/getK8sPodsList';
-import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-
-type UseGetK8sPodsList = (
- requestData: K8sPodsListPayload,
- options?: UseQueryOptions<
- SuccessResponse<K8sPodsListResponse> | ErrorResponse,
- Error
- >,
- headers?: Record<string, string>,
- dotMetricsEnabled?: boolean,
-) => UseQueryResult<
- SuccessResponse<K8sPodsListResponse> | ErrorResponse,
- Error
->;
-
-export const useGetK8sPodsList: UseGetK8sPodsList = (
- requestData,
- options,
- headers,
- dotMetricsEnabled,
-) => {
- const queryKey = useMemo(() => {
- if (options?.queryKey && Array.isArray(options.queryKey)) {
- return [...options.queryKey];
- }
-
- if (options?.queryKey && typeof options.queryKey === 'string') {
- return options.queryKey;
- }
-
- return [REACT_QUERY_KEY.GET_POD_LIST, requestData];
- }, [options?.queryKey, requestData]);
-
- return useQuery<SuccessResponse<K8sPodsListResponse> | ErrorResponse, Error>({
- queryFn: ({ signal }) =>
- getK8sPodsList(requestData, signal, headers, dotMetricsEnabled),
- ...options,
- queryKey,
- });
-};
diff --git a/frontend/src/hooks/infraMonitoring/useGetK8sStatefulSetsList.ts b/frontend/src/hooks/infraMonitoring/useGetK8sStatefulSetsList.ts
deleted file mode 100644
index bed0da8535..0000000000
--- a/frontend/src/hooks/infraMonitoring/useGetK8sStatefulSetsList.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useMemo } from 'react';
-import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
-import {
- getK8sStatefulSetsList,
- K8sStatefulSetsListPayload,
- K8sStatefulSetsListResponse,
-} from 'api/infraMonitoring/getsK8sStatefulSetsList';
-import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-
-type UseGetK8sStatefulSetsList = (
- requestData: K8sStatefulSetsListPayload,
-
- options?: UseQueryOptions<
- SuccessResponse<K8sStatefulSetsListResponse> | ErrorResponse,
- Error
- >,
-
- headers?: Record<string, string>,
- dotMetricsEnabled?: boolean,
-) => UseQueryResult<
- SuccessResponse<K8sStatefulSetsListResponse> | ErrorResponse,
- Error
->;
-
-export const useGetK8sStatefulSetsList: UseGetK8sStatefulSetsList = (
- requestData,
-
- options,
-
- headers,
- dotMetricsEnabled,
-) => {
- const queryKey = useMemo(() => {
- if (options?.queryKey && Array.isArray(options.queryKey)) {
- return [...options.queryKey];
- }
-
- if (options?.queryKey && typeof options.queryKey === 'string') {
- return options.queryKey;
- }
-
- return [REACT_QUERY_KEY.GET_STATEFULSET_LIST, requestData];
- }, [options?.queryKey, requestData]);
-
- return useQuery<
- SuccessResponse<K8sStatefulSetsListResponse> | ErrorResponse,
- Error
- >({
- queryFn: ({ signal }) =>
- getK8sStatefulSetsList(requestData, signal, headers, dotMetricsEnabled),
-
- ...options,
-
- queryKey,
- });
-};
diff --git a/frontend/src/hooks/infraMonitoring/useGetK8sVolumesList.ts b/frontend/src/hooks/infraMonitoring/useGetK8sVolumesList.ts
deleted file mode 100644
index 68f9098bc9..0000000000
--- a/frontend/src/hooks/infraMonitoring/useGetK8sVolumesList.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { useMemo } from 'react';
-import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
-import {
- getK8sVolumesList,
- K8sVolumesListPayload,
- K8sVolumesListResponse,
-} from 'api/infraMonitoring/getK8sVolumesList';
-import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-
-type UseGetK8sVolumesList = (
- requestData: K8sVolumesListPayload,
- options?: UseQueryOptions<
- SuccessResponse<K8sVolumesListResponse> | ErrorResponse,
- Error
- >,
- headers?: Record<string, string>,
- dotMetricsEnabled?: boolean,
-) => UseQueryResult<
- SuccessResponse<K8sVolumesListResponse> | ErrorResponse,
- Error
->;
-
-export const useGetK8sVolumesList: UseGetK8sVolumesList = (
- requestData,
- options,
- headers,
- dotMetricsEnabled,
-) => {
- const queryKey = useMemo(() => {
- if (options?.queryKey && Array.isArray(options.queryKey)) {
- return [...options.queryKey];
- }
-
- if (options?.queryKey && typeof options.queryKey === 'string') {
- return options.queryKey;
- }
-
- return [REACT_QUERY_KEY.GET_VOLUME_LIST, requestData];
- }, [options?.queryKey, requestData]);
-
- return useQuery<
- SuccessResponse<K8sVolumesListResponse> | ErrorResponse,
- Error
- >({
- queryFn: ({ signal }) =>
- getK8sVolumesList(requestData, signal, headers, dotMetricsEnabled),
- ...options,
- queryKey,
- });
-};
diff --git a/frontend/src/hooks/queryBuilder/useAutoComplete.ts b/frontend/src/hooks/queryBuilder/useAutoComplete.ts
index 762045f909..3741a373a2 100644
--- a/frontend/src/hooks/queryBuilder/useAutoComplete.ts
+++ b/frontend/src/hooks/queryBuilder/useAutoComplete.ts
@@ -1,6 +1,6 @@
import { KeyboardEvent, useCallback, useState } from 'react';
import { OPERATORS } from 'constants/queryBuilder';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
import {
getRemovePrefixFromKey,
getTagToken,
@@ -31,7 +31,7 @@ export const useAutoComplete = (
whereClauseConfig?: WhereClauseConfig,
shouldUseSuggestions?: boolean,
isInfraMonitoring?: boolean,
- entity?: K8sCategory | null,
+ entity?: InfraMonitoringEntity | null,
isMetricsExplorer?: boolean,
): IAutoComplete => {
const [searchValue, setSearchValue] = useState<string>('');
diff --git a/frontend/src/hooks/queryBuilder/useFetchKeysAndValues.ts b/frontend/src/hooks/queryBuilder/useFetchKeysAndValues.ts
index b366057703..ea14a6f7f1 100644
--- a/frontend/src/hooks/queryBuilder/useFetchKeysAndValues.ts
+++ b/frontend/src/hooks/queryBuilder/useFetchKeysAndValues.ts
@@ -6,7 +6,7 @@ import { DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY } from 'constants/queryBuilder';
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
import {
GetK8sEntityToAggregateAttribute,
- K8sCategory,
+ InfraMonitoringEntity,
} from 'container/InfraMonitoringK8s/constants';
import {
getRemovePrefixFromKey,
@@ -52,7 +52,7 @@ export const useFetchKeysAndValues = (
searchKey: string,
shouldUseSuggestions?: boolean,
isInfraMonitoring?: boolean,
- entity?: K8sCategory | null,
+ entity?: InfraMonitoringEntity | null,
isMetricsExplorer?: boolean,
): IuseFetchKeysAndValues => {
const [keys, setKeys] = useState<BaseAutocompleteData[]>([]);
diff --git a/frontend/src/hooks/queryBuilder/useGetAggregateKeys.ts b/frontend/src/hooks/queryBuilder/useGetAggregateKeys.ts
index 5f1765234b..b542c4b4a9 100644
--- a/frontend/src/hooks/queryBuilder/useGetAggregateKeys.ts
+++ b/frontend/src/hooks/queryBuilder/useGetAggregateKeys.ts
@@ -2,7 +2,7 @@ import { useMemo } from 'react';
import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
import { getAggregateKeys } from 'api/queryBuilder/getAttributeKeys';
import { QueryBuilderKeys } from 'constants/queryBuilder';
-import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8s/constants';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { IGetAttributeKeysPayload } from 'types/api/queryBuilder/getAttributeKeys';
import { IQueryAutocompleteResponse } from 'types/api/queryBuilder/queryAutocompleteResponse';
@@ -13,7 +13,7 @@ type UseGetAttributeKeys = (
SuccessResponse<IQueryAutocompleteResponse> | ErrorResponse
>,
isInfraMonitoring?: boolean,
- infraMonitoringEntity?: K8sCategory | null,
+ infraMonitoringEntity?: InfraMonitoringEntity | null,
) => UseQueryResult<
SuccessResponse<IQueryAutocompleteResponse> | ErrorResponse
>;
diff --git a/frontend/src/store/globalTime/globalTimeStore.ts b/frontend/src/store/globalTime/globalTimeStore.ts
index b9f7c08432..61478dd196 100644
--- a/frontend/src/store/globalTime/globalTimeStore.ts
+++ b/frontend/src/store/globalTime/globalTimeStore.ts
@@ -26,8 +26,7 @@ export const useGlobalTimeStore = create<IGlobalTimeStore>((set, get) => ({
};
});
},
- getMinMaxTime: (): ParsedTimeRange => {
- const { selectedTime } = get();
- return parseSelectedTime(selectedTime);
+ getMinMaxTime: (selectedTime): ParsedTimeRange => {
+ return parseSelectedTime(selectedTime || get().selectedTime);
},
}));
diff --git a/frontend/src/store/globalTime/types.ts b/frontend/src/store/globalTime/types.ts
index 5151aa5200..b16665b4c6 100644
--- a/frontend/src/store/globalTime/types.ts
+++ b/frontend/src/store/globalTime/types.ts
@@ -48,5 +48,5 @@ export interface IGlobalTimeStoreActions {
* For durations, computes fresh values based on Date.now().
* For custom ranges, extracts the stored values.
*/
- getMinMaxTime: () => ParsedTimeRange;
+ getMinMaxTime: (selectedItem?: GlobalTimeSelectedTime) => ParsedTimeRange;
}
diff --git a/frontend/src/store/globalTime/utils.ts b/frontend/src/store/globalTime/utils.ts
index 96330a2086..ba81d43e91 100644
--- a/frontend/src/store/globalTime/utils.ts
+++ b/frontend/src/store/globalTime/utils.ts
@@ -17,7 +17,9 @@ export const CUSTOM_TIME_SEPARATOR: CustomTimeRangeSeparator = '||_||';
/**
* Check if selectedTime represents a custom time range
*/
-export function isCustomTimeRange(selectedTime: string): boolean {
+export function isCustomTimeRange(
+ selectedTime: string,
+): selectedTime is CustomTimeRange {
return selectedTime.includes(CUSTOM_TIME_SEPARATOR);
}