Alerting: UI standardization and fixes (#38770)

* Add expand all button for rule list group view

* filter out recording rules by default

* Create rule type filter

* Add placeholder text for inputs

* WIP move Silences to use DynamicTable

* Use dynamic table for silences page

* hide expand all for state list view

* Add placeholders for inputs

* Update selector in receivers test

* Fix strict error for ruleType

* remove redundant placeholder text and cleanup hooks

* add fixed width for schedule

* Rebase with dynamic table for silences

* only show expand/collapse when filters are active
This commit is contained in:
Nathan Rodman 2021-10-01 15:15:55 -07:00 committed by GitHub
parent 9f93a81bee
commit 427f75d9b0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 323 additions and 133 deletions

View File

@ -7,6 +7,7 @@ export const getAvailableIcons = () =>
[
'angle-double-down',
'angle-double-right',
'angle-double-up',
'angle-down',
'angle-left',
'angle-right',

View File

@ -132,6 +132,5 @@ const getStyles = (theme: GrafanaTheme2) => ({
width: 100%;
height: 0;
margin-bottom: ${theme.spacing(2)};
border-bottom: solid 1px ${theme.colors.border.medium};
`,
});

View File

@ -18,7 +18,7 @@ import {
import { DataSourceType, GRAFANA_RULES_SOURCE_NAME } from './utils/datasource';
import { fetchNotifiers } from './api/grafana';
import { grafanaNotifiersMock } from './mocks/grafana-notifiers';
import { byLabelText, byRole, byTestId, byText } from 'testing-library-selector';
import { byLabelText, byPlaceholderText, byRole, byTestId, byText } from 'testing-library-selector';
import userEvent from '@testing-library/user-event';
import { ALERTMANAGER_NAME_LOCAL_STORAGE_KEY, ALERTMANAGER_NAME_QUERY_KEY } from './utils/constants';
import store from 'app/core/store';
@ -87,7 +87,7 @@ const ui = {
channelFormContainer: byTestId('item-container'),
inputs: {
name: byLabelText('Name'),
name: byPlaceholderText('Name'),
email: {
addresses: byLabelText(/Addresses/),
toEmails: byLabelText(/To/),
@ -213,7 +213,7 @@ describe('Receivers', () => {
expect(locationService.getLocation().pathname).toEqual('/alerting/notifications/receivers/new');
// type in a name for the new receiver
await userEvent.type(byLabelText('Name').get(), 'my new receiver');
await userEvent.type(byPlaceholderText('Name').get(), 'my new receiver');
// check that default email form is rendered
await ui.inputs.email.addresses.find();

View File

@ -1,6 +1,6 @@
import { GrafanaTheme2, urlUtil } from '@grafana/data';
import { useStyles2, LinkButton, withErrorBoundary } from '@grafana/ui';
import React, { useEffect, useMemo } from 'react';
import { useStyles2, LinkButton, withErrorBoundary, Button } from '@grafana/ui';
import React, { useEffect, useMemo, useState } from 'react';
import { useDispatch } from 'react-redux';
import { AlertingPageWrapper } from './components/AlertingPageWrapper';
import { NoRulesSplash } from './components/rules/NoRulesCTA';
@ -19,6 +19,7 @@ import { useLocation } from 'react-router-dom';
import { contextSrv } from 'app/core/services/context_srv';
import { RuleStats } from './components/rules/RuleStats';
import { RuleListErrors } from './components/rules/RuleListErrors';
import { getFiltersFromUrlParams } from './utils/misc';
const VIEWS = {
groups: RuleListGroupView,
@ -31,8 +32,11 @@ export const RuleList = withErrorBoundary(
const styles = useStyles2(getStyles);
const rulesDataSourceNames = useMemo(getAllRulesSourceNames, []);
const location = useLocation();
const [expandAll, setExpandAll] = useState(false);
const [queryParams] = useQueryParams();
const filters = getFiltersFromUrlParams(queryParams);
const filtersActive = Object.values(filters).some((filter) => filter !== undefined);
const view = VIEWS[queryParams['view'] as keyof typeof VIEWS]
? (queryParams['view'] as keyof typeof VIEWS)
@ -76,8 +80,19 @@ export const RuleList = withErrorBoundary(
<RulesFilter />
<div className={styles.break} />
<div className={styles.buttonsContainer}>
<RuleStats showInactive={true} showRecording={true} namespaces={filteredNamespaces} />
<div />
<div className={styles.statsContainer}>
{view === 'groups' && filtersActive && (
<Button
className={styles.expandAllButton}
icon={expandAll ? 'angle-double-up' : 'angle-double-down'}
variant="secondary"
onClick={() => setExpandAll(!expandAll)}
>
{expandAll ? 'Collapse all' : 'Expand all'}
</Button>
)}
<RuleStats showInactive={true} showRecording={true} namespaces={filteredNamespaces} />
</div>
{(contextSrv.hasEditPermissionInFolders || contextSrv.isEditor) && (
<LinkButton
href={urlUtil.renderUrl('alerting/new', { returnTo: location.pathname + location.search })}
@ -90,7 +105,7 @@ export const RuleList = withErrorBoundary(
</>
)}
{showNewAlertSplash && <NoRulesSplash />}
{haveResults && <ViewComponent namespaces={filteredNamespaces} />}
{haveResults && <ViewComponent expandAll={expandAll} namespaces={filteredNamespaces} />}
</AlertingPageWrapper>
);
},
@ -109,4 +124,12 @@ const getStyles = (theme: GrafanaTheme2) => ({
display: flex;
justify-content: space-between;
`,
statsContainer: css`
display: flex;
flex-direction: row;
align-items: center;
`,
expandAllButton: css`
margin-right: ${theme.spacing(1)};
`,
});

View File

@ -46,9 +46,9 @@ const dataSources = {
};
const ui = {
silencesTable: byTestId('silences-table'),
silenceRow: byTestId('silence-table-row'),
silencedAlertCell: byTestId('silenced-alerts'),
silencesTable: byTestId('dynamic-table'),
silenceRow: byTestId('row'),
silencedAlertCell: byTestId('alerts'),
queryBar: byPlaceholderText('Search'),
editor: {
timeRange: byLabelText('Timepicker', { exact: false }),
@ -58,7 +58,7 @@ const ui = {
matcherName: byPlaceholderText('label'),
matcherValue: byPlaceholderText('value'),
comment: byPlaceholderText('Details about the silence'),
createdBy: byPlaceholderText('Username'),
createdBy: byPlaceholderText('User'),
matcherOperatorSelect: byLabelText('operator'),
matcherOperator: (operator: MatcherOperator) => byText(operator, { exact: true }),
addMatcherButton: byRole('button', { name: 'Add matcher' }),

View File

@ -54,7 +54,10 @@ export const AmRootRouteForm: FC<AmRootRouteFormProps> = ({
rules={{ required: { value: true, message: 'Required.' } }}
/>
<span>or</span>
<Link href={makeAMLink('/alerting/notifications/receivers/new', alertManagerSourceName)}>
<Link
className={styles.linkText}
href={makeAMLink('/alerting/notifications/receivers/new', alertManagerSourceName)}
>
Create a contact point
</Link>
</div>
@ -89,6 +92,7 @@ export const AmRootRouteForm: FC<AmRootRouteFormProps> = ({
</Field>
<Collapse
collapsible
className={styles.collapse}
isOpen={isTimingOptionsExpanded}
label="Timing options"
onToggle={setIsTimingOptionsExpanded}
@ -104,7 +108,12 @@ export const AmRootRouteForm: FC<AmRootRouteFormProps> = ({
<div className={cx(styles.container, styles.timingContainer)}>
<InputControl
render={({ field, fieldState: { invalid } }) => (
<Input {...field} className={styles.smallInput} invalid={invalid} />
<Input
{...field}
className={styles.smallInput}
invalid={invalid}
placeholder={'Default 30 seconds'}
/>
)}
control={control}
name="groupWaitValue"
@ -139,7 +148,12 @@ export const AmRootRouteForm: FC<AmRootRouteFormProps> = ({
<div className={cx(styles.container, styles.timingContainer)}>
<InputControl
render={({ field, fieldState: { invalid } }) => (
<Input {...field} className={styles.smallInput} invalid={invalid} />
<Input
{...field}
className={styles.smallInput}
invalid={invalid}
placeholder={'Default 5 minutes'}
/>
)}
control={control}
name="groupIntervalValue"
@ -174,7 +188,7 @@ export const AmRootRouteForm: FC<AmRootRouteFormProps> = ({
<div className={cx(styles.container, styles.timingContainer)}>
<InputControl
render={({ field, fieldState: { invalid } }) => (
<Input {...field} className={styles.smallInput} invalid={invalid} />
<Input {...field} className={styles.smallInput} invalid={invalid} placeholder="Default 4 hours" />
)}
control={control}
name="repeatIntervalValue"

View File

@ -189,7 +189,7 @@ export const AmRoutesExpandedForm: FC<AmRoutesExpandedFormProps> = ({ onCancel,
<div className={cx(formStyles.container, formStyles.timingContainer)}>
<InputControl
render={({ field, fieldState: { invalid } }) => (
<Input {...field} className={formStyles.smallInput} invalid={invalid} />
<Input {...field} className={formStyles.smallInput} invalid={invalid} placeholder="Time" />
)}
control={control}
name="groupWaitValue"
@ -223,7 +223,7 @@ export const AmRoutesExpandedForm: FC<AmRoutesExpandedFormProps> = ({ onCancel,
<div className={cx(formStyles.container, formStyles.timingContainer)}>
<InputControl
render={({ field, fieldState: { invalid } }) => (
<Input {...field} className={formStyles.smallInput} invalid={invalid} />
<Input {...field} className={formStyles.smallInput} invalid={invalid} placeholder="Time" />
)}
control={control}
name="groupIntervalValue"
@ -257,7 +257,7 @@ export const AmRoutesExpandedForm: FC<AmRoutesExpandedFormProps> = ({ onCancel,
<div className={cx(formStyles.container, formStyles.timingContainer)}>
<InputControl
render={({ field, fieldState: { invalid } }) => (
<Input {...field} className={formStyles.smallInput} invalid={invalid} />
<Input {...field} className={formStyles.smallInput} invalid={invalid} placeholder="Time" />
)}
control={control}
name="repeatIntervalValue"

View File

@ -21,5 +21,13 @@ export const getFormStyles = (theme: GrafanaTheme2) => {
smallInput: css`
width: ${theme.spacing(6.5)};
`,
linkText: css`
text-decoration: underline;
`,
collapse: css`
border: none;
background: none;
color: ${theme.colors.text.primary};
`,
};
};

View File

@ -98,12 +98,13 @@ export const TemplateForm: FC<Props> = ({ existing, alertManagerSourceName, conf
{error.message || (error as any)?.data?.message || String(error)}
</Alert>
)}
<Field label="Template name" error={errors?.name?.message} invalid={!!errors.name?.message}>
<Field label="Template name" error={errors?.name?.message} invalid={!!errors.name?.message} required>
<Input
{...register('name', {
required: { value: true, message: 'Required.' },
validate: { nameIsUnique: validateNameIsUnique },
})}
placeholder="Give your template a name"
width={42}
autoFocus={true}
/>
@ -134,10 +135,12 @@ export const TemplateForm: FC<Props> = ({ existing, alertManagerSourceName, conf
label="Content"
error={errors?.content?.message}
invalid={!!errors.content?.message}
required
>
<TextArea
{...register('content', { required: { value: true, message: 'Required.' } })}
className={styles.textarea}
placeholder="Message"
rows={12}
/>
</Field>

View File

@ -98,7 +98,7 @@ export function ReceiverForm<R extends ChannelValues>({
<h4 className={styles.heading}>
{readOnly ? 'Contact point' : initialValues ? 'Update contact point' : 'Create contact point'}
</h4>
<Field label="Name" invalid={!!errors.name} error={errors.name && errors.name.message}>
<Field label="Name" invalid={!!errors.name} error={errors.name && errors.name.message} required>
<Input
readOnly={readOnly}
id="name"
@ -107,6 +107,7 @@ export function ReceiverForm<R extends ChannelValues>({
validate: { nameIsAvailable: validateNameIsAvailable },
})}
width={39}
placeholder="Name"
/>
</Field>
{fields.map((field, index) => {

View File

@ -10,9 +10,10 @@ import pluralize from 'pluralize';
interface Props {
namespaces: CombinedRuleNamespace[];
expandAll: boolean;
}
export const CloudRules: FC<Props> = ({ namespaces }) => {
export const CloudRules: FC<Props> = ({ namespaces, expandAll }) => {
const styles = useStyles(getStyles);
const rules = useUnifiedAlertingSelector((state) => state.promRules);
const rulesDataSources = useMemo(getRulesDataSources, []);
@ -43,6 +44,7 @@ export const CloudRules: FC<Props> = ({ namespaces }) => {
group={group}
key={`${getRulesSourceName(rulesSource)}-${name}-${group.name}`}
namespace={namespace}
expandAll={expandAll}
/>
));
})}

View File

@ -10,9 +10,10 @@ import { initialAsyncRequestState } from '../../utils/redux';
interface Props {
namespaces: CombinedRuleNamespace[];
expandAll: boolean;
}
export const GrafanaRules: FC<Props> = ({ namespaces }) => {
export const GrafanaRules: FC<Props> = ({ namespaces, expandAll }) => {
const styles = useStyles(getStyles);
const { loading } = useUnifiedAlertingSelector(
(state) => state.promRules[GRAFANA_RULES_SOURCE_NAME] || initialAsyncRequestState
@ -27,7 +28,12 @@ export const GrafanaRules: FC<Props> = ({ namespaces }) => {
{namespaces?.map((namespace) =>
namespace.groups.map((group) => (
<RulesGroup group={group} key={`${namespace.name}-${group.name}`} namespace={namespace} />
<RulesGroup
group={group}
key={`${namespace.name}-${group.name}`}
namespace={namespace}
expandAll={expandAll}
/>
))
)}
{namespaces?.length === 0 && <p>No rules found.</p>}

View File

@ -6,9 +6,10 @@ import { GrafanaRules } from './GrafanaRules';
interface Props {
namespaces: CombinedRuleNamespace[];
expandAll: boolean;
}
export const RuleListGroupView: FC<Props> = ({ namespaces }) => {
export const RuleListGroupView: FC<Props> = ({ namespaces, expandAll }) => {
const [grafanaNamespaces, cloudNamespaces] = useMemo(() => {
const sorted = namespaces
.map((namespace) => ({
@ -24,8 +25,8 @@ export const RuleListGroupView: FC<Props> = ({ namespaces }) => {
return (
<>
<GrafanaRules namespaces={grafanaNamespaces} />
<CloudRules namespaces={cloudNamespaces} />
<GrafanaRules namespaces={grafanaNamespaces} expandAll={expandAll} />
<CloudRules namespaces={cloudNamespaces} expandAll={expandAll} />
</>
);
};

View File

@ -8,6 +8,7 @@ import { RuleListStateSection } from './RuleListStateSection';
interface Props {
namespaces: CombinedRuleNamespace[];
expandAll?: boolean;
}
type GroupedRules = Record<PromAlertingRuleState, CombinedRule[]>;

View File

@ -4,7 +4,7 @@ import { DataSourceInstanceSettings, GrafanaTheme, SelectableValue } from '@graf
import { css, cx } from '@emotion/css';
import { debounce } from 'lodash';
import { PromAlertingRuleState } from 'app/types/unified-alerting-dto';
import { PromAlertingRuleState, PromRuleType } from 'app/types/unified-alerting-dto';
import { useQueryParams } from 'app/core/hooks/useQueryParams';
import { getFiltersFromUrlParams } from '../../utils/misc';
import { DataSourcePicker } from '@grafana/runtime';
@ -23,6 +23,17 @@ const ViewOptions: SelectableValue[] = [
},
];
const RuleTypeOptions: SelectableValue[] = [
{
label: 'Alert ',
value: PromRuleType.Alerting,
},
{
label: 'Recording ',
value: PromRuleType.Recording,
},
];
const RulesFilter = () => {
const [queryParams, setQueryParams] = useQueryParams();
// This key is used to force a rerender on the inputs when the filters are cleared
@ -30,7 +41,7 @@ const RulesFilter = () => {
const dataSourceKey = `dataSource-${filterKey}`;
const queryStringKey = `queryString-${filterKey}`;
const { dataSource, alertState, queryString } = getFiltersFromUrlParams(queryParams);
const { dataSource, alertState, queryString, ruleType } = getFiltersFromUrlParams(queryParams);
const styles = useStyles(getStyles);
const stateOptions = Object.entries(PromAlertingRuleState).map(([key, value]) => ({
@ -55,11 +66,16 @@ const RulesFilter = () => {
setQueryParams({ view });
};
const handleRuleTypeChange = (ruleType: PromRuleType) => {
setQueryParams({ ruleType });
};
const handleClearFiltersClick = () => {
setQueryParams({
alertState: null,
queryString: null,
dataSource: null,
ruleType: null,
});
setTimeout(() => setFilterKey(filterKey + 1), 100);
};
@ -107,6 +123,14 @@ const RulesFilter = () => {
<Label>State</Label>
<RadioButtonGroup options={stateOptions} value={alertState} onChange={handleAlertStateChange} />
</div>
<div className={styles.rowChild}>
<Label>Rule type</Label>
<RadioButtonGroup
options={RuleTypeOptions}
value={ruleType as PromRuleType}
onChange={handleRuleTypeChange}
/>
</div>
<div className={styles.rowChild}>
<Label>View as</Label>
<RadioButtonGroup
@ -116,7 +140,7 @@ const RulesFilter = () => {
/>
</div>
</div>
{(dataSource || alertState || queryString) && (
{(dataSource || alertState || queryString || ruleType) && (
<div className={styles.flexRow}>
<Button
className={styles.clearButton}

View File

@ -1,5 +1,5 @@
import { CombinedRuleGroup, CombinedRuleNamespace } from 'app/types/unified-alerting';
import React, { FC, useState } from 'react';
import React, { FC, useState, useEffect } from 'react';
import { HorizontalGroup, Icon, Spinner, Tooltip, useStyles2 } from '@grafana/ui';
import { GrafanaTheme2 } from '@grafana/data';
import { css } from '@emotion/css';
@ -17,14 +17,19 @@ import { EditCloudGroupModal } from './EditCloudGroupModal';
interface Props {
namespace: CombinedRuleNamespace;
group: CombinedRuleGroup;
expandAll: boolean;
}
export const RulesGroup: FC<Props> = React.memo(({ group, namespace }) => {
export const RulesGroup: FC<Props> = React.memo(({ group, namespace, expandAll }) => {
const { rulesSource } = namespace;
const styles = useStyles2(getStyles);
const [isCollapsed, setIsCollapsed] = useState(true);
const [isEditingGroup, setIsEditingGroup] = useState(false);
const [isCollapsed, setIsCollapsed] = useState(!expandAll);
useEffect(() => {
setIsCollapsed(!expandAll);
}, [expandAll]);
const hasRuler = useHasRuler();
const rulerRule = group.rules[0]?.rulerRule;

View File

@ -85,30 +85,6 @@ export const getStyles = (theme: GrafanaTheme2) => ({
background-color: ${theme.colors.background.secondary};
border-radius: ${theme.shape.borderRadius()};
`,
table: css`
width: 100%;
border-radius: ${theme.shape.borderRadius()};
border: solid 1px ${theme.colors.border.weak};
background-color: ${theme.colors.background.secondary};
th {
padding: ${theme.spacing(1)};
}
td + td {
padding: ${theme.spacing(0, 1)};
}
tr {
height: 38px;
}
`,
evenRow: css`
background-color: ${theme.colors.background.primary};
`,
state: css`
width: 110px;
`,
});
function useColumns(showSummaryColumn: boolean, showGroupColumn: boolean) {

View File

@ -0,0 +1,49 @@
import { css } from '@emotion/css';
import { dateMath, GrafanaTheme2, intervalToAbbreviatedDurationString } from '@grafana/data';
import React from 'react';
import { useStyles2 } from '@grafana/ui';
import SilencedAlertsTable from './SilencedAlertsTable';
import { SilenceTableItem } from './SilencesTable';
interface Props {
silence: SilenceTableItem;
}
export const SilenceDetails = ({ silence }: Props) => {
const { startsAt, endsAt, comment, createdBy, silencedAlerts } = silence;
const styles = useStyles2(getStyles);
const dateDisplayFormat = 'YYYY-MM-DD HH:mm';
const startsAtDate = dateMath.parse(startsAt);
const endsAtDate = dateMath.parse(endsAt);
const duration = intervalToAbbreviatedDurationString({ start: new Date(startsAt), end: new Date(endsAt) });
return (
<div className={styles.container}>
<div className={styles.title}>Comment</div>
<div>{comment}</div>
<div className={styles.title}>Schedule</div>
<div>{`${startsAtDate?.format(dateDisplayFormat)} - ${endsAtDate?.format(dateDisplayFormat)}`}</div>
<div className={styles.title}>Duration</div>
<div> {duration}</div>
<div className={styles.title}>Created by</div>
<div> {createdBy}</div>
<div className={styles.title}>Affected alerts</div>
<SilencedAlertsTable silencedAlerts={silencedAlerts} />
</div>
);
};
const getStyles = (theme: GrafanaTheme2) => ({
container: css`
display: grid;
grid-template-columns: 1fr 9fr;
grid-row-gap: 1rem;
`,
title: css`
color: ${theme.colors.text.primary};
`,
row: css`
margin: ${theme.spacing(1, 0)};
`,
});

View File

@ -4,7 +4,7 @@ import { CollapseToggle } from '../CollapseToggle';
import { ActionIcon } from '../rules/ActionIcon';
import { getAlertTableStyles } from '../../styles/table';
import { useStyles2 } from '@grafana/ui';
import { dateTimeAsMoment, toDuration } from '@grafana/data';
import { intervalToAbbreviatedDurationString } from '@grafana/data';
import { AlertLabels } from '../AlertLabels';
import { AmAlertStateTag } from './AmAlertStateTag';
@ -16,7 +16,11 @@ interface Props {
export const SilencedAlertsTableRow: FC<Props> = ({ alert, className }) => {
const [isCollapsed, setIsCollapsed] = useState(true);
const tableStyles = useStyles2(getAlertTableStyles);
const alertDuration = toDuration(dateTimeAsMoment(alert.endsAt).diff(alert.startsAt)).asSeconds();
const duration = intervalToAbbreviatedDurationString({
start: new Date(alert.startsAt),
end: new Date(alert.endsAt),
});
const alertName = Object.entries(alert.labels).reduce((name, [labelKey, labelValue]) => {
if (labelKey === 'alertname' || labelKey === '__alert_rule_title__') {
name = labelValue;
@ -32,7 +36,7 @@ export const SilencedAlertsTableRow: FC<Props> = ({ alert, className }) => {
<td>
<AmAlertStateTag state={alert.status.state} />
</td>
<td>for {alertDuration} seconds</td>
<td>for {duration} seconds</td>
<td>{alertName}</td>
<td className={tableStyles.actionsCell}>
<ActionIcon icon="chart-line" to={alert.generatorURL} tooltip="View in explorer" />

View File

@ -208,10 +208,7 @@ export const SilencesEditor: FC<Props> = ({ silence, alertManagerSourceName }) =
error={formState.errors.createdBy?.message}
invalid={!!formState.errors.createdBy}
>
<Input
{...register('createdBy', { required: { value: true, message: 'Required.' } })}
placeholder="Username"
/>
<Input {...register('createdBy', { required: { value: true, message: 'Required.' } })} placeholder="User" />
</Field>
</FieldSet>
<div className={styles.flexRow}>

View File

@ -1,16 +1,29 @@
import React, { FC, useMemo } from 'react';
import { GrafanaTheme2 } from '@grafana/data';
import { GrafanaTheme2, dateMath } from '@grafana/data';
import { Icon, useStyles2, Link, Button } from '@grafana/ui';
import { css } from '@emotion/css';
import { AlertmanagerAlert, Silence, SilenceState } from 'app/plugins/datasource/alertmanager/types';
import SilenceTableRow from './SilenceTableRow';
import { getAlertTableStyles } from '../../styles/table';
import { NoSilencesSplash } from './NoSilencesCTA';
import { getFiltersFromUrlParams, makeAMLink } from '../../utils/misc';
import { getSilenceFiltersFromUrlParams, makeAMLink } from '../../utils/misc';
import { contextSrv } from 'app/core/services/context_srv';
import { useQueryParams } from 'app/core/hooks/useQueryParams';
import { SilencesFilter } from './SilencesFilter';
import { parseMatchers } from '../../utils/alertmanager';
import { DynamicTable, DynamicTableColumnProps, DynamicTableItemProps } from '../DynamicTable';
import { SilenceStateTag } from './SilenceStateTag';
import { Matchers } from './Matchers';
import { ActionButton } from '../rules/ActionButton';
import { ActionIcon } from '../rules/ActionIcon';
import { useDispatch } from 'react-redux';
import { expireSilenceAction } from '../../state/actions';
import { SilenceDetails } from './SilenceDetails';
export interface SilenceTableItem extends Silence {
silencedAlerts: AlertmanagerAlert[];
}
type SilenceTableColumnProps = DynamicTableColumnProps<SilenceTableItem>;
type SilenceTableItemProps = DynamicTableItemProps<SilenceTableItem>;
interface Props {
silences: Silence[];
alertManagerAlerts: AlertmanagerAlert[];
@ -19,18 +32,28 @@ interface Props {
const SilencesTable: FC<Props> = ({ silences, alertManagerAlerts, alertManagerSourceName }) => {
const styles = useStyles2(getStyles);
const tableStyles = useStyles2(getAlertTableStyles);
const [queryParams] = useQueryParams();
const filteredSilences = useFilteredSilences(silences);
const { silenceState } = getFiltersFromUrlParams(queryParams);
const { silenceState } = getSilenceFiltersFromUrlParams(queryParams);
const showExpiredSilencesBanner =
!!filteredSilences.length && (silenceState === undefined || silenceState === SilenceState.Expired);
const findSilencedAlerts = (id: string) => {
return alertManagerAlerts.filter((alert) => alert.status.silencedBy.includes(id));
};
const columns = useColumns(alertManagerSourceName);
const items = useMemo((): SilenceTableItemProps[] => {
const findSilencedAlerts = (id: string) => {
return alertManagerAlerts.filter((alert) => alert.status.silencedBy.includes(id));
};
return filteredSilences.map((silence) => {
const silencedAlerts = findSilencedAlerts(silence.id);
return {
id: silence.id,
data: { ...silence, silencedAlerts },
};
});
}, [filteredSilences, alertManagerAlerts]);
return (
<div data-testid="silences-table">
@ -46,53 +69,23 @@ const SilencesTable: FC<Props> = ({ silences, alertManagerAlerts, alertManagerSo
</Link>
</div>
)}
{!!filteredSilences.length ? (
<table className={tableStyles.table}>
<colgroup>
<col className={tableStyles.colExpand} />
<col className={styles.colState} />
<col className={styles.colMatchers} />
<col />
<col />
{contextSrv.isEditor && <col />}
</colgroup>
<thead>
<tr>
<th />
<th>State</th>
<th>Matching labels</th>
<th>Alerts</th>
<th>Schedule</th>
{contextSrv.isEditor && <th>Action</th>}
</tr>
</thead>
<tbody>
{filteredSilences.map((silence, index) => {
const silencedAlerts = findSilencedAlerts(silence.id);
return (
<SilenceTableRow
key={silence.id}
silence={silence}
className={index % 2 === 0 ? tableStyles.evenRow : undefined}
silencedAlerts={silencedAlerts}
alertManagerSourceName={alertManagerSourceName}
/>
);
})}
</tbody>
</table>
{!!items.length ? (
<>
<DynamicTable
items={items}
cols={columns}
isExpandable
renderExpandedContent={({ data }) => <SilenceDetails silence={data} />}
/>
{showExpiredSilencesBanner && (
<div className={styles.callout}>
<Icon className={styles.calloutIcon} name="info-circle" />
<span>Expired silences are automatically deleted after 5 days.</span>
</div>
)}
</>
) : (
<div className={styles.callout}>
<Icon className={styles.calloutIcon} name="info-circle" />
<span>No silences match your filters</span>
</div>
)}
{showExpiredSilencesBanner && (
<div className={styles.callout}>
<Icon className={styles.calloutIcon} name="info-circle" />
<span>Expired silences are automatically deleted after 5 days.</span>
</div>
'No matching silences found'
)}
</>
)}
@ -104,7 +97,7 @@ const SilencesTable: FC<Props> = ({ silences, alertManagerAlerts, alertManagerSo
const useFilteredSilences = (silences: Silence[]) => {
const [queryParams] = useQueryParams();
return useMemo(() => {
const { queryString, silenceState } = getFiltersFromUrlParams(queryParams);
const { queryString, silenceState } = getSilenceFiltersFromUrlParams(queryParams);
const silenceIdsString = queryParams?.silenceIds;
return silences.filter((silence) => {
if (typeof silenceIdsString === 'string') {
@ -148,12 +141,6 @@ const getStyles = (theme: GrafanaTheme2) => ({
addNewSilence: css`
margin: ${theme.spacing(2, 0)};
`,
colState: css`
width: 110px;
`,
colMatchers: css`
width: 50%;
`,
callout: css`
background-color: ${theme.colors.background.secondary};
border-top: 3px solid ${theme.colors.info.border};
@ -171,6 +158,95 @@ const getStyles = (theme: GrafanaTheme2) => ({
calloutIcon: css`
color: ${theme.colors.info.text};
`,
editButton: css`
margin-left: ${theme.spacing(0.5)};
`,
});
function useColumns(alertManagerSourceName: string) {
const dispatch = useDispatch();
const styles = useStyles2(getStyles);
return useMemo((): SilenceTableColumnProps[] => {
const handleExpireSilenceClick = (id: string) => {
dispatch(expireSilenceAction(alertManagerSourceName, id));
};
const showActions = contextSrv.isEditor;
const columns: SilenceTableColumnProps[] = [
{
id: 'state',
label: 'State',
renderCell: function renderStateTag({ data: { status } }) {
return <SilenceStateTag state={status.state} />;
},
size: '88px',
},
{
id: 'matchers',
label: 'Matching labels',
renderCell: function renderMatchers({ data: { matchers } }) {
return <Matchers matchers={matchers || []} />;
},
size: 9,
},
{
id: 'alerts',
label: 'Alerts',
renderCell: function renderSilencedAlerts({ data: { silencedAlerts } }) {
return <span data-testid="alerts">{silencedAlerts.length}</span>;
},
size: 1,
},
{
id: 'schedule',
label: 'Schedule',
renderCell: function renderSchedule({ data: { startsAt, endsAt } }) {
const startsAtDate = dateMath.parse(startsAt);
const endsAtDate = dateMath.parse(endsAt);
const dateDisplayFormat = 'YYYY-MM-DD HH:mm';
return (
<>
{' '}
{startsAtDate?.format(dateDisplayFormat)} {'-'}
<br />
{endsAtDate?.format(dateDisplayFormat)}
</>
);
},
size: '150px',
},
];
if (showActions) {
columns.push({
id: 'actions',
label: 'Actions',
renderCell: function renderActions({ data: silence }) {
return (
<>
{silence.status.state === 'expired' ? (
<Link href={makeAMLink(`/alerting/silence/${silence.id}/edit`, alertManagerSourceName)}>
<ActionButton icon="sync">Recreate</ActionButton>
</Link>
) : (
<ActionButton icon="bell" onClick={() => handleExpireSilenceClick(silence.id)}>
Unsilence
</ActionButton>
)}
{silence.status.state !== 'expired' && (
<ActionIcon
className={styles.editButton}
to={makeAMLink(`/alerting/silence/${silence.id}/edit`, alertManagerSourceName)}
icon="pen"
tooltip="edit"
/>
)}
</>
);
},
size: '140px',
});
}
return columns;
}, [alertManagerSourceName, dispatch, styles]);
}
export default SilencesTable;

View File

@ -14,9 +14,6 @@ export const useFilteredRules = (namespaces: CombinedRuleNamespace[]) => {
const filters = getFiltersFromUrlParams(queryParams);
return useMemo(() => {
if (!filters.queryString && !filters.dataSource && !filters.alertState) {
return namespaces;
}
const filteredNamespaces = namespaces
// Filter by data source
// TODO: filter by multiple data sources for grafana-managed alerts
@ -48,6 +45,9 @@ const reduceNamespaces = (filters: FilterState) => {
const reduceGroups = (filters: FilterState) => {
return (groupAcc: CombinedRuleGroup[], group: CombinedRuleGroup) => {
const rules = group.rules.filter((rule) => {
if (filters.ruleType && filters.ruleType !== rule.promRule?.type) {
return false;
}
if (filters.dataSource && isGrafanaRulerRule(rule.rulerRule) && !isQueryingDataSource(rule.rulerRule, filters)) {
return false;
}

View File

@ -37,9 +37,9 @@ export const getFiltersFromUrlParams = (queryParams: UrlQueryMap): FilterState =
const queryString = queryParams['queryString'] === undefined ? undefined : String(queryParams['queryString']);
const alertState = queryParams['alertState'] === undefined ? undefined : String(queryParams['alertState']);
const dataSource = queryParams['dataSource'] === undefined ? undefined : String(queryParams['dataSource']);
const ruleType = queryParams['ruleType'] === undefined ? undefined : String(queryParams['ruleType']);
const groupBy = queryParams['groupBy'] === undefined ? undefined : String(queryParams['groupBy']).split(',');
const silenceState = queryParams['silenceState'] === undefined ? undefined : String(queryParams['silenceState']);
return { queryString, alertState, dataSource, groupBy, silenceState };
return { queryString, alertState, dataSource, groupBy, ruleType };
};
export const getSilenceFiltersFromUrlParams = (queryParams: UrlQueryMap): SilenceFilterState => {

View File

@ -133,7 +133,7 @@ export interface FilterState {
dataSource?: string;
alertState?: string;
groupBy?: string[];
silenceState?: string;
ruleType?: string;
}
export interface SilenceFilterState {