Skip to content

Commit

Permalink
[Custom threshold rule] Use lens chart with annotations in alert deta…
Browse files Browse the repository at this point in the history
…ils page (elastic#175513)

Resolves elastic#174075,
elastic#155691

- Using same chart in alert details page as in rule flyout for preview
- Group by info is applied as filter on chart data
- Added annotations
- For active alerts, added point annotation with alert start time and
range annotation with range from alert start time till current time
  - For recovered alerts, added range annotation for alert duration

### Active alert
<img width="1257" alt="Screenshot 2024-01-26 at 15 05 26"
src="https://github.com/elastic/kibana/assets/69037875/d548b529-7811-4e3e-996d-aa4d259327b9">

<img width="1265" alt="Screenshot 2024-01-26 at 15 09 44"
src="https://github.com/elastic/kibana/assets/69037875/a01d0cdf-5254-484d-91b3-c45a846790a9">

### Recovered alert
<img width="1250" alt="Screenshot 2024-01-26 at 14 53 08"
src="https://github.com/elastic/kibana/assets/69037875/521a69a2-6a4a-4b9e-a886-3477c92d63ac">

---------

Co-authored-by: kibanamachine <[email protected]>
  • Loading branch information
2 people authored and fkanout committed Mar 4, 2024
1 parent bfbdf3e commit 1a268b8
Show file tree
Hide file tree
Showing 17 changed files with 276 additions and 91 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ export const METRIC_ID = 'lnsMetric';

export const METRIC_TREND_LINE_ID = 'metricTrendline';
export const XY_REFERENCE_LINE_ID = 'referenceLine';
export const XY_ANNOTATIONS_ID = 'annotations';
export const XY_DATA_ID = 'data';
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ export {
XYReferenceLinesLayer,
type XYReferenceLinesLayerConfig,
} from './xy_reference_lines_layer';

export {
XYByValueAnnotationsLayer,
type XYByValueAnnotationsLayerConfig,
} from './xy_by_value_annotation_layer';
export { FormulaColumn } from './columns/formula';
export { StaticColumn } from './columns/static';
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import type { SavedObjectReference } from '@kbn/core/server';
import type { DataView } from '@kbn/data-views-plugin/common';
import { EventAnnotationConfig } from '@kbn/event-annotation-common';
import type { FormBasedPersistedState, PersistedIndexPatternLayer } from '@kbn/lens-plugin/public';
import type { XYByValueAnnotationLayerConfig } from '@kbn/lens-plugin/public/visualizations/xy/types';
import type { ChartLayer } from '../../types';
import { getDefaultReferences } from '../../utils';
import { XY_ANNOTATIONS_ID } from '../constants';

export interface XYByValueAnnotationsLayerConfig {
annotations: EventAnnotationConfig[];
layerType?: typeof XY_ANNOTATIONS_ID;
/**
* It is possible to define a specific dataView for the layer. It will override the global chart one
**/
dataView?: DataView;
ignoreGlobalFilters?: boolean;
}

export class XYByValueAnnotationsLayer implements ChartLayer<XYByValueAnnotationLayerConfig> {
private layerConfig: XYByValueAnnotationsLayerConfig;

constructor(layerConfig: XYByValueAnnotationsLayerConfig) {
this.layerConfig = {
...layerConfig,
layerType: layerConfig.layerType ?? 'annotations',
};
}

getName(): string | undefined {
return this.layerConfig.annotations[0].label;
}

getLayer(layerId: string): FormBasedPersistedState['layers'] {
const baseLayer = { columnOrder: [], columns: {} } as PersistedIndexPatternLayer;
return {
[`${layerId}_annotation`]: baseLayer,
};
}

getReference(layerId: string, chartDataView: DataView): SavedObjectReference[] {
return getDefaultReferences(this.layerConfig.dataView ?? chartDataView, `${layerId}_reference`);
}

getLayerConfig(layerId: string): XYByValueAnnotationLayerConfig {
return {
layerId: `${layerId}_annotation`,
layerType: 'annotations',
annotations: this.layerConfig.annotations,
ignoreGlobalFilters: this.layerConfig.ignoreGlobalFilters || false,
indexPatternId: this.layerConfig.dataView?.id || '',
};
}

getDataView(): DataView | undefined {
return this.layerConfig.dataView;
}
}
1 change: 1 addition & 0 deletions packages/kbn-lens-embeddable-utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export {
XYChart,
XYDataLayer,
XYReferenceLinesLayer,
XYByValueAnnotationsLayer,
METRIC_ID,
METRIC_TREND_LINE_ID,
XY_ID,
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
buildCustomThresholdRule,
} from '../../mocks/custom_threshold_rule';
import { CustomThresholdAlertFields } from '../../types';
import { ExpressionChart } from '../expression_chart';
import { RuleConditionChart } from '../rule_condition_chart/rule_condition_chart';
import AlertDetailsAppSection, { CustomThresholdAlert } from './alert_details_app_section';
import { Groups } from './groups';
import { Tags } from './tags';
Expand All @@ -37,8 +37,8 @@ jest.mock('@kbn/observability-get-padded-alert-time-range-util', () => ({
}),
}));

jest.mock('../expression_chart', () => ({
ExpressionChart: jest.fn(() => <div data-test-subj="ExpressionChart" />),
jest.mock('../rule_condition_chart/rule_condition_chart', () => ({
RuleConditionChart: jest.fn(() => <div data-test-subj="RuleConditionChart" />),
}));

jest.mock('../../../../utils/kibana_react', () => ({
Expand Down Expand Up @@ -141,11 +141,14 @@ describe('AlertDetailsAppSection', () => {
});

it('should render annotations', async () => {
const mockedExpressionChart = jest.fn(() => <div data-test-subj="ExpressionChart" />);
(ExpressionChart as jest.Mock).mockImplementation(mockedExpressionChart);
const alertDetailsAppSectionComponent = renderComponent();
const mockedRuleConditionChart = jest.fn(() => <div data-test-subj="RuleConditionChart" />);
(RuleConditionChart as jest.Mock).mockImplementation(mockedRuleConditionChart);
const alertDetailsAppSectionComponent = renderComponent(
{},
{ ['kibana.alert.end']: '2023-03-28T14:40:00.000Z' }
);

expect(alertDetailsAppSectionComponent.getAllByTestId('ExpressionChart').length).toBe(3);
expect(mockedExpressionChart.mock.calls[0]).toMatchSnapshot();
expect(alertDetailsAppSectionComponent.getAllByTestId('RuleConditionChart').length).toBe(3);
expect(mockedRuleConditionChart.mock.calls[0]).toMatchSnapshot();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@
* 2.0.
*/

import moment from 'moment';
import { DataViewBase, Query } from '@kbn/es-query';
import { Query } from '@kbn/es-query';
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n-react';
import React, { useEffect, useMemo, useState } from 'react';
import React, { useEffect, useState } from 'react';
import {
EuiFlexGroup,
EuiFlexItem,
Expand All @@ -18,10 +17,8 @@ import {
EuiSpacer,
EuiText,
EuiTitle,
useEuiTheme,
} from '@elastic/eui';
import { Rule, RuleTypeParams } from '@kbn/alerting-plugin/common';
import { AlertAnnotation, AlertActiveTimeRangeAnnotation } from '@kbn/observability-alert-details';
import { getPaddedAlertTimeRange } from '@kbn/observability-get-padded-alert-time-range-util';
import {
ALERT_END,
Expand All @@ -31,7 +28,14 @@ import {
TAGS,
} from '@kbn/rule-data-utils';
import { DataView } from '@kbn/data-views-plugin/common';
import { MetricsExplorerChartType } from '../../../../../common/custom_threshold_rule/types';
import chroma from 'chroma-js';
import type {
EventAnnotationConfig,
PointInTimeEventAnnotationConfig,
RangeEventAnnotationConfig,
} from '@kbn/event-annotation-common';
import moment from 'moment';
import { transparentize, useEuiTheme } from '@elastic/eui';
import { useLicense } from '../../../../hooks/use_license';
import { useKibana } from '../../../../utils/kibana_react';
import { metricValueFormatter } from '../../../../../common/custom_threshold_rule/metric_value_formatter';
Expand All @@ -41,21 +45,18 @@ import {
CustomThresholdAlertFields,
CustomThresholdRuleTypeParams,
} from '../../types';
import { ExpressionChart } from '../expression_chart';
import { TIME_LABELS } from '../criterion_preview_chart/criterion_preview_chart';
import { Threshold } from '../custom_threshold';
import { LogRateAnalysis } from './log_rate_analysis';
import { Groups } from './groups';
import { Tags } from './tags';
import { RuleConditionChart } from '../rule_condition_chart/rule_condition_chart';
import { getFilterQuery } from './helpers/get_filter_query';

// TODO Use a generic props for app sections https://github.com/elastic/kibana/issues/152690
export type CustomThresholdRule = Rule<CustomThresholdRuleTypeParams>;
export type CustomThresholdAlert = TopAlert<CustomThresholdAlertFields>;

const DEFAULT_DATE_FORMAT = 'YYYY-MM-DD HH:mm';
const ALERT_START_ANNOTATION_ID = 'alert_start_annotation';
const ALERT_TIME_RANGE_ANNOTATION_ID = 'alert_time_range_annotation';

interface AppSectionProps {
alert: CustomThresholdAlert;
rule: CustomThresholdRule;
Expand All @@ -71,37 +72,49 @@ export default function AlertDetailsAppSection({
setAlertSummaryFields,
}: AppSectionProps) {
const services = useKibana().services;
const { uiSettings, charts, data } = services;
const { euiTheme } = useEuiTheme();
const { charts, data } = services;
const { hasAtLeast } = useLicense();
const { euiTheme } = useEuiTheme();
const hasLogRateAnalysisLicense = hasAtLeast('platinum');
const [dataView, setDataView] = useState<DataView>();
const [filterQuery, setFilterQuery] = useState<string>('');
const [, setDataViewError] = useState<Error>();
const ruleParams = rule.params as RuleTypeParams & AlertParams;
const chartProps = {
baseTheme: charts.theme.useChartsBaseTheme(),
};
const timeRange = getPaddedAlertTimeRange(alert.fields[ALERT_START]!, alert.fields[ALERT_END]);
const alertEnd = alert.fields[ALERT_END] ? moment(alert.fields[ALERT_END]).valueOf() : undefined;
const alertStart = alert.fields[ALERT_START];
const alertEnd = alert.fields[ALERT_END];
const timeRange = getPaddedAlertTimeRange(alertStart!, alertEnd);
const groups = alert.fields[ALERT_GROUP];
const tags = alert.fields[TAGS];

const annotations = [
<AlertAnnotation
alertStart={alert.start}
color={euiTheme.colors.danger}
dateFormat={uiSettings.get('dateFormat') || DEFAULT_DATE_FORMAT}
id={ALERT_START_ANNOTATION_ID}
key={ALERT_START_ANNOTATION_ID}
/>,
<AlertActiveTimeRangeAnnotation
alertStart={alert.start}
alertEnd={alertEnd}
color={euiTheme.colors.danger}
id={ALERT_TIME_RANGE_ANNOTATION_ID}
key={ALERT_TIME_RANGE_ANNOTATION_ID}
/>,
];
const alertStartAnnotation: PointInTimeEventAnnotationConfig = {
label: 'Alert',
type: 'manual',
key: {
type: 'point_in_time',
timestamp: alertStart!,
},
color: euiTheme.colors.danger,
icon: 'alert',
id: 'custom_threshold_alert_start_annotation',
};

const alertRangeAnnotation: RangeEventAnnotationConfig = {
label: `${alertEnd ? 'Alert duration' : 'Active alert'}`,
type: 'manual',
key: {
type: 'range',
timestamp: alertStart!,
endTimestamp: alertEnd ?? moment().toISOString(),
},
color: chroma(transparentize('#F04E981A', 0.2)).hex().toUpperCase(),
id: `custom_threshold_${alertEnd ? 'recovered' : 'active'}_alert_range_annotation`,
};

const annotations: EventAnnotationConfig[] = [];
annotations.push(alertStartAnnotation, alertRangeAnnotation);

useEffect(() => {
const alertSummaryFields = [];
Expand Down Expand Up @@ -144,13 +157,10 @@ export default function AlertDetailsAppSection({
setAlertSummaryFields(alertSummaryFields);
}, [groups, tags, rule, ruleLink, setAlertSummaryFields]);

const derivedIndexPattern = useMemo<DataViewBase>(
() => ({
fields: dataView?.fields || [],
title: dataView?.getIndexPattern() || 'unknown-index',
}),
[dataView]
);
useEffect(() => {
const query = `${(ruleParams.searchConfiguration?.query as Query)?.query as string}`;
setFilterQuery(getFilterQuery(query, groups));
}, [groups, ruleParams.searchConfiguration]);

useEffect(() => {
const initDataView = async () => {
Expand Down Expand Up @@ -209,15 +219,15 @@ export default function AlertDetailsAppSection({
/>
</EuiFlexItem>
<EuiFlexItem grow={5}>
<ExpressionChart
annotations={annotations}
chartType={MetricsExplorerChartType.line}
derivedIndexPattern={derivedIndexPattern}
expression={criterion}
filterQuery={(ruleParams.searchConfiguration?.query as Query)?.query as string}
<RuleConditionChart
metricExpression={criterion}
dataView={dataView}
filterQuery={filterQuery}
groupBy={ruleParams.groupBy}
hideTitle
annotations={annotations}
timeRange={timeRange}
// For alert details page, the series type needs to be changed to 'bar_stacked' due to https://github.com/elastic/elastic-charts/issues/2323
seriesType={'bar_stacked'}
/>
</EuiFlexItem>
</EuiFlexGroup>
Expand Down
Loading

0 comments on commit 1a268b8

Please sign in to comment.