import { isUndefined, omitBy, sum } from 'lodash'; import pluralize from 'pluralize'; import React, { Fragment } from 'react'; import { Stack } from '@grafana/experimental'; import { Badge } from '@grafana/ui'; import { AlertGroupTotals, AlertInstanceTotalState, CombinedRuleGroup, CombinedRuleNamespace, } from 'app/types/unified-alerting'; import { PromAlertingRuleState } from 'app/types/unified-alerting-dto'; interface Props { namespaces: CombinedRuleNamespace[]; } // All available states for a rule need to be initialized to prevent NaN values when adding a number and undefined const emptyStats: Required = { recording: 0, alerting: 0, [PromAlertingRuleState.Pending]: 0, [PromAlertingRuleState.Inactive]: 0, paused: 0, error: 0, nodata: 0, }; export const RuleStats = ({ namespaces }: Props) => { const stats = { ...emptyStats }; // sum all totals for all namespaces namespaces.forEach(({ groups }) => { groups.forEach((group) => { const groupTotals = omitBy(group.totals, isUndefined); for (let key in groupTotals) { // @ts-ignore stats[key] += groupTotals[key]; } }); }); const statsComponents = getComponentsFromStats(stats); const hasStats = Boolean(statsComponents.length); const total = sum(Object.values(stats)); statsComponents.unshift( {total} {pluralize('rule', total)} ); return ( {hasStats && (
{statsComponents}
)}
); }; interface RuleGroupStatsProps { group: CombinedRuleGroup; } export const RuleGroupStats = ({ group }: RuleGroupStatsProps) => { const stats = group.totals; const evaluationInterval = group?.interval; const statsComponents = getComponentsFromStats(stats); const hasStats = Boolean(statsComponents.length); return ( {hasStats && (
{statsComponents}
)} {evaluationInterval && ( <>
|
)}
); }; export function getComponentsFromStats( stats: Partial> ) { const statsComponents: React.ReactNode[] = []; if (stats[AlertInstanceTotalState.Alerting]) { statsComponents.push(); } if (stats.error) { statsComponents.push(); } if (stats.nodata) { statsComponents.push(); } if (stats[AlertInstanceTotalState.Pending]) { statsComponents.push( ); } if (stats[AlertInstanceTotalState.Normal] && stats.paused) { statsComponents.push( ); } if (stats[AlertInstanceTotalState.Normal] && !stats.paused) { statsComponents.push( ); } if (stats.recording) { statsComponents.push(); } return statsComponents; }