Skip to content
/ kibana Public
forked from elastic/kibana

Commit

Permalink
[APM] Alerting: Show preview as chart of threshold (elastic#84080)
Browse files Browse the repository at this point in the history
  • Loading branch information
cauemarcondes authored and smith committed Dec 14, 2020
1 parent 9504601 commit db64c28
Show file tree
Hide file tree
Showing 24 changed files with 774 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { i18n } from '@kbn/i18n';
import React, { useState } from 'react';
import { IBasePath } from '../../../../../../src/core/public';
import { AlertType } from '../../../common/alert_types';
import { AlertingFlyout } from '../../components/alerting/AlertingFlyout';
import { AlertingFlyout } from '../../components/alerting/alerting_flyout';

const alertLabel = i18n.translate('xpack.apm.home.alertsMenu.alerts', {
defaultMessage: 'Alerts',
Expand Down
112 changes: 112 additions & 0 deletions x-pack/plugins/apm/public/components/alerting/chart_preview/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import {
AnnotationDomainTypes,
Axis,
BarSeries,
Chart,
LineAnnotation,
niceTimeFormatter,
Position,
RectAnnotation,
RectAnnotationDatum,
ScaleType,
Settings,
TickFormatter,
} from '@elastic/charts';
import { EuiSpacer } from '@elastic/eui';
import React from 'react';
import { Coordinate } from '../../../../typings/timeseries';
import { useTheme } from '../../../hooks/use_theme';

interface ChartPreviewProps {
yTickFormat?: TickFormatter;
data?: Coordinate[];
threshold: number;
}

export function ChartPreview({
data = [],
yTickFormat,
threshold,
}: ChartPreviewProps) {
const theme = useTheme();
const thresholdOpacity = 0.3;
const timestamps = data.map((d) => d.x);
const xMin = Math.min(...timestamps);
const xMax = Math.max(...timestamps);
const xFormatter = niceTimeFormatter([xMin, xMax]);

// Make the maximum Y value either the actual max or 20% more than the threshold
const values = data.map((d) => d.y ?? 0);
const yMax = Math.max(...values, threshold * 1.2);

const style = {
fill: theme.eui.euiColorVis9,
line: {
strokeWidth: 2,
stroke: theme.eui.euiColorVis9,
opacity: 1,
},
opacity: thresholdOpacity,
};

const rectDataValues: RectAnnotationDatum[] = [
{
coordinates: {
x0: null,
x1: null,
y0: threshold,
y1: null,
},
},
];

return (
<>
<EuiSpacer size="m" />
<Chart size={{ height: 150 }} data-test-subj="ChartPreview">
<Settings tooltip="none" />
<LineAnnotation
dataValues={[{ dataValue: threshold }]}
domainType={AnnotationDomainTypes.YDomain}
id="chart_preview_line_annotation"
markerPosition="left"
style={style}
/>
<RectAnnotation
dataValues={rectDataValues}
hideTooltips={true}
id="chart_preview_rect_annotation"
style={style}
/>
<Axis
id="chart_preview_x_axis"
position={Position.Bottom}
showOverlappingTicks
tickFormat={xFormatter}
/>
<Axis
id="chart_preview_y_axis"
position={Position.Left}
tickFormat={yTickFormat}
ticks={5}
domain={{ max: yMax }}
/>
<BarSeries
color={theme.eui.euiColorVis1}
data={data}
id="chart_preview_bar_series"
xAccessor="x"
xScaleType={ScaleType.Linear}
yAccessors={['y']}
yScaleType={ScaleType.Linear}
/>
</Chart>
</>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,17 @@ import { i18n } from '@kbn/i18n';
import React from 'react';
import { useParams } from 'react-router-dom';
import { ForLastExpression } from '../../../../../triggers_actions_ui/public';
import { ALERT_TYPES_CONFIG, AlertType } from '../../../../common/alert_types';
import { AlertType, ALERT_TYPES_CONFIG } from '../../../../common/alert_types';
import { ENVIRONMENT_ALL } from '../../../../common/environment_filter_values';
import { useEnvironmentsFetcher } from '../../../hooks/use_environments_fetcher';
import { asInteger } from '../../../../common/utils/formatters';
import { useUrlParams } from '../../../context/url_params_context/use_url_params';
import { EnvironmentField, ServiceField, IsAboveField } from '../fields';
import { ServiceAlertTrigger } from '../ServiceAlertTrigger';
import { useEnvironmentsFetcher } from '../../../hooks/use_environments_fetcher';
import { useFetcher } from '../../../hooks/use_fetcher';
import { callApmApi } from '../../../services/rest/createCallApmApi';
import { ChartPreview } from '../chart_preview';
import { EnvironmentField, IsAboveField, ServiceField } from '../fields';
import { getAbsoluteTimeRange } from '../helper';
import { ServiceAlertTrigger } from '../service_alert_trigger';

export interface AlertParams {
windowSize: number;
Expand All @@ -40,6 +45,23 @@ export function ErrorCountAlertTrigger(props: Props) {
end,
});

const { threshold, windowSize, windowUnit, environment } = alertParams;

const { data } = useFetcher(() => {
if (windowSize && windowUnit) {
return callApmApi({
endpoint: 'GET /api/apm/alerts/chart_preview/transaction_error_count',
params: {
query: {
...getAbsoluteTimeRange(windowSize, windowUnit),
environment,
serviceName,
},
},
});
}
}, [windowSize, windowUnit, environment, serviceName]);

const defaults = {
threshold: 25,
windowSize: 1,
Expand All @@ -64,14 +86,14 @@ export function ErrorCountAlertTrigger(props: Props) {
unit={i18n.translate('xpack.apm.errorCountAlertTrigger.errors', {
defaultMessage: ' errors',
})}
onChange={(value) => setAlertParams('threshold', value)}
onChange={(value) => setAlertParams('threshold', value || 0)}
/>,
<ForLastExpression
onChangeWindowSize={(windowSize) =>
setAlertParams('windowSize', windowSize || '')
onChangeWindowSize={(timeWindowSize) =>
setAlertParams('windowSize', timeWindowSize || '')
}
onChangeWindowUnit={(windowUnit) =>
setAlertParams('windowUnit', windowUnit)
onChangeWindowUnit={(timeWindowUnit) =>
setAlertParams('windowUnit', timeWindowUnit)
}
timeWindowSize={params.windowSize}
timeWindowUnit={params.windowUnit}
Expand All @@ -82,13 +104,18 @@ export function ErrorCountAlertTrigger(props: Props) {
/>,
];

const chartPreview = (
<ChartPreview data={data} threshold={threshold} yTickFormat={asInteger} />
);

return (
<ServiceAlertTrigger
alertTypeName={ALERT_TYPES_CONFIG[AlertType.ErrorCount].name}
defaults={defaults}
fields={fields}
setAlertParams={setAlertParams}
setAlertProperty={setAlertProperty}
chartPreview={chartPreview}
/>
);
}
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/apm/public/components/alerting/fields.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import React from 'react';
import { i18n } from '@kbn/i18n';
import { EuiSelectOption } from '@elastic/eui';
import { getEnvironmentLabel } from '../../../common/environment_filter_values';
import { PopoverExpression } from './ServiceAlertTrigger/PopoverExpression';
import { PopoverExpression } from './service_alert_trigger/popover_expression';

const ALL_OPTION = i18n.translate('xpack.apm.alerting.fields.all_option', {
defaultMessage: 'All',
Expand Down
17 changes: 17 additions & 0 deletions x-pack/plugins/apm/public/components/alerting/helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import datemath from '@elastic/datemath';

export function getAbsoluteTimeRange(windowSize: number, windowUnit: string) {
const now = new Date().toISOString();

return {
start:
datemath.parse(`now-${windowSize}${windowUnit}`)?.toISOString() ?? now,
end: now,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function registerApmAlerts(
documentationUrl(docLinks) {
return `${docLinks.ELASTIC_WEBSITE_URL}guide/en/kibana/${docLinks.DOC_LINK_VERSION}/apm-alerts.html`;
},
alertParamsExpression: lazy(() => import('./ErrorCountAlertTrigger')),
alertParamsExpression: lazy(() => import('./error_count_alert_trigger')),
validate: () => ({
errors: [],
}),
Expand Down Expand Up @@ -60,7 +60,7 @@ export function registerApmAlerts(
return `${docLinks.ELASTIC_WEBSITE_URL}guide/en/kibana/${docLinks.DOC_LINK_VERSION}/apm-alerts.html`;
},
alertParamsExpression: lazy(
() => import('./TransactionDurationAlertTrigger')
() => import('./transaction_duration_alert_trigger')
),
validate: () => ({
errors: [],
Expand Down Expand Up @@ -97,7 +97,7 @@ export function registerApmAlerts(
return `${docLinks.ELASTIC_WEBSITE_URL}guide/en/kibana/${docLinks.DOC_LINK_VERSION}/apm-alerts.html`;
},
alertParamsExpression: lazy(
() => import('./TransactionErrorRateAlertTrigger')
() => import('./transaction_error_rate_alert_trigger')
),
validate: () => ({
errors: [],
Expand Down Expand Up @@ -134,7 +134,7 @@ export function registerApmAlerts(
return `${docLinks.ELASTIC_WEBSITE_URL}guide/en/kibana/${docLinks.DOC_LINK_VERSION}/apm-alerts.html`;
},
alertParamsExpression: lazy(
() => import('./TransactionDurationAnomalyAlertTrigger')
() => import('./transaction_duration_anomaly_alert_trigger')
),
validate: () => ({
errors: [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { EuiFlexGrid, EuiFlexItem, EuiSpacer } from '@elastic/eui';
import React, { useEffect } from 'react';
import { EuiSpacer, EuiFlexGrid, EuiFlexItem } from '@elastic/eui';
import { useParams } from 'react-router-dom';

interface Props {
Expand All @@ -14,6 +14,7 @@ interface Props {
setAlertProperty: (key: string, value: any) => void;
defaults: Record<string, any>;
fields: React.ReactNode[];
chartPreview?: React.ReactNode;
}

export function ServiceAlertTrigger(props: Props) {
Expand All @@ -25,6 +26,7 @@ export function ServiceAlertTrigger(props: Props) {
setAlertProperty,
alertTypeName,
defaults,
chartPreview,
} = props;

const params: Record<string, any> = {
Expand Down Expand Up @@ -61,6 +63,7 @@ export function ServiceAlertTrigger(props: Props) {
</EuiFlexItem>
))}
</EuiFlexGrid>
{chartPreview}
<EuiSpacer size="m" />
</>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { render } from '@testing-library/react';
import React, { ReactNode } from 'react';
import { MemoryRouter } from 'react-router-dom';
import { ServiceAlertTrigger } from './';

function Wrapper({ children }: { children?: ReactNode }) {
return <MemoryRouter>{children}</MemoryRouter>;
}

describe('ServiceAlertTrigger', () => {
it('renders', () => {
expect(() =>
render(
<ServiceAlertTrigger
alertTypeName="test alert type name"
defaults={{}}
fields={[null]}
setAlertParams={() => {}}
setAlertProperty={() => {}}
/>,
{
wrapper: Wrapper,
}
)
).not.toThrowError();
});
});
Loading

0 comments on commit db64c28

Please sign in to comment.