Commit 2c2869a0 by Peter Holmberg Committed by GitHub

AlertingNG: List saved Alert definitions in Alert Rule list (#30603)

* fetch alert definitions

* add new card for ng definitions

* get alerts from selector

* fix tests

* replace ol/li with verticalgroup
parent 10aabe8c
{ {
"npmClient": "yarn", "npmClient": "yarn",
"useWorkspaces": true, "useWorkspaces": true,
"packages": [ "packages": ["packages/*"],
"packages/*"
],
"version": "7.5.0-pre.0" "version": "7.5.0-pre.0"
} }
import React, { useCallback } from 'react'; import React, { useCallback } from 'react';
// @ts-ignore // @ts-ignore
import Highlighter from 'react-highlight-words'; import Highlighter from 'react-highlight-words';
import { css } from 'emotion';
import { Icon, IconName, Button, LinkButton, Card } from '@grafana/ui'; import { Icon, IconName, Button, LinkButton, Card } from '@grafana/ui';
import { AlertRule } from '../../types'; import { AlertRule } from '../../types';
...@@ -26,39 +25,33 @@ const AlertRuleItem = ({ rule, search, onTogglePause }: Props) => { ...@@ -26,39 +25,33 @@ const AlertRuleItem = ({ rule, search, onTogglePause }: Props) => {
); );
return ( return (
<li <Card heading={<a href={ruleUrl}>{renderText(rule.name)}</a>}>
className={css` <Card.Figure>
width: 100%; <Icon size="xl" name={rule.stateIcon as IconName} className={`alert-rule-item__icon ${rule.stateClass}`} />
`} </Card.Figure>
> <Card.Meta>
<Card heading={<a href={ruleUrl}>{renderText(rule.name)}</a>}> <span key="state">
<Card.Figure> <span key="text" className={`${rule.stateClass}`}>
<Icon size="xl" name={rule.stateIcon as IconName} className={`alert-rule-item__icon ${rule.stateClass}`} /> {renderText(rule.stateText)}{' '}
</Card.Figure>
<Card.Meta>
<span key="state">
<span key="text" className={`${rule.stateClass}`}>
{renderText(rule.stateText)}{' '}
</span>
for {rule.stateAge}
</span> </span>
{rule.info ? renderText(rule.info) : null} for {rule.stateAge}
</Card.Meta> </span>
<Card.Actions> {rule.info ? renderText(rule.info) : null}
<Button </Card.Meta>
key="play" <Card.Actions>
variant="secondary" <Button
icon={rule.state === 'paused' ? 'play' : 'pause'} key="play"
onClick={onTogglePause} variant="secondary"
> icon={rule.state === 'paused' ? 'play' : 'pause'}
{rule.state === 'paused' ? 'Resume' : 'Pause'} onClick={onTogglePause}
</Button> >
<LinkButton key="edit" variant="secondary" href={ruleUrl} icon="cog"> {rule.state === 'paused' ? 'Resume' : 'Pause'}
Edit alert </Button>
</LinkButton> <LinkButton key="edit" variant="secondary" href={ruleUrl} icon="cog">
</Card.Actions> Edit alert
</Card> </LinkButton>
</li> </Card.Actions>
</Card>
); );
}; };
......
...@@ -6,17 +6,18 @@ import AlertRuleItem from './AlertRuleItem'; ...@@ -6,17 +6,18 @@ import AlertRuleItem from './AlertRuleItem';
import appEvents from 'app/core/app_events'; import appEvents from 'app/core/app_events';
import { updateLocation } from 'app/core/actions'; import { updateLocation } from 'app/core/actions';
import { getNavModel } from 'app/core/selectors/navModel'; import { getNavModel } from 'app/core/selectors/navModel';
import { AlertRule, CoreEvents, StoreState } from 'app/types'; import { AlertDefinition, AlertRule, CoreEvents, StoreState } from 'app/types';
import { getAlertRulesAsync, togglePauseAlertRule } from './state/actions'; import { getAlertRulesAsync, togglePauseAlertRule } from './state/actions';
import { getAlertRuleItems, getSearchQuery } from './state/selectors'; import { getAlertRuleItems, getSearchQuery } from './state/selectors';
import { FilterInput } from 'app/core/components/FilterInput/FilterInput'; import { FilterInput } from 'app/core/components/FilterInput/FilterInput';
import { NavModel, SelectableValue } from '@grafana/data'; import { NavModel, SelectableValue } from '@grafana/data';
import { setSearchQuery } from './state/reducers'; import { setSearchQuery } from './state/reducers';
import { Button, Select } from '@grafana/ui'; import { Button, Select, VerticalGroup } from '@grafana/ui';
import { AlertDefinitionItem } from './components/AlertDefinitionItem';
export interface Props { export interface Props {
navModel: NavModel; navModel: NavModel;
alertRules: AlertRule[]; alertRules: Array<AlertRule | AlertDefinition>;
updateLocation: typeof updateLocation; updateLocation: typeof updateLocation;
getAlertRulesAsync: typeof getAlertRulesAsync; getAlertRulesAsync: typeof getAlertRulesAsync;
setSearchQuery: typeof setSearchQuery; setSearchQuery: typeof setSearchQuery;
...@@ -121,18 +122,28 @@ export class AlertRuleList extends PureComponent<Props, any> { ...@@ -121,18 +122,28 @@ export class AlertRuleList extends PureComponent<Props, any> {
How to add an alert How to add an alert
</Button> </Button>
</div> </div>
<section> <VerticalGroup spacing="none">
<ol className="alert-rule-list"> {alertRules.map((rule, index) => {
{alertRules.map((rule) => ( // Alert definition has "title" as name property.
<AlertRuleItem if (rule.hasOwnProperty('name')) {
rule={rule} return (
key={rule.id} <AlertRuleItem
rule={rule as AlertRule}
key={rule.id}
search={search}
onTogglePause={() => this.onTogglePause(rule as AlertRule)}
/>
);
}
return (
<AlertDefinitionItem
key={`${rule.id}-${index}`}
alertDefinition={rule as AlertDefinition}
search={search} search={search}
onTogglePause={() => this.onTogglePause(rule)}
/> />
))} );
</ol> })}
</section> </VerticalGroup>
</Page.Contents> </Page.Contents>
</Page> </Page>
); );
...@@ -141,10 +152,11 @@ export class AlertRuleList extends PureComponent<Props, any> { ...@@ -141,10 +152,11 @@ export class AlertRuleList extends PureComponent<Props, any> {
const mapStateToProps = (state: StoreState) => ({ const mapStateToProps = (state: StoreState) => ({
navModel: getNavModel(state.navIndex, 'alert-list'), navModel: getNavModel(state.navIndex, 'alert-list'),
alertRules: getAlertRuleItems(state.alertRules), alertRules: getAlertRuleItems(state),
stateFilter: state.location.query.state, stateFilter: state.location.query.state,
search: getSearchQuery(state.alertRules), search: getSearchQuery(state.alertRules),
isLoading: state.alertRules.isLoading, isLoading: state.alertRules.isLoading,
ngAlertDefinitions: state.alertDefinition.alertDefinitions,
}); });
const mapDispatchToProps = { const mapDispatchToProps = {
......
...@@ -162,13 +162,10 @@ export default hot(module)( ...@@ -162,13 +162,10 @@ export default hot(module)(
const getStyles = stylesFactory((theme: GrafanaTheme) => ({ const getStyles = stylesFactory((theme: GrafanaTheme) => ({
wrapper: css` wrapper: css`
width: 100%; width: calc(100% - 55px);
height: 100%; height: 100%;
position: fixed; position: fixed;
z-index: ${theme.zIndex.sidemenu};
top: 0; top: 0;
left: 0;
right: 0;
bottom: 0; bottom: 0;
background: ${theme.colors.dashboardBg}; background: ${theme.colors.dashboardBg};
display: flex; display: flex;
......
...@@ -80,54 +80,52 @@ exports[`Render should render alert rules 1`] = ` ...@@ -80,54 +80,52 @@ exports[`Render should render alert rules 1`] = `
How to add an alert How to add an alert
</Button> </Button>
</div> </div>
<section> <VerticalGroup
<ol spacing="none"
className="alert-rule-list" >
> <AlertRuleItem
<AlertRuleItem key="1"
key="1" onTogglePause={[Function]}
onTogglePause={[Function]} rule={
rule={ Object {
Object { "dashboardId": 7,
"dashboardId": 7, "dashboardSlug": "alerting-with-testdata",
"dashboardSlug": "alerting-with-testdata", "dashboardUid": "ggHbN42mk",
"dashboardUid": "ggHbN42mk", "evalData": Object {},
"evalData": Object {}, "evalDate": "0001-01-01T00:00:00Z",
"evalDate": "0001-01-01T00:00:00Z", "executionError": "",
"executionError": "", "id": 1,
"id": 1, "name": "TestData - Always OK",
"name": "TestData - Always OK", "newStateDate": "2018-09-04T10:01:01+02:00",
"newStateDate": "2018-09-04T10:01:01+02:00", "panelId": 3,
"panelId": 3, "state": "ok",
"state": "ok", "url": "/d/ggHbN42mk/alerting-with-testdata",
"url": "/d/ggHbN42mk/alerting-with-testdata",
}
} }
search="" }
/> search=""
<AlertRuleItem />
key="3" <AlertRuleItem
onTogglePause={[Function]} key="3"
rule={ onTogglePause={[Function]}
Object { rule={
"dashboardId": 7, Object {
"dashboardSlug": "alerting-with-testdata", "dashboardId": 7,
"dashboardUid": "ggHbN42mk", "dashboardSlug": "alerting-with-testdata",
"evalData": Object {}, "dashboardUid": "ggHbN42mk",
"evalDate": "0001-01-01T00:00:00Z", "evalData": Object {},
"executionError": "error", "evalDate": "0001-01-01T00:00:00Z",
"id": 3, "executionError": "error",
"name": "TestData - ok", "id": 3,
"newStateDate": "2018-09-04T10:01:01+02:00", "name": "TestData - ok",
"panelId": 3, "newStateDate": "2018-09-04T10:01:01+02:00",
"state": "ok", "panelId": 3,
"url": "/d/ggHbN42mk/alerting-with-testdata", "state": "ok",
} "url": "/d/ggHbN42mk/alerting-with-testdata",
} }
search="" }
/> search=""
</ol> />
</section> </VerticalGroup>
</PageContents> </PageContents>
</Page> </Page>
`; `;
...@@ -212,11 +210,9 @@ exports[`Render should render component 1`] = ` ...@@ -212,11 +210,9 @@ exports[`Render should render component 1`] = `
How to add an alert How to add an alert
</Button> </Button>
</div> </div>
<section> <VerticalGroup
<ol spacing="none"
className="alert-rule-list" />
/>
</section>
</PageContents> </PageContents>
</Page> </Page>
`; `;
import React, { FC } from 'react';
// @ts-ignore
import Highlighter from 'react-highlight-words';
import { Card, FeatureBadge, Icon } from '@grafana/ui';
import { AlertDefinition } from 'app/types';
import { FeatureState } from '@grafana/data';
interface Props {
alertDefinition: AlertDefinition;
search: string;
}
export const AlertDefinitionItem: FC<Props> = ({ alertDefinition, search }) => {
return (
<Card heading={CardTitle(alertDefinition.title, search)}>
<Card.Figure>
<Icon size="xl" name="question-circle" className="alert-rule-item__icon" />
</Card.Figure>
<Card.Meta>
<span key="state">
<span key="text">{alertDefinition.description}</span>
</span>
</Card.Meta>
</Card>
);
};
const CardTitle = (title: string, search: string) => (
<div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
<Highlighter
key={title}
highlightClassName="highlight-search-match"
textToHighlight={title}
searchWords={[search]}
/>
<FeatureBadge featureState={FeatureState.beta} />
</div>
);
import { AppEvents, dateMath } from '@grafana/data'; import { AppEvents, dateMath } from '@grafana/data';
import { getBackendSrv, getDataSourceSrv } from '@grafana/runtime'; import { config, getBackendSrv, getDataSourceSrv } from '@grafana/runtime';
import { appEvents } from 'app/core/core'; import { appEvents } from 'app/core/core';
import { updateLocation } from 'app/core/actions'; import { updateLocation } from 'app/core/actions';
import store from 'app/core/store'; import store from 'app/core/store';
...@@ -12,6 +12,7 @@ import { ...@@ -12,6 +12,7 @@ import {
ALERT_DEFINITION_UI_STATE_STORAGE_KEY, ALERT_DEFINITION_UI_STATE_STORAGE_KEY,
updateAlertDefinition, updateAlertDefinition,
setQueryOptions, setQueryOptions,
setAlertDefinitions,
} from './reducers'; } from './reducers';
import { import {
AlertDefinition, AlertDefinition,
...@@ -29,6 +30,12 @@ export function getAlertRulesAsync(options: { state: string }): ThunkResult<void ...@@ -29,6 +30,12 @@ export function getAlertRulesAsync(options: { state: string }): ThunkResult<void
return async (dispatch) => { return async (dispatch) => {
dispatch(loadAlertRules()); dispatch(loadAlertRules());
const rules: AlertRuleDTO[] = await getBackendSrv().get('/api/alerts', options); const rules: AlertRuleDTO[] = await getBackendSrv().get('/api/alerts', options);
if (config.featureToggles.ngalert) {
const ngAlertDefinitions = await getBackendSrv().get('/api/alert-definitions');
dispatch(setAlertDefinitions(ngAlertDefinitions.results));
}
dispatch(loadedAlertRules(rules)); dispatch(loadedAlertRules(rules));
}; };
} }
......
...@@ -63,6 +63,7 @@ export const initialAlertDefinitionState: AlertDefinitionState = { ...@@ -63,6 +63,7 @@ export const initialAlertDefinitionState: AlertDefinitionState = {
queryRunner: new PanelQueryRunner(dataConfig), queryRunner: new PanelQueryRunner(dataConfig),
uiState: { ...store.getObject(ALERT_DEFINITION_UI_STATE_STORAGE_KEY, DEFAULT_ALERT_DEFINITION_UI_STATE) }, uiState: { ...store.getObject(ALERT_DEFINITION_UI_STATE_STORAGE_KEY, DEFAULT_ALERT_DEFINITION_UI_STATE) },
data: [], data: [],
alertDefinitions: [] as AlertDefinition[],
}; };
function convertToAlertRule(dto: AlertRuleDTO, state: string): AlertRule { function convertToAlertRule(dto: AlertRuleDTO, state: string): AlertRule {
...@@ -170,6 +171,9 @@ const alertDefinitionSlice = createSlice({ ...@@ -170,6 +171,9 @@ const alertDefinitionSlice = createSlice({
queryOptions: action.payload, queryOptions: action.payload,
}; };
}, },
setAlertDefinitions: (state: AlertDefinitionState, action: PayloadAction<AlertDefinition[]>) => {
return { ...state, alertDefinitions: action.payload };
},
}, },
}); });
...@@ -181,7 +185,7 @@ export const { ...@@ -181,7 +185,7 @@ export const {
resetSecureField, resetSecureField,
} = notificationChannelSlice.actions; } = notificationChannelSlice.actions;
export const { setUiState, updateAlertDefinition, setQueryOptions } = alertDefinitionSlice.actions; export const { setUiState, updateAlertDefinition, setQueryOptions, setAlertDefinitions } = alertDefinitionSlice.actions;
export const alertRulesReducer = alertRulesSlice.reducer; export const alertRulesReducer = alertRulesSlice.reducer;
export const notificationChannelReducer = notificationChannelSlice.reducer; export const notificationChannelReducer = notificationChannelSlice.reducer;
......
...@@ -12,21 +12,23 @@ describe('Get search query', () => { ...@@ -12,21 +12,23 @@ describe('Get search query', () => {
describe('Get alert rule items', () => { describe('Get alert rule items', () => {
it('should get alert rule items', () => { it('should get alert rule items', () => {
const state = { const state = {
items: [ alertRules: {
{ items: [
id: 1, {
dashboardId: 1, id: 1,
panelId: 1, dashboardId: 1,
name: '', panelId: 1,
state: '', name: '',
stateText: '', state: '',
stateIcon: '', stateText: '',
stateClass: '', stateIcon: '',
stateAge: '', stateClass: '',
url: '', stateAge: '',
}, url: '',
], },
searchQuery: '', ],
searchQuery: '',
},
}; };
const result = getAlertRuleItems(state as any); const result = getAlertRuleItems(state as any);
...@@ -35,57 +37,59 @@ describe('Get alert rule items', () => { ...@@ -35,57 +37,59 @@ describe('Get alert rule items', () => {
it('should filter rule items based on search query', () => { it('should filter rule items based on search query', () => {
const state = { const state = {
items: [ alertRules: {
{ items: [
id: 1, {
dashboardId: 1, id: 1,
panelId: 1, dashboardId: 1,
name: 'dashboard', panelId: 1,
state: '', name: 'dashboard',
stateText: '', state: '',
stateIcon: '', stateText: '',
stateClass: '', stateIcon: '',
stateAge: '', stateClass: '',
url: '', stateAge: '',
}, url: '',
{ },
id: 2, {
dashboardId: 3, id: 2,
panelId: 1, dashboardId: 3,
name: 'dashboard2', panelId: 1,
state: '', name: 'dashboard2',
stateText: '', state: '',
stateIcon: '', stateText: '',
stateClass: '', stateIcon: '',
stateAge: '', stateClass: '',
url: '', stateAge: '',
}, url: '',
{ },
id: 3, {
dashboardId: 5, id: 3,
panelId: 1, dashboardId: 5,
name: 'hello', panelId: 1,
state: '', name: 'hello',
stateText: '', state: '',
stateIcon: '', stateText: '',
stateClass: '', stateIcon: '',
stateAge: '', stateClass: '',
url: '', stateAge: '',
}, url: '',
{ },
id: 4, {
dashboardId: 7, id: 4,
panelId: 1, dashboardId: 7,
name: 'test', panelId: 1,
state: '', name: 'test',
stateText: 'dashboard', state: '',
stateIcon: '', stateText: 'dashboard',
stateClass: '', stateIcon: '',
stateAge: '', stateClass: '',
url: '', stateAge: '',
}, url: '',
], },
searchQuery: 'dashboard', ],
searchQuery: 'dashboard',
},
}; };
const result = getAlertRuleItems(state as any); const result = getAlertRuleItems(state as any);
......
import { AlertRulesState, NotificationChannelState } from 'app/types'; import { AlertDefinition, AlertRule, AlertRulesState, NotificationChannelState, StoreState } from 'app/types';
import { config } from '@grafana/runtime';
export const getSearchQuery = (state: AlertRulesState) => state.searchQuery; export const getSearchQuery = (state: AlertRulesState) => state.searchQuery;
export const getAlertRuleItems = (state: AlertRulesState) => { export const getAlertRuleItems = (state: StoreState) => {
const regex = new RegExp(state.searchQuery, 'i'); const regex = new RegExp(state.alertRules.searchQuery, 'i');
const result: Array<AlertRule | AlertDefinition> = [];
return state.items.filter((item) => { result.push(
return regex.test(item.name) || regex.test(item.stateText) || regex.test(item.info!); ...state.alertRules.items.filter((item) => {
}); return regex.test(item.name) || regex.test(item.stateText) || regex.test(item.info!);
})
);
if (config.featureToggles.ngalert) {
result.push(
...state.alertDefinition.alertDefinitions.filter((item) => {
return regex.test(item.title);
})
);
}
return result;
}; };
export const getNotificationChannel = (state: NotificationChannelState, channelId: number) => { export const getNotificationChannel = (state: NotificationChannelState, channelId: number) => {
......
...@@ -142,6 +142,7 @@ export interface AlertDefinitionState { ...@@ -142,6 +142,7 @@ export interface AlertDefinitionState {
queryOptions: QueryGroupOptions; queryOptions: QueryGroupOptions;
queryRunner: PanelQueryRunner; queryRunner: PanelQueryRunner;
data: PanelData[]; data: PanelData[];
alertDefinitions: AlertDefinition[];
} }
export interface AlertDefinition { export interface AlertDefinition {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment