Skip to content

Commit

Permalink
[Synthetics] Added alerts page (elastic#190751)
Browse files Browse the repository at this point in the history
## Summary

Synthetics - add alerts page , it shows related alerts for selected
monitor and location !!

<img width="1717" alt="image"
src="https://github.com/user-attachments/assets/590d2110-ad75-4c95-b413-496eff3a2544">

---------

Co-authored-by: shahzad31 <shahzad31comp@gmail.com>
  • Loading branch information
dominiqueclarke and shahzad31 committed Aug 20, 2024
1 parent 9ff78cf commit 398daa1
Show file tree
Hide file tree
Showing 11 changed files with 221 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const MONITOR_NOT_FOUND_ROUTE = '/monitor-not-found/:monitorId';
export const MONITOR_HISTORY_ROUTE = '/monitor/:monitorId/history';

export const MONITOR_ERRORS_ROUTE = '/monitor/:monitorId/errors';
export const MONITOR_ALERTS_ROUTE = '/monitor/:monitorId/alerts';

export const MONITOR_ADD_ROUTE = '/add-monitor';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,21 +119,16 @@ journey('AlertingDefaults', async ({ page, params }) => {
await page.click('.euiForm');
await page.click('text=To: Email is required for selected email connector');
});
step(
'Click .euiComboBox.euiComboBox--fullWidth.euiComboBox-isInvalid .euiFormControlLayout .euiFormControlLayout__childrenWrapper .euiComboBox__inputWrap',
async () => {
await page.click(
'.euiComboBox.euiComboBox--fullWidth.euiComboBox-isInvalid .euiFormControlLayout .euiFormControlLayout__childrenWrapper .euiComboBox__inputWrap'
);
await page.fill(
'text=To BccCombo box. Selected. Combo box input. Type some text or, to display a list >> input[role="combobox"]',
'test@gmail.com'
);
await page.isDisabled('button:has-text("Apply changes")');
await page.click('[aria-label="Account menu"]');
await page.click('text=Log out');
}
);

step('Fill email fields', async () => {
await page
.getByTestId('toEmailAddressInput')
.getByTestId('comboBoxSearchInput')
.fill('test@gmail.com');
await page.isDisabled('button:has-text("Apply changes")');
await page.click('[aria-label="Account menu"]');
await page.click('text=Log out');
});

step('Login to kibana with readonly', async () => {
await syntheticsApp.loginToKibana('viewer', 'changeme');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ export const SyntheticsDatePicker = ({ fullWidth }: { fullWidth?: boolean }) =>
refreshApp();
}}
onRefresh={refreshApp}
updateButtonProps={{
fill: false,
}}
/>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* 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 { BASE_RAC_ALERTS_API_PATH } from '@kbn/rule-registry-plugin/common';
import { AlertConsumers } from '@kbn/rule-registry-plugin/common/technical_rule_data_field_names';
import { useFetcher } from '@kbn/observability-shared-plugin/public';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { useParams } from 'react-router-dom';
import type { ESSearchResponse } from '@kbn/es-types';
import { useSelectedLocation } from './use_selected_location';

import { ClientPluginsStart } from '../../../../../plugin';

export function useFetchActiveAlerts() {
const { http } = useKibana<ClientPluginsStart>().services;

const { monitorId: configId } = useParams<{ monitorId: string }>();

const selectedLocation = useSelectedLocation();

const { loading, data } = useFetcher(async () => {
return await http.post<ESSearchResponse>(`${BASE_RAC_ALERTS_API_PATH}/find`, {
body: JSON.stringify({
feature_ids: [AlertConsumers.UPTIME],
size: 0,
track_total_hits: true,
query: {
bool: {
filter: [
{
range: {
'@timestamp': {
gte: 'now-24h/h',
},
},
},
{
term: {
configId,
},
},
{
term: {
'location.id': selectedLocation?.id,
},
},
],
},
},
}),
});
}, [configId, http, selectedLocation?.id]);

return {
loading,
data,
numberOfAlerts: data?.hits?.total.value ?? 0,
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*
* 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 React from 'react';
import { EuiBadge } from '@elastic/eui';
import { useFetchActiveAlerts } from '../hooks/use_fetch_active_alerts';

export const MonitorAlertsIcon = () => {
const { numberOfAlerts } = useFetchActiveAlerts();

return numberOfAlerts > 0 ? <EuiBadge color="danger">{numberOfAlerts}</EuiBadge> : null;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* 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 { EuiFlexGroup, EuiFlexItem, EuiSpacer, EuiLoadingSpinner } from '@elastic/eui';
import React from 'react';
import { AlertConsumers } from '@kbn/rule-data-utils';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { useParams } from 'react-router-dom';
import { useRefreshedRangeFromUrl } from '../../../hooks';
import { SyntheticsDatePicker } from '../../common/date_picker/synthetics_date_picker';
import { useSelectedLocation } from '../hooks/use_selected_location';
import { ClientPluginsStart } from '../../../../../plugin';

export const MONITOR_ALERTS_TABLE_ID = 'xpack.observability.slo.sloDetails.alertTable';

export function MonitorDetailsAlerts() {
const {
triggersActionsUi: { alertsTableConfigurationRegistry, getAlertsStateTable: AlertsStateTable },
observability: { observabilityRuleTypeRegistry },
} = useKibana<ClientPluginsStart>().services;

const { monitorId: configId } = useParams<{ monitorId: string }>();

const selectedLocation = useSelectedLocation();
const { from, to } = useRefreshedRangeFromUrl();

if (!selectedLocation) {
return <EuiLoadingSpinner size="xl" />;
}

return (
<>
<EuiSpacer size="m" />
<EuiFlexGroup direction="column" gutterSize="xl">
<EuiFlexItem>
<SyntheticsDatePicker fullWidth={true} />
</EuiFlexItem>
<EuiFlexItem>
<AlertsStateTable
alertsTableConfigurationRegistry={alertsTableConfigurationRegistry}
configurationId={AlertConsumers.OBSERVABILITY}
id={MONITOR_ALERTS_TABLE_ID}
data-test-subj="monitorAlertsTable"
featureIds={[AlertConsumers.UPTIME]}
query={{
bool: {
filter: [
{ term: { configId } },
{ term: { 'location.id': selectedLocation?.id } },
{ range: { '@timestamp': { gte: from, lte: to } } },
],
},
}}
showAlertStatusWithFlapping
initialPageSize={100}
cellContext={{ observabilityRuleTypeRegistry }}
/>
</EuiFlexItem>
</EuiFlexGroup>
</>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ import React, { useCallback } from 'react';
import { useParams, useRouteMatch } from 'react-router-dom';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { useGetUrlParams } from '../../hooks';
import { MONITOR_ERRORS_ROUTE, MONITOR_HISTORY_ROUTE } from '../../../../../common/constants';
import {
MONITOR_ALERTS_ROUTE,
MONITOR_ERRORS_ROUTE,
MONITOR_HISTORY_ROUTE,
} from '../../../../../common/constants';
import { ClientPluginsStart } from '../../../../plugin';
import { PLUGIN } from '../../../../../common/constants/plugin';
import { useSelectedLocation } from './hooks/use_selected_location';
Expand All @@ -28,6 +32,7 @@ export const MonitorDetailsLocation = ({ isDisabled }: { isDisabled?: boolean })

const isErrorsTab = useRouteMatch(MONITOR_ERRORS_ROUTE);
const isHistoryTab = useRouteMatch(MONITOR_HISTORY_ROUTE);
const isAlertsTab = useRouteMatch(MONITOR_ALERTS_ROUTE);

const params = `&dateRangeStart=${dateRangeStart}&dateRangeEnd=${dateRangeEnd}`;

Expand All @@ -39,7 +44,11 @@ export const MonitorDetailsLocation = ({ isDisabled }: { isDisabled?: boolean })
selectedLocation={selectedLocation}
onChange={useCallback(
(id, label) => {
if (isErrorsTab) {
if (isAlertsTab) {
services.application.navigateToApp(PLUGIN.SYNTHETICS_PLUGIN_ID, {
path: `/monitor/${monitorId}/alerts?locationId=${id}${params}`,
});
} else if (isErrorsTab) {
services.application.navigateToApp(PLUGIN.SYNTHETICS_PLUGIN_ID, {
path: `/monitor/${monitorId}/errors?locationId=${id}${params}`,
});
Expand All @@ -53,7 +62,7 @@ export const MonitorDetailsLocation = ({ isDisabled }: { isDisabled?: boolean })
});
}
},
[isErrorsTab, isHistoryTab, monitorId, params, services.application]
[isAlertsTab, isErrorsTab, isHistoryTab, monitorId, params, services.application]
)}
/>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import React from 'react';
import { useHistory, useRouteMatch } from 'react-router-dom';
import { EuiIcon, EuiPageHeaderProps } from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n-react';
import { MonitorDetailsAlerts } from './monitor_alerts/monitor_detail_alerts';
import { MonitorAlertsIcon } from './monitor_alerts/alerts_icon';
import { RefreshButton } from '../common/components/refresh_button';
import { MonitorNotFoundPage } from './monitor_not_found_page';
import { MonitorDetailsPageTitle } from './monitor_details_page_title';
Expand All @@ -23,6 +25,7 @@ import { MonitorHistory } from './monitor_history/monitor_history';
import { MonitorSummary } from './monitor_summary/monitor_summary';
import { EditMonitorLink } from './monitor_summary/edit_monitor_link';
import {
MONITOR_ALERTS_ROUTE,
MONITOR_ERRORS_ROUTE,
MONITOR_HISTORY_ROUTE,
MONITOR_NOT_FOUND_ROUTE,
Expand Down Expand Up @@ -67,6 +70,16 @@ export const getMonitorDetailsRoute = (
dataTestSubj: 'syntheticsMonitorHistoryPage',
pageHeader: getMonitorSummaryHeader(history, syntheticsPath, 'errors'),
},
{
title: i18n.translate('xpack.synthetics.monitorErrors.title', {
defaultMessage: 'Synthetics Monitor Alerts | {baseTitle}',
values: { baseTitle },
}),
path: MONITOR_ALERTS_ROUTE,
component: MonitorDetailsAlerts,
dataTestSubj: 'syntheticsMonitorAlertsPage',
pageHeader: getMonitorSummaryHeader(history, syntheticsPath, 'alerts'),
},
{
title: i18n.translate('xpack.synthetics.monitorNotFound.title', {
defaultMessage: 'Synthetics Monitor Not Found | {baseTitle}',
Expand Down Expand Up @@ -100,7 +113,7 @@ const getMonitorsBreadcrumb = (syntheticsPath: string) => ({
const getMonitorSummaryHeader = (
history: ReturnType<typeof useHistory>,
syntheticsPath: string,
selectedTab: 'overview' | 'history' | 'errors'
selectedTab: 'overview' | 'history' | 'errors' | 'alerts'
): EuiPageHeaderProps => {
// Not a component, but it doesn't matter. Hooks are just functions
const match = useRouteMatch<{ monitorId: string }>(MONITOR_ROUTE); // eslint-disable-line react-hooks/rules-of-hooks
Expand All @@ -112,17 +125,23 @@ const getMonitorSummaryHeader = (
const search = history.location.search;
const monitorId = match.params.monitorId;

const rightSideItems = [
<RefreshButton />,
<EditMonitorLink />,
<RunTestManually />,
<MonitorDetailsLastRun />,
<MonitorDetailsStatus />,
<MonitorDetailsLocation />,
];
if (selectedTab === 'alerts' || selectedTab === 'history' || selectedTab === 'errors') {
// remove first item refresh button
rightSideItems.shift();
}

return {
pageTitle: <MonitorDetailsPageTitle />,
breadcrumbs: [getMonitorsBreadcrumb(syntheticsPath)],
rightSideItems: [
<RefreshButton />,
<EditMonitorLink />,
<RunTestManually />,
<MonitorDetailsLastRun />,
<MonitorDetailsStatus />,
<MonitorDetailsLocation />,
],
rightSideItems,
tabs: [
{
label: i18n.translate('xpack.synthetics.monitorOverviewTab.title', {
Expand All @@ -149,6 +168,15 @@ const getMonitorSummaryHeader = (
href: `${syntheticsPath}${MONITOR_ERRORS_ROUTE.replace(':monitorId', monitorId)}${search}`,
'data-test-subj': 'syntheticsMonitorErrorsTab',
},
{
label: i18n.translate('xpack.synthetics.monitorAlertsTab.title', {
defaultMessage: 'Alerts',
}),
prepend: <MonitorAlertsIcon />,
isSelected: selectedTab === 'alerts',
href: `${syntheticsPath}${MONITOR_ALERTS_ROUTE.replace(':monitorId', monitorId)}${search}`,
'data-test-subj': 'syntheticsMonitorAlertsTab',
},
],
};
};
10 changes: 5 additions & 5 deletions x-pack/plugins/translations/translations/fr-FR.json
Original file line number Diff line number Diff line change
Expand Up @@ -11131,8 +11131,8 @@
"xpack.apm.serviceIcons.service": "Service",
"xpack.apm.serviceIcons.serviceDetails.cloud.architecture": "Architecture",
"xpack.apm.serviceIcons.serviceDetails.cloud.availabilityZoneLabel": "{zones, plural, =0 {Zone de disponibilité} one {Zone de disponibilité} other {Zones de disponibilité}} ",
"xpack.apm.serviceIcons.serviceDetails.cloud.functionNameLabel": "{functionNames, plural, =0 {Nom de fonction} one {Nom de fonction} other {Noms de fonction}} ",
"xpack.apm.serviceIcons.serviceDetails.cloud.faasTriggerTypeLabel": "{triggerTypes, plural, =0 {Type de déclencheur} one {Type de déclencheur} other {Types de déclencheurs}} ",
"xpack.apm.serviceIcons.serviceDetails.cloud.functionNameLabel": "{functionNames, plural, =0 {Nom de fonction} one {Nom de fonction} other {Noms de fonction}} ",
"xpack.apm.serviceIcons.serviceDetails.cloud.machineTypesLabel": "{machineTypes, plural, =0{Type de machine} one {Type de machine} other {Types de machines}} ",
"xpack.apm.serviceIcons.serviceDetails.cloud.projectIdLabel": "ID de projet",
"xpack.apm.serviceIcons.serviceDetails.cloud.providerLabel": "Fournisseur cloud",
Expand Down Expand Up @@ -27088,8 +27088,8 @@
"xpack.maps.source.esSearch.descendingLabel": "décroissant",
"xpack.maps.source.esSearch.extentFilterLabel": "Filtre dynamique pour les données de la zone de carte visible",
"xpack.maps.source.esSearch.fieldNotFoundMsg": "Impossible de trouver \"{fieldName}\" dans le modèle d'indexation \"{indexPatternName}\".",
"xpack.maps.source.esSearch.geoFieldLabel": "Champ géospatial",
"xpack.maps.source.esSearch.geofieldLabel": "Champ géospatial",
"xpack.maps.source.esSearch.geoFieldLabel": "Champ géospatial",
"xpack.maps.source.esSearch.geoFieldTypeLabel": "Type de champ géospatial",
"xpack.maps.source.esSearch.indexOverOneLengthEditError": "Votre vue de données pointe vers plusieurs index. Un seul index est autorisé par vue de données.",
"xpack.maps.source.esSearch.indexZeroLengthEditError": "Votre vue de données ne pointe vers aucun index.",
Expand Down Expand Up @@ -36554,8 +36554,8 @@
"xpack.securitySolution.detectionEngine.createRule.stepAboutRule.maxAlertsFieldLessThanWarning": "Kibana ne permet qu'un maximum de {maxNumber} {maxNumber, plural, =1 {alerte} other {alertes}} par exécution de règle.",
"xpack.securitySolution.detectionEngine.createRule.stepAboutRule.nameFieldRequiredError": "Nom obligatoire.",
"xpack.securitySolution.detectionEngine.createRule.stepAboutrule.noteHelpText": "Ajouter un guide d'investigation sur les règles...",
"xpack.securitySolution.detectionEngine.createRule.stepAboutRule.setupHelpText": "Fournissez des instructions sur les conditions préalables à la règle, telles que les intégrations requises, les étapes de configuration et tout ce qui est nécessaire au bon fonctionnement de la règle.",
"xpack.securitySolution.detectionEngine.createRule.stepAboutrule.setupHelpText": "Ajouter le guide de configuration de règle...",
"xpack.securitySolution.detectionEngine.createRule.stepAboutRule.setupHelpText": "Fournissez des instructions sur les conditions préalables à la règle, telles que les intégrations requises, les étapes de configuration et tout ce qui est nécessaire au bon fonctionnement de la règle.",
"xpack.securitySolution.detectionEngine.createRule.stepAboutRule.setupLabel": "Guide de configuration",
"xpack.securitySolution.detectionEngine.createRule.stepAboutRule.tagFieldEmptyError": "Une balise ne doit pas être vide",
"xpack.securitySolution.detectionEngine.createRule.stepAboutRule.threatIndicatorPathFieldEmptyError": "Le remplacement du préfixe d'indicateur ne peut pas être vide.",
Expand Down Expand Up @@ -42193,8 +42193,8 @@
"xpack.slo.sloEmbeddable.config.sloSelector.placeholder": "Sélectionner un SLO",
"xpack.slo.sloEmbeddable.displayName": "Aperçu du SLO",
"xpack.slo.sloEmbeddable.overview.sloNotFoundText": "Le SLO a été supprimé. Vous pouvez supprimer sans risque le widget du tableau de bord.",
"xpack.slo.sLOGridItem.targetFlexItemLabel": "Cible {target}",
"xpack.slo.sloGridItem.targetFlexItemLabel": "Cible {target}",
"xpack.slo.sLOGridItem.targetFlexItemLabel": "Cible {target}",
"xpack.slo.sloGroupConfiguration.customFiltersLabel": "Personnaliser le filtre",
"xpack.slo.sloGroupConfiguration.customFiltersOptional": "Facultatif",
"xpack.slo.sloGroupConfiguration.customFilterText": "Personnaliser le filtre",
Expand Down Expand Up @@ -43640,8 +43640,8 @@
"xpack.stackConnectors.components.casesWebhookxpack.stackConnectors.components.casesWebhook.connectorTypeTitle": "Webhook - Données de gestion des cas",
"xpack.stackConnectors.components.d3security.bodyCodeEditorAriaLabel": "Éditeur de code",
"xpack.stackConnectors.components.d3security.bodyFieldLabel": "Corps",
"xpack.stackConnectors.components.d3Security.connectorTypeTitle": "D3 Security",
"xpack.stackConnectors.components.d3security.connectorTypeTitle": "Données D3",
"xpack.stackConnectors.components.d3Security.connectorTypeTitle": "D3 Security",
"xpack.stackConnectors.components.d3security.eventTypeFieldLabel": "Type d'événement",
"xpack.stackConnectors.components.d3security.invalidActionText": "Nom d'action non valide.",
"xpack.stackConnectors.components.d3security.requiredActionText": "L'action est requise.",
Expand Down
Loading

0 comments on commit 398daa1

Please sign in to comment.