From 7bc63e07afb19760ee9a258cbc2f57d0aa5abaae Mon Sep 17 00:00:00 2001 From: Coen Warmer Date: Thu, 27 Oct 2022 15:20:43 +0200 Subject: [PATCH] Add context.alertDetailsUrl to connector template when configuring a Rule (#142854) --- x-pack/plugins/alerting/server/types.ts | 18 +-- .../lib/adapters/framework/adapter_types.ts | 8 +- .../server/lib/alerting/common/messages.ts | 10 +- .../infra/server/lib/alerting/common/utils.ts | 51 ++++++-- .../inventory_metric_threshold_executor.ts | 111 +++++++++++------- ...er_inventory_metric_threshold_rule_type.ts | 12 +- .../metric_threshold_executor.ts | 61 ++++++---- .../register_metric_threshold_rule_type.ts | 12 +- .../alerting/metric_threshold/test_mocks.ts | 4 - .../plugins/infra/server/lib/infra_types.ts | 10 +- x-pack/plugins/infra/server/plugin.ts | 1 + x-pack/plugins/observability/server/plugin.ts | 3 + .../server/utils/create_lifecycle_executor.ts | 38 ++++-- .../utils/create_lifecycle_rule_type.test.ts | 33 +++--- .../utils/lifecycle_alert_services.mock.ts | 1 + 15 files changed, 250 insertions(+), 123 deletions(-) diff --git a/x-pack/plugins/alerting/server/types.ts b/x-pack/plugins/alerting/server/types.ts index f1917a079a26d..9326f30dd7828 100644 --- a/x-pack/plugins/alerting/server/types.ts +++ b/x-pack/plugins/alerting/server/types.ts @@ -90,21 +90,21 @@ export interface RuleExecutorOptions< InstanceContext extends AlertInstanceContext = never, ActionGroupIds extends string = never > { - alertId: string; + alertId: string; // Is actually the Rule ID. Will be updated as part of https://github.com/elastic/kibana/issues/100115 + createdBy: string | null; executionId: string; - startedAt: Date; - previousStartedAt: Date | null; - services: RuleExecutorServices; + logger: Logger; + name: string; params: Params; - state: State; + previousStartedAt: Date | null; rule: SanitizedRuleConfig; + services: RuleExecutorServices; spaceId: string; - namespace?: string; - name: string; + startedAt: Date; + state: State; tags: string[]; - createdBy: string | null; updatedBy: string | null; - logger: Logger; + namespace?: string; } export interface RuleParamsAndRefs { diff --git a/x-pack/plugins/infra/server/lib/adapters/framework/adapter_types.ts b/x-pack/plugins/infra/server/lib/adapters/framework/adapter_types.ts index 64d389a1c0bf7..55b847d33f87d 100644 --- a/x-pack/plugins/infra/server/lib/adapters/framework/adapter_types.ts +++ b/x-pack/plugins/infra/server/lib/adapters/framework/adapter_types.ts @@ -22,16 +22,18 @@ import { SpacesPluginSetup } from '@kbn/spaces-plugin/server'; import { PluginSetupContract as AlertingPluginContract } from '@kbn/alerting-plugin/server'; import { MlPluginSetup } from '@kbn/ml-plugin/server'; import { RuleRegistryPluginSetupContract } from '@kbn/rule-registry-plugin/server'; +import { ObservabilityPluginSetup } from '@kbn/observability-plugin/server'; export interface InfraServerPluginSetupDeps { + alerting: AlertingPluginContract; data: DataPluginSetup; home: HomeServerPluginSetup; + features: FeaturesPluginSetup; + ruleRegistry: RuleRegistryPluginSetupContract; + observability: ObservabilityPluginSetup; spaces: SpacesPluginSetup; usageCollection: UsageCollectionSetup; visTypeTimeseries: VisTypeTimeseriesSetup; - features: FeaturesPluginSetup; - alerting: AlertingPluginContract; - ruleRegistry: RuleRegistryPluginSetupContract; ml?: MlPluginSetup; } diff --git a/x-pack/plugins/infra/server/lib/alerting/common/messages.ts b/x-pack/plugins/infra/server/lib/alerting/common/messages.ts index 80dae7ffac959..644c31813deae 100644 --- a/x-pack/plugins/infra/server/lib/alerting/common/messages.ts +++ b/x-pack/plugins/infra/server/lib/alerting/common/messages.ts @@ -169,6 +169,14 @@ export const alertStateActionVariableDescription = i18n.translate( } ); +export const alertDetailUrlActionVariableDescription = i18n.translate( + 'xpack.infra.metrics.alerting.alertDetailUrlActionVariableDescription', + { + defaultMessage: + 'Link to the view within Elastic that shows further details and context surrounding this alert', + } +); + export const reasonActionVariableDescription = i18n.translate( 'xpack.infra.metrics.alerting.reasonActionVariableDescription', { @@ -211,7 +219,7 @@ export const viewInAppUrlActionVariableDescription = i18n.translate( 'xpack.infra.metrics.alerting.viewInAppUrlActionVariableDescription', { defaultMessage: - 'Link to the view or feature within Elastic that can be used to investigate the alert and its context further', + 'Link to the view or feature within Elastic that can assist with further investigation', } ); diff --git a/x-pack/plugins/infra/server/lib/alerting/common/utils.ts b/x-pack/plugins/infra/server/lib/alerting/common/utils.ts index 2618af72168cd..ced80c75a3ef1 100644 --- a/x-pack/plugins/infra/server/lib/alerting/common/utils.ts +++ b/x-pack/plugins/infra/server/lib/alerting/common/utils.ts @@ -9,8 +9,11 @@ import { isEmpty, isError } from 'lodash'; import { schema } from '@kbn/config-schema'; import { Logger, LogMeta } from '@kbn/logging'; import type { IBasePath } from '@kbn/core/server'; +import { addSpaceIdToPath } from '@kbn/spaces-plugin/common'; +import { ObservabilityConfig } from '@kbn/observability-plugin/server'; import { ALERT_RULE_PARAMETERS, TIMESTAMP } from '@kbn/rule-data-utils'; import { parseTechnicalFields } from '@kbn/rule-registry-plugin/common/parse_technical_fields'; +import { LINK_TO_METRICS_EXPLORER } from '../../../../common/alerting/metrics'; import { getInventoryViewInAppUrl } from '../../../../common/alerting/metrics/alert_link'; import { AlertExecutionDetails, @@ -83,18 +86,30 @@ export const createScopedLogger = ( }; }; -export const getViewInAppUrl = (basePath: IBasePath, relativeViewInAppUrl: string) => - basePath.publicBaseUrl - ? new URL(basePath.prepend(relativeViewInAppUrl), basePath.publicBaseUrl).toString() - : relativeViewInAppUrl; +export const getAlertDetailsPageEnabledForApp = ( + config: ObservabilityConfig['unsafe']['alertDetails'] | null, + appName: keyof ObservabilityConfig['unsafe']['alertDetails'] +): boolean => { + if (!config) return false; -export const getViewInAppUrlInventory = ( - criteria: InventoryMetricConditions[], - nodeType: string, - timestamp: string, - basePath: IBasePath -) => { + return config[appName].enabled; +}; + +export const getViewInInventoryAppUrl = ({ + basePath, + criteria, + nodeType, + spaceId, + timestamp, +}: { + basePath: IBasePath; + criteria: InventoryMetricConditions[]; + nodeType: string; + spaceId: string; + timestamp: string; +}) => { const { metric, customMetric } = criteria[0]; + const fields = { [`${ALERT_RULE_PARAMETERS}.criteria.metric`]: [metric], [`${ALERT_RULE_PARAMETERS}.criteria.customMetric.id`]: [customMetric?.id], @@ -104,6 +119,18 @@ export const getViewInAppUrlInventory = ( [TIMESTAMP]: timestamp, }; - const relativeViewInAppUrl = getInventoryViewInAppUrl(parseTechnicalFields(fields, true)); - return getViewInAppUrl(basePath, relativeViewInAppUrl); + return addSpaceIdToPath( + basePath.publicBaseUrl, + spaceId, + getInventoryViewInAppUrl(parseTechnicalFields(fields, true)) + ); }; + +export const getViewInMetricsAppUrl = (basePath: IBasePath, spaceId: string) => + addSpaceIdToPath(basePath.publicBaseUrl, spaceId, LINK_TO_METRICS_EXPLORER); + +export const getAlertDetailsUrl = ( + basePath: IBasePath, + spaceId: string, + alertUuid: string | null +) => addSpaceIdToPath(basePath.publicBaseUrl, spaceId, `/app/observability/alerts/${alertUuid}`); diff --git a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts index 2e51d2e8291b5..20b804a2cc7db 100644 --- a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts @@ -30,7 +30,12 @@ import { buildNoDataAlertReason, stateToAlertMessage, } from '../common/messages'; -import { createScopedLogger, getViewInAppUrlInventory } from '../common/utils'; +import { + createScopedLogger, + getAlertDetailsUrl, + getViewInInventoryAppUrl, + UNGROUPED_FACTORY_KEY, +} from '../common/utils'; import { evaluateCondition, ConditionResult } from './evaluate_condition'; type InventoryMetricThresholdAllowedActionGroups = ActionGroupIdsOf< @@ -61,12 +66,18 @@ export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) = InventoryMetricThresholdAlertState, InventoryMetricThresholdAlertContext, InventoryMetricThresholdAllowedActionGroups - >(async ({ services, params, alertId, executionId, startedAt }) => { + >(async ({ services, params, alertId, executionId, spaceId, startedAt }) => { const startTime = Date.now(); + const { criteria, filterQuery, sourceId = 'default', nodeType, alertOnNoData } = params; + if (criteria.length === 0) throw new Error('Cannot execute an alert with 0 conditions'); + const logger = createScopedLogger(libs.logger, 'inventoryRule', { alertId, executionId }); - const { alertWithLifecycle, savedObjectsClient, getAlertStartedDate } = services; + + const esClient = services.scopedClusterClient.asCurrentUser; + + const { alertWithLifecycle, savedObjectsClient, getAlertStartedDate, getAlertUuid } = services; const alertFactory: InventoryMetricThresholdAlertFactory = (id, reason, additionalContext) => alertWithLifecycle({ id, @@ -85,23 +96,28 @@ export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) = logger.error(e.message); const actionGroupId = FIRED_ACTIONS.id; // Change this to an Error action group when able const reason = buildInvalidQueryAlertReason(params.filterQueryText); - const alert = alertFactory('*', reason); - const indexedStartedDate = getAlertStartedDate('*') ?? startedAt.toISOString(); - const viewInAppUrl = getViewInAppUrlInventory( - criteria, - nodeType, - indexedStartedDate, - libs.basePath - ); + const alert = alertFactory(UNGROUPED_FACTORY_KEY, reason); + const indexedStartedDate = + getAlertStartedDate(UNGROUPED_FACTORY_KEY) ?? startedAt.toISOString(); + const alertUuid = getAlertUuid(UNGROUPED_FACTORY_KEY); + alert.scheduleActions(actionGroupId, { - group: '*', + alertDetailsUrl: getAlertDetailsUrl(libs.basePath, spaceId, alertUuid), alertState: stateToAlertMessage[AlertStates.ERROR], + group: UNGROUPED_FACTORY_KEY, + metric: mapToConditionsLookup(criteria, (c) => c.metric), reason, timestamp: startedAt.toISOString(), - viewInAppUrl, value: null, - metric: mapToConditionsLookup(criteria, (c) => c.metric), + viewInAppUrl: getViewInInventoryAppUrl({ + basePath: libs.basePath, + criteria, + nodeType, + timestamp: indexedStartedDate, + spaceId, + }), }); + return {}; } } @@ -109,7 +125,7 @@ export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) = const [, , { logViews }] = await libs.getStartServices(); const logQueryFields: LogQueryFields | undefined = await logViews - .getClient(savedObjectsClient, services.scopedClusterClient.asCurrentUser) + .getClient(savedObjectsClient, esClient) .getResolvedLogView(sourceId) .then( ({ indices }) => ({ indexPattern: indices }), @@ -120,18 +136,19 @@ export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) = const results = await Promise.all( criteria.map((condition) => evaluateCondition({ - condition, - nodeType, - source, - logQueryFields, - esClient: services.scopedClusterClient.asCurrentUser, compositeSize, - filterQuery, + condition, + esClient, executionTimestamp: startedAt, + filterQuery, logger, + logQueryFields, + nodeType, + source, }) ) ); + let scheduledActionsCount = 0; const inventoryItems = Object.keys(first(results)!); for (const group of inventoryItems) { @@ -190,25 +207,28 @@ export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) = const alert = alertFactory(group, reason, additionalContext); const indexedStartedDate = getAlertStartedDate(group) ?? startedAt.toISOString(); - const viewInAppUrl = getViewInAppUrlInventory( - criteria, - nodeType, - indexedStartedDate, - libs.basePath - ); + const alertUuid = getAlertUuid(group); + scheduledActionsCount++; const context = { - group, + alertDetailsUrl: getAlertDetailsUrl(libs.basePath, spaceId, alertUuid), alertState: stateToAlertMessage[nextState], + group, reason, + metric: mapToConditionsLookup(criteria, (c) => c.metric), timestamp: startedAt.toISOString(), - viewInAppUrl, + threshold: mapToConditionsLookup(criteria, (c) => c.threshold), value: mapToConditionsLookup(results, (result) => formatMetric(result[group].metric, result[group].currentValue) ), - threshold: mapToConditionsLookup(criteria, (c) => c.threshold), - metric: mapToConditionsLookup(criteria, (c) => c.metric), + viewInAppUrl: getViewInInventoryAppUrl({ + basePath: libs.basePath, + criteria, + nodeType, + timestamp: indexedStartedDate, + spaceId, + }), ...additionalContext, }; alert.scheduleActions(actionGroupId, context); @@ -217,24 +237,27 @@ export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) = const { getRecoveredAlerts } = services.alertFactory.done(); const recoveredAlerts = getRecoveredAlerts(); + for (const alert of recoveredAlerts) { const recoveredAlertId = alert.getId(); const indexedStartedDate = getAlertStartedDate(recoveredAlertId) ?? startedAt.toISOString(); - const viewInAppUrl = getViewInAppUrlInventory( - criteria, - nodeType, - indexedStartedDate, - libs.basePath - ); - const context = { - group: recoveredAlertId, + const alertUuid = getAlertUuid(recoveredAlertId); + + alert.setContext({ + alertDetailsUrl: getAlertDetailsUrl(libs.basePath, spaceId, alertUuid), alertState: stateToAlertMessage[AlertStates.OK], - timestamp: startedAt.toISOString(), - viewInAppUrl, - threshold: mapToConditionsLookup(criteria, (c) => c.threshold), + group: recoveredAlertId, metric: mapToConditionsLookup(criteria, (c) => c.metric), - }; - alert.setContext(context); + threshold: mapToConditionsLookup(criteria, (c) => c.threshold), + timestamp: startedAt.toISOString(), + viewInAppUrl: getViewInInventoryAppUrl({ + basePath: libs.basePath, + criteria, + nodeType, + timestamp: indexedStartedDate, + spaceId, + }), + }); } const stopTime = Date.now(); diff --git a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_rule_type.ts b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_rule_type.ts index b3b1f5ba21c65..030628f59ad38 100644 --- a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_rule_type.ts +++ b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_rule_type.ts @@ -24,6 +24,7 @@ import { } from '../../../../common/inventory_models/types'; import { InfraBackendLibs } from '../../infra_types'; import { + alertDetailUrlActionVariableDescription, alertStateActionVariableDescription, cloudActionVariableDescription, containerActionVariableDescription, @@ -39,7 +40,11 @@ import { valueActionVariableDescription, viewInAppUrlActionVariableDescription, } from '../common/messages'; -import { oneOfLiterals, validateIsStringElasticsearchJSONFilter } from '../common/utils'; +import { + getAlertDetailsPageEnabledForApp, + oneOfLiterals, + validateIsStringElasticsearchJSONFilter, +} from '../common/utils'; import { createInventoryMetricThresholdExecutor, FIRED_ACTIONS, @@ -72,6 +77,8 @@ export async function registerMetricInventoryThresholdRuleType( alertingPlugin: PluginSetupContract, libs: InfraBackendLibs ) { + const config = libs.getAlertDetailsConfig(); + alertingPlugin.registerType({ id: METRIC_INVENTORY_THRESHOLD_ALERT_TYPE_ID, name: i18n.translate('xpack.infra.metrics.inventory.alertName', { @@ -102,6 +109,9 @@ export async function registerMetricInventoryThresholdRuleType( context: [ { name: 'group', description: groupActionVariableDescription }, { name: 'alertState', description: alertStateActionVariableDescription }, + ...(getAlertDetailsPageEnabledForApp(config, 'metrics') + ? [{ name: 'alertDetailsUrl', description: alertDetailUrlActionVariableDescription }] + : []), { name: 'reason', description: reasonActionVariableDescription }, { name: 'timestamp', description: timestampActionVariableDescription }, { name: 'value', description: valueActionVariableDescription }, diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts index 14b5fe8e75614..200ad68aa81d1 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts @@ -26,8 +26,12 @@ import { // buildRecoveredAlertReason, stateToAlertMessage, } from '../common/messages'; -import { UNGROUPED_FACTORY_KEY, getViewInAppUrl, createScopedLogger } from '../common/utils'; -import { LINK_TO_METRICS_EXPLORER } from '../../../../common/alerting/metrics'; +import { + createScopedLogger, + getAlertDetailsUrl, + getViewInMetricsAppUrl, + UNGROUPED_FACTORY_KEY, +} from '../common/utils'; import { EvaluatedRuleParams, evaluateRule } from './lib/evaluate_rule'; @@ -67,11 +71,16 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs) => MetricThresholdAllowedActionGroups >(async function (options) { const startTime = Date.now(); - const { services, params, state, startedAt, alertId, executionId } = options; + + const { services, params, state, startedAt, alertId, executionId, spaceId } = options; + const { criteria } = params; if (criteria.length === 0) throw new Error('Cannot execute an alert with 0 conditions'); + const logger = createScopedLogger(libs.logger, 'metricThresholdRule', { alertId, executionId }); - const { alertWithLifecycle, savedObjectsClient } = services; + + const { alertWithLifecycle, savedObjectsClient, getAlertUuid } = services; + const alertFactory: MetricThresholdAlertFactory = (id, reason) => alertWithLifecycle({ id, @@ -100,15 +109,19 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs) => const actionGroupId = FIRED_ACTIONS.id; // Change this to an Error action group when able const reason = buildInvalidQueryAlertReason(params.filterQueryText); const alert = alertFactory(UNGROUPED_FACTORY_KEY, reason); + const alertUuid = getAlertUuid(UNGROUPED_FACTORY_KEY); + alert.scheduleActions(actionGroupId, { - group: UNGROUPED_FACTORY_KEY, + alertDetailsUrl: getAlertDetailsUrl(libs.basePath, spaceId, alertUuid), alertState: stateToAlertMessage[AlertStates.ERROR], + group: UNGROUPED_FACTORY_KEY, + metric: mapToConditionsLookup(criteria, (c) => c.metric), reason, - viewInAppUrl: getViewInAppUrl(libs.basePath, LINK_TO_METRICS_EXPLORER), timestamp, value: null, - metric: mapToConditionsLookup(criteria, (c) => c.metric), + viewInAppUrl: getViewInMetricsAppUrl(libs.basePath, spaceId), }); + return { lastRunTimestamp: startedAt.valueOf(), missingGroups: [], @@ -157,6 +170,7 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs) => const hasGroups = !isEqual(groups, [UNGROUPED_FACTORY_KEY]); let scheduledActionsCount = 0; + // The key of `groups` is the alert instance ID. for (const group of groups) { // AND logic; all criteria must be across the threshold const shouldAlertFire = alertResults.every((result) => result[group]?.shouldFire); @@ -227,40 +241,45 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs) => ? WARNING_ACTIONS.id : FIRED_ACTIONS.id; const alert = alertFactory(`${group}`, reason); + const alertUuid = getAlertUuid(group); scheduledActionsCount++; + alert.scheduleActions(actionGroupId, { - group, + alertDetailsUrl: getAlertDetailsUrl(libs.basePath, spaceId, alertUuid), alertState: stateToAlertMessage[nextState], + group, + metric: mapToConditionsLookup(criteria, (c) => c.metric), reason, - viewInAppUrl: getViewInAppUrl(libs.basePath, LINK_TO_METRICS_EXPLORER), + threshold: mapToConditionsLookup( + alertResults, + (result) => formatAlertResult(result[group]).threshold + ), timestamp, value: mapToConditionsLookup( alertResults, (result) => formatAlertResult(result[group]).currentValue ), - threshold: mapToConditionsLookup( - alertResults, - (result) => formatAlertResult(result[group]).threshold - ), - metric: mapToConditionsLookup(criteria, (c) => c.metric), + viewInAppUrl: getViewInMetricsAppUrl(libs.basePath, spaceId), }); } } const { getRecoveredAlerts } = services.alertFactory.done(); const recoveredAlerts = getRecoveredAlerts(); + for (const alert of recoveredAlerts) { const recoveredAlertId = alert.getId(); - const viewInAppUrl = getViewInAppUrl(libs.basePath, LINK_TO_METRICS_EXPLORER); - const context = { - group: recoveredAlertId, + const alertUuid = getAlertUuid(recoveredAlertId); + + alert.setContext({ + alertDetailsUrl: getAlertDetailsUrl(libs.basePath, spaceId, alertUuid), alertState: stateToAlertMessage[AlertStates.OK], + group: recoveredAlertId, + metric: mapToConditionsLookup(criteria, (c) => c.metric), timestamp: startedAt.toISOString(), - viewInAppUrl, threshold: mapToConditionsLookup(criteria, (c) => c.threshold), - metric: mapToConditionsLookup(criteria, (c) => c.metric), - }; - alert.setContext(context); + viewInAppUrl: getViewInMetricsAppUrl(libs.basePath, spaceId), + }); } const stopTime = Date.now(); diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_rule_type.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_rule_type.ts index 0ebb427819f74..6538fb25b6c8c 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_rule_type.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_rule_type.ts @@ -13,6 +13,7 @@ import { Comparator, METRIC_THRESHOLD_ALERT_TYPE_ID } from '../../../../common/a import { METRIC_EXPLORER_AGGREGATIONS } from '../../../../common/http_api'; import { InfraBackendLibs } from '../../infra_types'; import { + alertDetailUrlActionVariableDescription, alertStateActionVariableDescription, groupActionVariableDescription, metricActionVariableDescription, @@ -22,7 +23,11 @@ import { valueActionVariableDescription, viewInAppUrlActionVariableDescription, } from '../common/messages'; -import { oneOfLiterals, validateIsStringElasticsearchJSONFilter } from '../common/utils'; +import { + getAlertDetailsPageEnabledForApp, + oneOfLiterals, + validateIsStringElasticsearchJSONFilter, +} from '../common/utils'; import { createMetricThresholdExecutor, FIRED_ACTIONS, @@ -41,6 +46,8 @@ export async function registerMetricThresholdRuleType( alertingPlugin: PluginSetupContract, libs: InfraBackendLibs ) { + const config = libs.getAlertDetailsConfig(); + const baseCriterion = { threshold: schema.arrayOf(schema.number()), comparator: oneOfLiterals(Object.values(Comparator)), @@ -93,6 +100,9 @@ export async function registerMetricThresholdRuleType( actionVariables: { context: [ { name: 'group', description: groupActionVariableDescription }, + ...(getAlertDetailsPageEnabledForApp(config, 'metrics') + ? [{ name: 'alertDetailsUrl', description: alertDetailUrlActionVariableDescription }] + : []), { name: 'alertState', description: alertStateActionVariableDescription }, { name: 'reason', description: reasonActionVariableDescription }, { name: 'timestamp', description: timestampActionVariableDescription }, diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/test_mocks.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/test_mocks.ts index 37e59700b0488..3d3c7a17cd1dd 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/test_mocks.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/test_mocks.ts @@ -4,10 +4,6 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import * as utils from '../common/utils'; -jest - .spyOn(utils, 'getViewInAppUrl') - .mockReturnValue('http://localhost:5601/eyg/app/metrics/explorer'); const bucketsA = (from: number) => [ { diff --git a/x-pack/plugins/infra/server/lib/infra_types.ts b/x-pack/plugins/infra/server/lib/infra_types.ts index a4636daa7986e..4801fb49651f6 100644 --- a/x-pack/plugins/infra/server/lib/infra_types.ts +++ b/x-pack/plugins/infra/server/lib/infra_types.ts @@ -8,6 +8,7 @@ import { Logger } from '@kbn/logging'; import type { IBasePath } from '@kbn/core/server'; import { handleEsError } from '@kbn/es-ui-shared-plugin/server'; +import { ObservabilityConfig } from '@kbn/observability-plugin/server'; import { RulesServiceSetup } from '../services/rules'; import { InfraConfig, InfraPluginStartServicesAccessor } from '../types'; import { KibanaFramework } from './adapters/framework/kibana_framework_adapter'; @@ -24,14 +25,15 @@ export interface InfraDomainLibs { } export interface InfraBackendLibs extends InfraDomainLibs { + basePath: IBasePath; configuration: InfraConfig; framework: KibanaFramework; - sources: InfraSources; - sourceStatus: InfraSourceStatus; - handleEsError: typeof handleEsError; logsRules: RulesServiceSetup; metricsRules: RulesServiceSetup; + sources: InfraSources; + sourceStatus: InfraSourceStatus; + getAlertDetailsConfig: () => ObservabilityConfig['unsafe']['alertDetails']; getStartServices: InfraPluginStartServicesAccessor; + handleEsError: typeof handleEsError; logger: Logger; - basePath: IBasePath; } diff --git a/x-pack/plugins/infra/server/plugin.ts b/x-pack/plugins/infra/server/plugin.ts index bfd7113ec4dc0..a7fa9ceacd3c9 100644 --- a/x-pack/plugins/infra/server/plugin.ts +++ b/x-pack/plugins/infra/server/plugin.ts @@ -170,6 +170,7 @@ export class InfraServerPlugin logsRules: this.logsRules.setup(core, plugins), metricsRules: this.metricsRules.setup(core, plugins), getStartServices: () => core.getStartServices(), + getAlertDetailsConfig: () => plugins.observability.getAlertDetailsConfig(), logger: this.logger, basePath: core.http.basePath, }; diff --git a/x-pack/plugins/observability/server/plugin.ts b/x-pack/plugins/observability/server/plugin.ts index ff5fd246bea1b..dd2a07f848db3 100644 --- a/x-pack/plugins/observability/server/plugin.ts +++ b/x-pack/plugins/observability/server/plugin.ts @@ -157,6 +157,9 @@ export class ObservabilityPlugin implements Plugin { }); return { + getAlertDetailsConfig() { + return config.unsafe.alertDetails; + }, getScopedAnnotationsClient: async (...args: Parameters) => { const api = await annotationsApiPromise; return api?.getScopedAnnotationsClient(...args); diff --git a/x-pack/plugins/rule_registry/server/utils/create_lifecycle_executor.ts b/x-pack/plugins/rule_registry/server/utils/create_lifecycle_executor.ts index 160e06d03e92a..615201fe44d99 100644 --- a/x-pack/plugins/rule_registry/server/utils/create_lifecycle_executor.ts +++ b/x-pack/plugins/rule_registry/server/utils/create_lifecycle_executor.ts @@ -68,7 +68,8 @@ export interface LifecycleAlertServices< ActionGroupIds extends string = never > { alertWithLifecycle: LifecycleAlertService; - getAlertStartedDate: (alertId: string) => string | null; + getAlertStartedDate: (alertInstanceId: string) => string | null; + getAlertUuid: (alertInstanceId: string) => string | null; } export type LifecycleRuleExecutor< @@ -88,6 +89,12 @@ export type LifecycleRuleExecutor< > ) => Promise; +/* + `alertId` will at some point be renamed to `ruleId` as that more + accurately describes the meaning of the variable. + See https://github.com/elastic/kibana/issues/100115 +*/ + const trackedAlertStateRt = rt.type({ alertId: rt.string, alertUuid: rt.string, @@ -159,6 +166,8 @@ export const createLifecycleExecutor = const currentAlerts: Record = {}; + const newAlertUuids: Record = {}; + const lifecycleAlertServices: LifecycleAlertServices< InstanceState, InstanceContext, @@ -169,6 +178,15 @@ export const createLifecycleExecutor = return alertFactory.create(id); }, getAlertStartedDate: (alertId: string) => state.trackedAlerts[alertId]?.started ?? null, + getAlertUuid: (alertId: string) => { + if (!state.trackedAlerts[alertId]) { + const alertUuid = v4(); + newAlertUuids[alertId] = alertUuid; + return alertUuid; + } + + return state.trackedAlerts[alertId].alertUuid; + }, }; const nextWrappedState = await wrappedExecutor({ @@ -203,9 +221,9 @@ export const createLifecycleExecutor = commonRuleFields ); result.forEach((hit) => { - const alertId = hit._source ? hit._source[ALERT_INSTANCE_ID] : void 0; - if (alertId && hit._source) { - trackedAlertsDataMap[alertId] = { + const alertInstanceId = hit._source ? hit._source[ALERT_INSTANCE_ID] : void 0; + if (alertInstanceId && hit._source) { + trackedAlertsDataMap[alertInstanceId] = { indexName: hit._index, fields: hit._source, }; @@ -226,10 +244,12 @@ export const createLifecycleExecutor = const isRecovered = !currentAlerts[alertId]; const isActive = !isRecovered; - const { alertUuid, started } = state.trackedAlerts[alertId] ?? { - alertUuid: v4(), - started: commonRuleFields[TIMESTAMP], - }; + const { alertUuid, started } = !isNew + ? state.trackedAlerts[alertId] + : { + alertUuid: newAlertUuids[alertId] || v4(), + started: commonRuleFields[TIMESTAMP], + }; const event: ParsedTechnicalFields & ParsedExperimentalFields = { ...alertData?.fields, @@ -249,8 +269,8 @@ export const createLifecycleExecutor = [ALERT_WORKFLOW_STATUS]: alertData?.fields[ALERT_WORKFLOW_STATUS] ?? 'open', [EVENT_KIND]: 'signal', [EVENT_ACTION]: isNew ? 'open' : isActive ? 'active' : 'close', - [VERSION]: ruleDataClient.kibanaVersion, [TAGS]: options.tags, + [VERSION]: ruleDataClient.kibanaVersion, ...(isRecovered ? { [ALERT_END]: commonRuleFields[TIMESTAMP] } : {}), }; diff --git a/x-pack/plugins/rule_registry/server/utils/create_lifecycle_rule_type.test.ts b/x-pack/plugins/rule_registry/server/utils/create_lifecycle_rule_type.test.ts index f71c7391cec77..132eb096e0aaa 100644 --- a/x-pack/plugins/rule_registry/server/utils/create_lifecycle_rule_type.test.ts +++ b/x-pack/plugins/rule_registry/server/utils/create_lifecycle_rule_type.test.ts @@ -40,6 +40,11 @@ function createRule(shouldWriteAlerts: boolean = true) { name: 'warning', }, ], + actionVariables: { + context: [], + params: [], + state: [], + }, defaultActionGroupId: 'warning', executor: async ({ services }) => { nextAlerts.forEach((alert) => { @@ -48,17 +53,17 @@ function createRule(shouldWriteAlerts: boolean = true) { nextAlerts = []; }, id: 'ruleTypeId', - minimumLicenseRequired: 'basic', isExportable: true, + minimumLicenseRequired: 'basic', name: 'ruleTypeName', producer: 'producer', - actionVariables: { - context: [], - params: [], - state: [], - }, validate: { - params: schema.object({}, { unknowns: 'allow' }), + params: schema.object( + {}, + { + unknowns: 'allow', + } + ), }, }); @@ -92,10 +97,12 @@ function createRule(shouldWriteAlerts: boolean = true) { state = ((await type.executor({ alertId: 'alertId', createdBy: 'createdBy', + executionId: 'b33f65d7-6e8b-4aae-8d20-c93613dec9f9', + logger: loggerMock.create(), name: 'name', + namespace: 'namespace', params: {}, previousStartedAt, - startedAt, rule: { actions: [], consumer: 'consumer', @@ -118,20 +125,18 @@ function createRule(shouldWriteAlerts: boolean = true) { services: { alertFactory, savedObjectsClient: {} as any, - uiSettingsClient: {} as any, scopedClusterClient: {} as any, - shouldWriteAlerts: () => shouldWriteAlerts, - shouldStopExecution: () => false, search: {} as any, searchSourceClient: {} as ISearchStartSearchSource, + shouldStopExecution: () => false, + shouldWriteAlerts: () => shouldWriteAlerts, + uiSettingsClient: {} as any, }, spaceId: 'spaceId', + startedAt, state, tags: ['tags'], updatedBy: 'updatedBy', - namespace: 'namespace', - executionId: 'b33f65d7-6e8b-4aae-8d20-c93613dec9f9', - logger: loggerMock.create(), })) ?? {}) as Record; previousStartedAt = startedAt; diff --git a/x-pack/plugins/rule_registry/server/utils/lifecycle_alert_services.mock.ts b/x-pack/plugins/rule_registry/server/utils/lifecycle_alert_services.mock.ts index 5465e7a7922c5..a383110394da7 100644 --- a/x-pack/plugins/rule_registry/server/utils/lifecycle_alert_services.mock.ts +++ b/x-pack/plugins/rule_registry/server/utils/lifecycle_alert_services.mock.ts @@ -36,4 +36,5 @@ export const createLifecycleAlertServicesMock = < ): LifecycleAlertServices => ({ alertWithLifecycle: ({ id }) => alertServices.alertFactory.create(id), getAlertStartedDate: jest.fn((id: string) => null), + getAlertUuid: jest.fn((id: string) => null), });