Skip to content

Commit

Permalink
[RAC] ALerts table in observability (#103270)
Browse files Browse the repository at this point in the history
Closes #98611

## Summary

Add alerts table in Observability => 

![image](https://user-images.githubusercontent.com/189600/123854490-c68ddf00-d8ec-11eb-897e-2217249d5fba.png)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to identify risks that should be tested prior to the change/feature release.

When forming the risk matrix, consider some of the following examples and how they may potentially impact the change:

| Risk                      | Probability | Severity | Mitigation/Notes        |
|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces—unexpected behavior in non-default Kibana Space. | Low | High | Integration tests will verify that all features are still supported in non-default Kibana Space and when user switches between spaces. |
| Multiple nodes—Elasticsearch polling might have race conditions when multiple Kibana nodes are polling for the same tasks. | High | Low | Tasks are idempotent, so executing them multiple times will not result in logical error, but will degrade performance. To test for this case we add plenty of unit tests around this logic and document manual testing procedure. |
| Code should gracefully handle cases when feature X or plugin Y are disabled. | Medium | High | Unit tests will verify that any feature flag or plugin combination still results in our service operational. |
| [See more potential risk examples](https://github.com/elastic/kibana/blob/master/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)
  • Loading branch information
XavierM authored Jul 6, 2021
1 parent 5b49380 commit cf9e88c
Show file tree
Hide file tree
Showing 23 changed files with 652 additions and 173 deletions.
1 change: 1 addition & 0 deletions x-pack/plugins/observability/kibana.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"data",
"features",
"ruleRegistry",
"timelines",
"triggersActionsUi"
],
"ui": true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 +31,23 @@ import {
} from '@kbn/rule-data-utils/target/technical_field_names';
import moment from 'moment-timezone';
import React, { useMemo } from 'react';
import type { TopAlertResponse } from '../';
import type { TopAlert, TopAlertResponse } from '../';
import { useKibana, useUiSetting } from '../../../../../../../src/plugins/kibana_react/public';
import { asDuration } from '../../../../common/utils/formatters';
import type { ObservabilityRuleTypeRegistry } from '../../../rules/create_observability_rule_type_registry';
import { decorateResponse } from '../decorate_response';
import { SeverityBadge } from '../severity_badge';

type AlertsFlyoutProps = {
alert?: TopAlert;
alerts?: TopAlertResponse[];
isInApp?: boolean;
observabilityRuleTypeRegistry: ObservabilityRuleTypeRegistry;
selectedAlertId?: string;
} & EuiFlyoutProps;

export function AlertsFlyout({
alert,
alerts,
isInApp = false,
observabilityRuleTypeRegistry,
Expand All @@ -59,9 +61,12 @@ export function AlertsFlyout({
const decoratedAlerts = useMemo(() => {
return decorateResponse(alerts ?? [], observabilityRuleTypeRegistry);
}, [alerts, observabilityRuleTypeRegistry]);
const alert = decoratedAlerts?.find((a) => a.fields[ALERT_UUID] === selectedAlertId);

if (!alert) {
let alertData = alert;
if (!alertData) {
alertData = decoratedAlerts?.find((a) => a.fields[ALERT_UUID] === selectedAlertId);
}
if (!alertData) {
return null;
}

Expand All @@ -70,56 +75,56 @@ export function AlertsFlyout({
title: i18n.translate('xpack.observability.alertsFlyout.statusLabel', {
defaultMessage: 'Status',
}),
description: alert.active ? 'Active' : 'Recovered',
description: alertData.active ? 'Active' : 'Recovered',
},
{
title: i18n.translate('xpack.observability.alertsFlyout.severityLabel', {
defaultMessage: 'Severity',
}),
description: <SeverityBadge severityLevel={alert.fields[ALERT_SEVERITY_LEVEL]} />,
description: <SeverityBadge severityLevel={alertData.fields[ALERT_SEVERITY_LEVEL]} />,
},
{
title: i18n.translate('xpack.observability.alertsFlyout.triggeredLabel', {
defaultMessage: 'Triggered',
}),
description: (
<span title={alert.start.toString()}>{moment(alert.start).format(dateFormat)}</span>
<span title={alertData.start.toString()}>{moment(alertData.start).format(dateFormat)}</span>
),
},
{
title: i18n.translate('xpack.observability.alertsFlyout.durationLabel', {
defaultMessage: 'Duration',
}),
description: asDuration(alert.fields[ALERT_DURATION], { extended: true }),
description: asDuration(alertData.fields[ALERT_DURATION], { extended: true }),
},
{
title: i18n.translate('xpack.observability.alertsFlyout.expectedValueLabel', {
defaultMessage: 'Expected value',
}),
description: alert.fields[ALERT_EVALUATION_THRESHOLD] ?? '-',
description: alertData.fields[ALERT_EVALUATION_THRESHOLD] ?? '-',
},
{
title: i18n.translate('xpack.observability.alertsFlyout.actualValueLabel', {
defaultMessage: 'Actual value',
}),
description: alert.fields[ALERT_EVALUATION_VALUE] ?? '-',
description: alertData.fields[ALERT_EVALUATION_VALUE] ?? '-',
},
{
title: i18n.translate('xpack.observability.alertsFlyout.ruleTypeLabel', {
defaultMessage: 'Rule type',
}),
description: alert.fields[RULE_CATEGORY] ?? '-',
description: alertData.fields[RULE_CATEGORY] ?? '-',
},
];

return (
<EuiFlyout onClose={onClose} size="s">
<EuiFlyoutHeader>
<EuiTitle size="m">
<h2>{alert.fields[RULE_NAME]}</h2>
<h2>{alertData.fields[RULE_NAME]}</h2>
</EuiTitle>
<EuiSpacer size="s" />
<EuiText size="s">{alert.reason}</EuiText>
<EuiText size="s">{alertData.reason}</EuiText>
</EuiFlyoutHeader>
<EuiFlyoutBody>
<EuiSpacer size="s" />
Expand All @@ -129,11 +134,11 @@ export function AlertsFlyout({
listItems={overviewListItems}
/>
</EuiFlyoutBody>
{alert.link && !isInApp && (
{alertData.link && !isInApp && (
<EuiFlyoutFooter>
<EuiFlexGroup justifyContent="flexEnd">
<EuiFlexItem grow={false}>
<EuiButton href={prepend && prepend(alert.link)} fill>
<EuiButton href={prepend && prepend(alertData.link)} fill>
View in app
</EuiButton>
</EuiFlexItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@

import { i18n } from '@kbn/i18n';
import React, { useMemo, useState } from 'react';
import { SearchBar, TimeHistory } from '../../../../../../src/plugins/data/public';
import { IIndexPattern, SearchBar, TimeHistory } from '../../../../../../src/plugins/data/public';
import { Storage } from '../../../../../../src/plugins/kibana_utils/public';
import { useFetcher } from '../../hooks/use_fetcher';
import { callObservabilityApi } from '../../services/call_observability_api';

export function AlertsSearchBar({
dynamicIndexPattern,
rangeFrom,
rangeTo,
onQueryChange,
query,
}: {
dynamicIndexPattern: IIndexPattern[];
rangeFrom?: string;
rangeTo?: string;
query?: string;
Expand All @@ -31,16 +31,9 @@ export function AlertsSearchBar({
}, []);
const [queryLanguage, setQueryLanguage] = useState<'lucene' | 'kuery'>('kuery');

const { data: dynamicIndexPattern } = useFetcher(({ signal }) => {
return callObservabilityApi({
signal,
endpoint: 'GET /api/observability/rules/alerts/dynamic_index_pattern',
});
}, []);

return (
<SearchBar
indexPatterns={dynamicIndexPattern ? [dynamicIndexPattern] : []}
indexPatterns={dynamicIndexPattern}
placeholder={i18n.translate('xpack.observability.alerts.searchBarPlaceholder', {
defaultMessage: '"domain": "ecommerce" AND ("service.name": "ProductCatalogService" …)',
})}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { EuiButtonIcon, EuiDataGridColumn } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import React, { Suspense, useState } from 'react';
import {
ALERT_DURATION,
ALERT_SEVERITY_LEVEL,
ALERT_STATUS,
ALERT_START,
RULE_NAME,
} from '@kbn/rule-data-utils/target/technical_field_names';

import type { TimelinesUIStart } from '../../../../timelines/public';
import type { TopAlert } from './';
import { useKibana } from '../../../../../../src/plugins/kibana_react/public';
import type { ActionProps, ColumnHeaderOptions, RowRenderer } from '../../../../timelines/common';
import { getRenderCellValue } from './render_cell_value';
import { usePluginContext } from '../../hooks/use_plugin_context';
import { decorateResponse } from './decorate_response';
import { LazyAlertsFlyout } from '../..';

interface AlertsTableTGridProps {
indexName: string;
rangeFrom: string;
rangeTo: string;
kuery: string;
status: string;
setRefetch: (ref: () => void) => void;
}

/**
* columns implements a subset of `EuiDataGrid`'s `EuiDataGridColumn` interface,
* plus additional TGrid column properties
*/
export const columns: Array<
Pick<EuiDataGridColumn, 'display' | 'displayAsText' | 'id' | 'initialWidth'> & ColumnHeaderOptions
> = [
{
columnHeaderType: 'not-filtered',
displayAsText: i18n.translate('xpack.observability.alertsTGrid.statusColumnDescription', {
defaultMessage: 'Status',
}),
id: ALERT_STATUS,
initialWidth: 79,
},
{
columnHeaderType: 'not-filtered',
displayAsText: i18n.translate('xpack.observability.alertsTGrid.triggeredColumnDescription', {
defaultMessage: 'Triggered',
}),
id: ALERT_START,
initialWidth: 116,
},
{
columnHeaderType: 'not-filtered',
displayAsText: i18n.translate('xpack.observability.alertsTGrid.durationColumnDescription', {
defaultMessage: 'Duration',
}),
id: ALERT_DURATION,
initialWidth: 116,
},
{
columnHeaderType: 'not-filtered',
displayAsText: i18n.translate('xpack.observability.alertsTGrid.severityColumnDescription', {
defaultMessage: 'Severity',
}),
id: ALERT_SEVERITY_LEVEL,
initialWidth: 102,
},
{
columnHeaderType: 'not-filtered',
displayAsText: i18n.translate('xpack.observability.alertsTGrid.reasonColumnDescription', {
defaultMessage: 'Reason',
}),
linkField: '*',
id: RULE_NAME,
initialWidth: 400,
},
];

const NO_ROW_RENDER: RowRenderer[] = [];

const trailingControlColumns: never[] = [];

export function AlertsTableTGrid(props: AlertsTableTGridProps) {
const { core, observabilityRuleTypeRegistry } = usePluginContext();
const { prepend } = core.http.basePath;
const { indexName, rangeFrom, rangeTo, kuery, status, setRefetch } = props;
const [flyoutAlert, setFlyoutAlert] = useState<TopAlert | undefined>(undefined);
const handleFlyoutClose = () => setFlyoutAlert(undefined);
const { timelines } = useKibana<{ timelines: TimelinesUIStart }>().services;

const leadingControlColumns = [
{
id: 'expand',
width: 40,
headerCellRender: () => null,
rowCellRender: ({ data }: ActionProps) => {
const dataFieldEs = data.reduce((acc, d) => ({ ...acc, [d.field]: d.value }), {});
const decoratedAlerts = decorateResponse(
[dataFieldEs] ?? [],
observabilityRuleTypeRegistry
);
const alert = decoratedAlerts[0];
return (
<EuiButtonIcon
size="s"
iconType="expand"
color="text"
onClick={() => setFlyoutAlert(alert)}
/>
);
},
},
{
id: 'view_in_app',
width: 40,
headerCellRender: () => null,
rowCellRender: ({ data }: ActionProps) => {
const dataFieldEs = data.reduce((acc, d) => ({ ...acc, [d.field]: d.value }), {});
const decoratedAlerts = decorateResponse(
[dataFieldEs] ?? [],
observabilityRuleTypeRegistry
);
const alert = decoratedAlerts[0];
return (
<EuiButtonIcon
size="s"
target="_blank"
rel="nofollow noreferrer"
href={prepend(alert.link ?? '')}
iconType="inspect"
color="text"
/>
);
},
},
];

return (
<>
{flyoutAlert && (
<Suspense fallback={null}>
<LazyAlertsFlyout
alert={flyoutAlert}
observabilityRuleTypeRegistry={observabilityRuleTypeRegistry}
onClose={handleFlyoutClose}
/>
</Suspense>
)}
{timelines.getTGrid<'standalone'>({
type: 'standalone',
columns,
deletedEventIds: [],
end: rangeTo,
filters: [],
indexNames: [indexName],
itemsPerPage: 10,
itemsPerPageOptions: [10, 25, 50],
loadingText: i18n.translate('xpack.observability.alertsTable.loadingTextLabel', {
defaultMessage: 'loading alerts',
}),
footerText: i18n.translate('xpack.observability.alertsTable.footerTextLabel', {
defaultMessage: 'alerts',
}),
query: {
query: `${ALERT_STATUS}: ${status}${kuery !== '' ? ` and ${kuery}` : ''}`,
language: 'kuery',
},
renderCellValue: getRenderCellValue({ rangeFrom, rangeTo, setFlyoutAlert }),
rowRenderers: NO_ROW_RENDER,
start: rangeFrom,
setRefetch,
sort: [
{
columnId: '@timestamp',
columnType: 'date',
sortDirection: 'desc',
},
],
leadingControlColumns,
trailingControlColumns,
unit: (totalAlerts: number) =>
i18n.translate('xpack.observability.alertsTable.showingAlertsTitle', {
values: { totalAlerts },
defaultMessage: '{totalAlerts, plural, =1 {alert} other {alerts}}',
}),
})}
</>
);
}
Loading

0 comments on commit cf9e88c

Please sign in to comment.