[RAC] Rename occurrences of alert_type to rule_type in Infra (#120455) (#120573)

[RAC] Rename occurrences of alert_type to rule_type in Infra

Co-authored-by: Ersin Erdal <92688503+ersin-erdal@users.noreply.github.com>
This commit is contained in:
Kibana Machine 2021-12-07 03:33:42 -05:00 committed by GitHub
parent 6844e06baf
commit 785faa4b04
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
23 changed files with 219 additions and 215 deletions

View file

@ -15,15 +15,15 @@ import {
import { ObservabilityRuleTypeModel } from '../../../../observability/public';
import { AlertTypeParams } from '../../../../alerting/common';
import { AlertTypeParams as RuleTypeParams } from '../../../../alerting/common';
import { validateMetricThreshold } from './components/validation';
import { formatReason } from './rule_data_formatters';
interface InventoryMetricAlertTypeParams extends AlertTypeParams {
interface InventoryMetricRuleTypeParams extends RuleTypeParams {
criteria: InventoryMetricConditions[];
}
export function createInventoryMetricAlertType(): ObservabilityRuleTypeModel<InventoryMetricAlertTypeParams> {
export function createInventoryMetricRuleType(): ObservabilityRuleTypeModel<InventoryMetricRuleTypeParams> {
return {
id: METRIC_INVENTORY_THRESHOLD_ALERT_TYPE_ID,
description: i18n.translate('xpack.infra.metrics.inventory.alertFlyout.alertDescription', {

View file

@ -5,5 +5,5 @@
* 2.0.
*/
export * from './log_threshold_alert_type';
export * from './log_threshold_rule_type';
export { AlertDropdown } from './components/alert_dropdown';

View file

@ -11,11 +11,11 @@ import { ObservabilityRuleTypeModel } from '../../../../observability/public';
import {
LOG_DOCUMENT_COUNT_ALERT_TYPE_ID,
PartialAlertParams,
} from '../../../common/alerting/logs/log_threshold/types';
} from '../../../common/alerting/logs/log_threshold';
import { formatRuleData } from './rule_data_formatters';
import { validateExpression } from './validation';
export function createLogThresholdAlertType(): ObservabilityRuleTypeModel<PartialAlertParams> {
export function createLogThresholdRuleType(): ObservabilityRuleTypeModel<PartialAlertParams> {
return {
id: LOG_DOCUMENT_COUNT_ALERT_TYPE_ID,
description: i18n.translate('xpack.infra.logs.alertFlyout.alertDescription', {

View file

@ -8,16 +8,15 @@
import { i18n } from '@kbn/i18n';
import React from 'react';
import { METRIC_ANOMALY_ALERT_TYPE_ID } from '../../../common/alerting/metrics';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { AlertTypeModel } from '../../../../triggers_actions_ui/public/types';
import { AlertTypeParams } from '../../../../alerting/common';
import { AlertTypeModel } from '../../../../triggers_actions_ui/public';
import { AlertTypeParams as RuleTypeParams } from '../../../../alerting/common';
import { validateMetricAnomaly } from './components/validation';
interface MetricAnomalyAlertTypeParams extends AlertTypeParams {
interface MetricAnomalyRuleTypeParams extends RuleTypeParams {
hasInfraMLCapabilities: boolean;
}
export function createMetricAnomalyAlertType(): AlertTypeModel<MetricAnomalyAlertTypeParams> {
export function createMetricAnomalyRuleType(): AlertTypeModel<MetricAnomalyRuleTypeParams> {
return {
id: METRIC_ANOMALY_ALERT_TYPE_ID,
description: i18n.translate('xpack.infra.metrics.anomaly.alertFlyout.alertDescription', {

View file

@ -10,18 +10,18 @@ import React from 'react';
import { ObservabilityRuleTypeModel } from '../../../../observability/public';
import { validateMetricThreshold } from './components/validation';
import { formatReason } from './rule_data_formatters';
import { AlertTypeParams } from '../../../../alerting/common';
import { AlertTypeParams as RuleTypeParams } from '../../../../alerting/common';
import {
MetricExpressionParams,
METRIC_THRESHOLD_ALERT_TYPE_ID,
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
} from '../../../server/lib/alerting/metric_threshold/types';
interface MetricThresholdAlertTypeParams extends AlertTypeParams {
interface MetricThresholdRuleTypeParams extends RuleTypeParams {
criteria: MetricExpressionParams[];
}
export function createMetricThresholdAlertType(): ObservabilityRuleTypeModel<MetricThresholdAlertTypeParams> {
export function createMetricThresholdRuleType(): ObservabilityRuleTypeModel<MetricThresholdRuleTypeParams> {
return {
id: METRIC_THRESHOLD_ALERT_TYPE_ID,
description: i18n.translate('xpack.infra.metrics.alertFlyout.alertDescription', {

View file

@ -31,19 +31,17 @@ export class Plugin implements InfraClientPluginClass {
registerFeatures(pluginsSetup.home);
}
const { createInventoryMetricAlertType } = await import('./alerting/inventory');
const { createLogThresholdAlertType } = await import('./alerting/log_threshold');
const { createMetricThresholdAlertType } = await import('./alerting/metric_threshold');
const { createInventoryMetricRuleType } = await import('./alerting/inventory');
const { createLogThresholdRuleType } = await import('./alerting/log_threshold');
const { createMetricThresholdRuleType } = await import('./alerting/metric_threshold');
pluginsSetup.observability.observabilityRuleTypeRegistry.register(
createInventoryMetricAlertType()
createInventoryMetricRuleType()
);
pluginsSetup.observability.observabilityRuleTypeRegistry.register(createLogThresholdRuleType());
pluginsSetup.observability.observabilityRuleTypeRegistry.register(
createLogThresholdAlertType()
);
pluginsSetup.observability.observabilityRuleTypeRegistry.register(
createMetricThresholdAlertType()
createMetricThresholdRuleType()
);
pluginsSetup.observability.dashboard.register({
appName: 'infra_logs',

View file

@ -5,4 +5,4 @@
* 2.0.
*/
export { registerAlertTypes } from './register_alert_types';
export { registerRuleTypes } from './register_rule_types';

View file

@ -8,18 +8,18 @@
import { mapValues, last, first } from 'lodash';
import moment from 'moment';
import { ElasticsearchClient } from 'kibana/server';
import { SnapshotCustomMetricInput } from '../../../../common/http_api/snapshot_api';
import {
isTooManyBucketsPreviewException,
TOO_MANY_BUCKETS_PREVIEW_EXCEPTION,
} from '../../../../common/alerting/metrics';
import {
InfraDatabaseSearchResponse,
CallWithRequestParams,
} from '../../adapters/framework/adapter_types';
import { InfraDatabaseSearchResponse, CallWithRequestParams } from '../../adapters/framework';
import { Comparator, InventoryMetricConditions } from './types';
import { InventoryItemType, SnapshotMetricType } from '../../../../common/inventory_models/types';
import { InfraTimerangeInput, SnapshotRequest } from '../../../../common/http_api/snapshot_api';
import {
InfraTimerangeInput,
SnapshotRequest,
SnapshotCustomMetricInput,
} from '../../../../common/http_api';
import { InfraSource } from '../../sources';
import { UNGROUPED_FACTORY_KEY } from '../common/utils';
import { getNodes } from '../../../routes/snapshot/lib/get_nodes';

View file

@ -15,11 +15,14 @@ import { AlertStates } from './types';
import {
ActionGroupIdsOf,
ActionGroup,
AlertInstanceContext,
AlertInstanceState,
AlertInstanceContext as AlertContext,
AlertInstanceState as AlertState,
RecoveredActionGroup,
} from '../../../../../alerting/common';
import { AlertInstance, AlertTypeState } from '../../../../../alerting/server';
import {
AlertInstance as Alert,
AlertTypeState as RuleTypeState,
} from '../../../../../alerting/server';
import { SnapshotMetricType } from '../../../../common/inventory_models/types';
import { InfraBackendLibs } from '../../infra_types';
import { METRIC_FORMATTERS } from '../../../../common/formatters/snapshot_metric_formats';
@ -39,34 +42,34 @@ type InventoryMetricThresholdAllowedActionGroups = ActionGroupIdsOf<
typeof FIRED_ACTIONS | typeof WARNING_ACTIONS
>;
export type InventoryMetricThresholdAlertTypeState = AlertTypeState; // no specific state used
export type InventoryMetricThresholdAlertInstanceState = AlertInstanceState; // no specific state used
export type InventoryMetricThresholdAlertInstanceContext = AlertInstanceContext; // no specific instance context used
export type InventoryMetricThresholdRuleTypeState = RuleTypeState; // no specific state used
export type InventoryMetricThresholdAlertState = AlertState; // no specific state used
export type InventoryMetricThresholdAlertContext = AlertContext; // no specific instance context used
type InventoryMetricThresholdAlertInstance = AlertInstance<
InventoryMetricThresholdAlertInstanceState,
InventoryMetricThresholdAlertInstanceContext,
type InventoryMetricThresholdAlert = Alert<
InventoryMetricThresholdAlertState,
InventoryMetricThresholdAlertContext,
InventoryMetricThresholdAllowedActionGroups
>;
type InventoryMetricThresholdAlertInstanceFactory = (
type InventoryMetricThresholdAlertFactory = (
id: string,
reason: string,
threshold?: number | undefined,
value?: number | undefined
) => InventoryMetricThresholdAlertInstance;
) => InventoryMetricThresholdAlert;
export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) =>
libs.metricsRules.createLifecycleRuleExecutor<
InventoryMetricThresholdParams & Record<string, unknown>,
InventoryMetricThresholdAlertTypeState,
InventoryMetricThresholdAlertInstanceState,
InventoryMetricThresholdAlertInstanceContext,
InventoryMetricThresholdRuleTypeState,
InventoryMetricThresholdAlertState,
InventoryMetricThresholdAlertContext,
InventoryMetricThresholdAllowedActionGroups
>(async ({ services, params }) => {
const { criteria, filterQuery, sourceId, nodeType, alertOnNoData } = params;
if (criteria.length === 0) throw new Error('Cannot execute an alert with 0 conditions');
const { alertWithLifecycle, savedObjectsClient } = services;
const alertInstanceFactory: InventoryMetricThresholdAlertInstanceFactory = (id, reason) =>
const alertFactory: InventoryMetricThresholdAlertFactory = (id, reason) =>
alertWithLifecycle({
id,
fields: {
@ -82,8 +85,8 @@ export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) =
} catch (e) {
const actionGroupId = FIRED_ACTIONS.id; // Change this to an Error action group when able
const reason = buildInvalidQueryAlertReason(params.filterQueryText);
const alertInstance = alertInstanceFactory('*', reason);
alertInstance.scheduleActions(actionGroupId, {
const alert = alertFactory('*', reason);
alert.scheduleActions(actionGroupId, {
group: '*',
alertState: stateToAlertMessage[AlertStates.ERROR],
reason,
@ -191,8 +194,8 @@ export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) =
? WARNING_ACTIONS.id
: FIRED_ACTIONS.id;
const alertInstance = alertInstanceFactory(`${group}`, reason);
alertInstance.scheduleActions(
const alert = alertFactory(`${group}`, reason);
alert.scheduleActions(
/**
* TODO: We're lying to the compiler here as explicitly calling `scheduleActions` on
* the RecoveredActionGroup isn't allowed

View file

@ -58,7 +58,7 @@ const condition = schema.object({
),
});
export async function registerMetricInventoryThresholdAlertType(
export async function registerMetricInventoryThresholdRuleType(
alertingPlugin: PluginSetupContract,
libs: InfraBackendLibs
) {

View file

@ -22,7 +22,7 @@ import {
Criterion,
UngroupedSearchQueryResponse,
GroupedSearchQueryResponse,
} from '../../../../common/alerting/logs/log_threshold/types';
} from '../../../../common/alerting/logs/log_threshold';
import { alertsMock } from '../../../../../alerting/server/mocks';
import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
@ -407,7 +407,7 @@ describe('Log threshold executor', () => {
describe('Results processors', () => {
describe('Can process ungrouped results', () => {
test('It handles the ALERT state correctly', () => {
const alertInstanceUpdaterMock = jest.fn();
const alertUpdaterMock = jest.fn();
const alertParams = {
...baseAlertParams,
criteria: [positiveCriteria[0]],
@ -423,12 +423,12 @@ describe('Log threshold executor', () => {
results,
alertParams,
alertsMock.createAlertInstanceFactory,
alertInstanceUpdaterMock
alertUpdaterMock
);
// First call, second argument
expect(alertInstanceUpdaterMock.mock.calls[0][1]).toBe(AlertStates.ALERT);
expect(alertUpdaterMock.mock.calls[0][1]).toBe(AlertStates.ALERT);
// First call, third argument
expect(alertInstanceUpdaterMock.mock.calls[0][2]).toEqual([
expect(alertUpdaterMock.mock.calls[0][2]).toEqual([
{
actionGroup: 'logs.threshold.fired',
context: {
@ -444,7 +444,7 @@ describe('Log threshold executor', () => {
describe('Can process grouped results', () => {
test('It handles the ALERT state correctly', () => {
const alertInstanceUpdaterMock = jest.fn();
const alertUpdaterMock = jest.fn();
const alertParams = {
...baseAlertParams,
criteria: [positiveCriteria[0]],
@ -487,13 +487,13 @@ describe('Log threshold executor', () => {
results,
alertParams,
alertsMock.createAlertInstanceFactory,
alertInstanceUpdaterMock
alertUpdaterMock
);
expect(alertInstanceUpdaterMock.mock.calls.length).toBe(2);
expect(alertUpdaterMock.mock.calls.length).toBe(2);
// First call, second argument
expect(alertInstanceUpdaterMock.mock.calls[0][1]).toBe(AlertStates.ALERT);
expect(alertUpdaterMock.mock.calls[0][1]).toBe(AlertStates.ALERT);
// First call, third argument
expect(alertInstanceUpdaterMock.mock.calls[0][2]).toEqual([
expect(alertUpdaterMock.mock.calls[0][2]).toEqual([
{
actionGroup: 'logs.threshold.fired',
context: {
@ -506,9 +506,9 @@ describe('Log threshold executor', () => {
]);
// Second call, second argument
expect(alertInstanceUpdaterMock.mock.calls[1][1]).toBe(AlertStates.ALERT);
expect(alertUpdaterMock.mock.calls[1][1]).toBe(AlertStates.ALERT);
// Second call, third argument
expect(alertInstanceUpdaterMock.mock.calls[1][2]).toEqual([
expect(alertUpdaterMock.mock.calls[1][2]).toEqual([
{
actionGroup: 'logs.threshold.fired',
context: {

View file

@ -16,10 +16,10 @@ import { ElasticsearchClient } from 'kibana/server';
import {
ActionGroup,
ActionGroupIdsOf,
AlertInstance,
AlertInstanceContext,
AlertInstanceState,
AlertTypeState,
AlertInstance as Alert,
AlertInstanceContext as AlertContext,
AlertInstanceState as AlertState,
AlertTypeState as RuleTypeState,
} from '../../../../../alerting/server';
import {
AlertParams,
@ -40,7 +40,7 @@ import {
RatioAlertParams,
UngroupedSearchQueryResponse,
UngroupedSearchQueryResponseRT,
} from '../../../../common/alerting/logs/log_threshold/types';
} from '../../../../common/alerting/logs/log_threshold';
import { resolveLogSourceConfiguration } from '../../../../common/log_sources';
import { decodeOrThrow } from '../../../../common/runtime_types';
import { getIntervalInSeconds } from '../../../utils/get_interval_in_seconds';
@ -54,22 +54,22 @@ import {
} from './reason_formatters';
export type LogThresholdActionGroups = ActionGroupIdsOf<typeof FIRED_ACTIONS>;
export type LogThresholdAlertTypeParams = AlertParams;
export type LogThresholdAlertTypeState = AlertTypeState; // no specific state used
export type LogThresholdAlertInstanceState = AlertInstanceState; // no specific state used
export type LogThresholdAlertInstanceContext = AlertInstanceContext; // no specific instance context used
export type LogThresholdRuleTypeParams = AlertParams;
export type LogThresholdRuleTypeState = RuleTypeState; // no specific state used
export type LogThresholdAlertState = AlertState; // no specific state used
export type LogThresholdAlertContext = AlertContext; // no specific instance context used
type LogThresholdAlertInstance = AlertInstance<
LogThresholdAlertInstanceState,
LogThresholdAlertInstanceContext,
type LogThresholdAlert = Alert<
LogThresholdAlertState,
LogThresholdAlertContext,
LogThresholdActionGroups
>;
type LogThresholdAlertInstanceFactory = (
type LogThresholdAlertFactory = (
id: string,
reason: string,
value: number,
threshold: number
) => LogThresholdAlertInstance;
) => LogThresholdAlert;
const COMPOSITE_GROUP_SIZE = 2000;
@ -88,15 +88,15 @@ const checkValueAgainstComparatorMap: {
export const createLogThresholdExecutor = (libs: InfraBackendLibs) =>
libs.logsRules.createLifecycleRuleExecutor<
LogThresholdAlertTypeParams,
LogThresholdAlertTypeState,
LogThresholdAlertInstanceState,
LogThresholdAlertInstanceContext,
LogThresholdRuleTypeParams,
LogThresholdRuleTypeState,
LogThresholdAlertState,
LogThresholdAlertContext,
LogThresholdActionGroups
>(async ({ services, params }) => {
const { alertWithLifecycle, savedObjectsClient, scopedClusterClient } = services;
const { sources } = libs;
const alertInstanceFactory: LogThresholdAlertInstanceFactory = (id, reason, value, threshold) =>
const alertFactory: LogThresholdAlertFactory = (id, reason, value, threshold) =>
alertWithLifecycle({
id,
fields: {
@ -125,7 +125,7 @@ export const createLogThresholdExecutor = (libs: InfraBackendLibs) =>
indices,
runtimeMappings,
scopedClusterClient.asCurrentUser,
alertInstanceFactory
alertFactory
);
} else {
await executeRatioAlert(
@ -134,7 +134,7 @@ export const createLogThresholdExecutor = (libs: InfraBackendLibs) =>
indices,
runtimeMappings,
scopedClusterClient.asCurrentUser,
alertInstanceFactory
alertFactory
);
}
} catch (e) {
@ -148,7 +148,7 @@ async function executeAlert(
indexPattern: string,
runtimeMappings: estypes.MappingRuntimeFields,
esClient: ElasticsearchClient,
alertInstanceFactory: LogThresholdAlertInstanceFactory
alertFactory: LogThresholdAlertFactory
) {
const query = getESQuery(alertParams, timestampField, indexPattern, runtimeMappings);
@ -160,15 +160,15 @@ async function executeAlert(
processGroupByResults(
await getGroupedResults(query, esClient),
alertParams,
alertInstanceFactory,
updateAlertInstance
alertFactory,
updateAlert
);
} else {
processUngroupedResults(
await getUngroupedResults(query, esClient),
alertParams,
alertInstanceFactory,
updateAlertInstance
alertFactory,
updateAlert
);
}
}
@ -179,7 +179,7 @@ async function executeRatioAlert(
indexPattern: string,
runtimeMappings: estypes.MappingRuntimeFields,
esClient: ElasticsearchClient,
alertInstanceFactory: LogThresholdAlertInstanceFactory
alertFactory: LogThresholdAlertFactory
) {
// Ratio alert params are separated out into two standard sets of alert params
const numeratorParams: AlertParams = {
@ -211,8 +211,8 @@ async function executeRatioAlert(
numeratorGroupedResults,
denominatorGroupedResults,
alertParams,
alertInstanceFactory,
updateAlertInstance
alertFactory,
updateAlert
);
} else {
const numeratorUngroupedResults = await getUngroupedResults(numeratorQuery, esClient);
@ -221,8 +221,8 @@ async function executeRatioAlert(
numeratorUngroupedResults,
denominatorUngroupedResults,
alertParams,
alertInstanceFactory,
updateAlertInstance
alertFactory,
updateAlert
);
}
}
@ -241,20 +241,20 @@ const getESQuery = (
export const processUngroupedResults = (
results: UngroupedSearchQueryResponse,
params: CountAlertParams,
alertInstanceFactory: LogThresholdAlertInstanceFactory,
alertInstaceUpdater: AlertInstanceUpdater
alertFactory: LogThresholdAlertFactory,
alertUpdater: AlertUpdater
) => {
const { count, criteria } = params;
const documentCount = results.hits.total.value;
if (checkValueAgainstComparatorMap[count.comparator](documentCount, count.value)) {
const alertInstance = alertInstanceFactory(
const alert = alertFactory(
UNGROUPED_FACTORY_KEY,
getReasonMessageForUngroupedCountAlert(documentCount, count.value, count.comparator),
documentCount,
count.value
);
alertInstaceUpdater(alertInstance, AlertStates.ALERT, [
alertUpdater(alert, AlertStates.ALERT, [
{
actionGroup: FIRED_ACTIONS.id,
context: {
@ -272,8 +272,8 @@ export const processUngroupedRatioResults = (
numeratorResults: UngroupedSearchQueryResponse,
denominatorResults: UngroupedSearchQueryResponse,
params: RatioAlertParams,
alertInstanceFactory: LogThresholdAlertInstanceFactory,
alertInstaceUpdater: AlertInstanceUpdater
alertFactory: LogThresholdAlertFactory,
alertUpdater: AlertUpdater
) => {
const { count, criteria } = params;
@ -282,13 +282,13 @@ export const processUngroupedRatioResults = (
const ratio = getRatio(numeratorCount, denominatorCount);
if (ratio !== undefined && checkValueAgainstComparatorMap[count.comparator](ratio, count.value)) {
const alertInstance = alertInstanceFactory(
const alert = alertFactory(
UNGROUPED_FACTORY_KEY,
getReasonMessageForUngroupedRatioAlert(ratio, count.value, count.comparator),
ratio,
count.value
);
alertInstaceUpdater(alertInstance, AlertStates.ALERT, [
alertUpdater(alert, AlertStates.ALERT, [
{
actionGroup: FIRED_ACTIONS.id,
context: {
@ -345,8 +345,8 @@ const getReducedGroupByResults = (
export const processGroupByResults = (
results: GroupedSearchQueryResponse['aggregations']['groups']['buckets'],
params: CountAlertParams,
alertInstanceFactory: LogThresholdAlertInstanceFactory,
alertInstaceUpdater: AlertInstanceUpdater
alertFactory: LogThresholdAlertFactory,
alertUpdater: AlertUpdater
) => {
const { count, criteria } = params;
@ -356,7 +356,7 @@ export const processGroupByResults = (
const documentCount = group.documentCount;
if (checkValueAgainstComparatorMap[count.comparator](documentCount, count.value)) {
const alertInstance = alertInstanceFactory(
const alert = alertFactory(
group.name,
getReasonMessageForGroupedCountAlert(
documentCount,
@ -367,7 +367,7 @@ export const processGroupByResults = (
documentCount,
count.value
);
alertInstaceUpdater(alertInstance, AlertStates.ALERT, [
alertUpdater(alert, AlertStates.ALERT, [
{
actionGroup: FIRED_ACTIONS.id,
context: {
@ -386,8 +386,8 @@ export const processGroupByRatioResults = (
numeratorResults: GroupedSearchQueryResponse['aggregations']['groups']['buckets'],
denominatorResults: GroupedSearchQueryResponse['aggregations']['groups']['buckets'],
params: RatioAlertParams,
alertInstanceFactory: LogThresholdAlertInstanceFactory,
alertInstaceUpdater: AlertInstanceUpdater
alertFactory: LogThresholdAlertFactory,
alertUpdater: AlertUpdater
) => {
const { count, criteria } = params;
@ -407,7 +407,7 @@ export const processGroupByRatioResults = (
ratio !== undefined &&
checkValueAgainstComparatorMap[count.comparator](ratio, count.value)
) {
const alertInstance = alertInstanceFactory(
const alert = alertFactory(
numeratorGroup.name,
getReasonMessageForGroupedRatioAlert(
ratio,
@ -418,7 +418,7 @@ export const processGroupByRatioResults = (
ratio,
count.value
);
alertInstaceUpdater(alertInstance, AlertStates.ALERT, [
alertUpdater(alert, AlertStates.ALERT, [
{
actionGroup: FIRED_ACTIONS.id,
context: {
@ -434,24 +434,24 @@ export const processGroupByRatioResults = (
});
};
type AlertInstanceUpdater = (
alertInstance: AlertInstance<AlertInstanceState, AlertInstanceContext, LogThresholdActionGroups>,
type AlertUpdater = (
alert: Alert<AlertState, AlertContext, LogThresholdActionGroups>,
state: AlertStates,
actions?: Array<{ actionGroup: LogThresholdActionGroups; context: AlertInstanceContext }>
actions?: Array<{ actionGroup: LogThresholdActionGroups; context: AlertContext }>
) => void;
export const updateAlertInstance: AlertInstanceUpdater = (alertInstance, state, actions) => {
export const updateAlert: AlertUpdater = (alert, state, actions) => {
if (actions && actions.length > 0) {
const sharedContext = {
timestamp: new Date().toISOString(),
};
actions.forEach((actionSet) => {
const { actionGroup, context } = actionSet;
alertInstance.scheduleActions(actionGroup, { ...sharedContext, ...context });
alert.scheduleActions(actionGroup, { ...sharedContext, ...context });
});
}
alertInstance.replaceState({
alert.replaceState({
alertState: state,
});
};

View file

@ -11,7 +11,7 @@ import { createLogThresholdExecutor, FIRED_ACTIONS } from './log_threshold_execu
import {
LOG_DOCUMENT_COUNT_ALERT_TYPE_ID,
alertParamsRT,
} from '../../../../common/alerting/logs/log_threshold/types';
} from '../../../../common/alerting/logs/log_threshold';
import { InfraBackendLibs } from '../../infra_types';
import { decodeOrThrow } from '../../../../common/runtime_types';
@ -71,7 +71,7 @@ const denominatorConditionsActionVariableDescription = i18n.translate(
}
);
export async function registerLogThresholdAlertType(
export async function registerLogThresholdRuleType(
alertingPlugin: PluginSetupContract,
libs: InfraBackendLibs
) {

View file

@ -8,20 +8,20 @@
import { i18n } from '@kbn/i18n';
import { first } from 'lodash';
import moment from 'moment';
import { KibanaRequest } from 'kibana/server';
import { stateToAlertMessage } from '../common/messages';
import { MetricAnomalyParams } from '../../../../common/alerting/metrics';
import { MappedAnomalyHit } from '../../infra_ml';
import { AlertStates } from '../common/types';
import {
ActionGroup,
AlertInstanceContext,
AlertInstanceState,
AlertInstanceContext as AlertContext,
AlertInstanceState as AlertState,
} from '../../../../../alerting/common';
import { AlertExecutorOptions } from '../../../../../alerting/server';
import { AlertExecutorOptions as RuleExecutorOptions } from '../../../../../alerting/server';
import { getIntervalInSeconds } from '../../../utils/get_interval_in_seconds';
import { MetricAnomalyAllowedActionGroups } from './register_metric_anomaly_alert_type';
import { MetricAnomalyAllowedActionGroups } from './register_metric_anomaly_rule_type';
import { MlPluginSetup } from '../../../../../ml/server';
import { KibanaRequest } from '../../../../../../../src/core/server';
import { InfraBackendLibs } from '../../infra_types';
import { evaluateCondition } from './evaluate_condition';
@ -31,14 +31,14 @@ export const createMetricAnomalyExecutor =
services,
params,
startedAt,
}: AlertExecutorOptions<
}: RuleExecutorOptions<
/**
* TODO: Remove this use of `any` by utilizing a proper type
*/
Record<string, any>,
Record<string, any>,
AlertInstanceState,
AlertInstanceContext,
AlertState,
AlertContext,
MetricAnomalyAllowedActionGroups
>) => {
if (!ml) {
@ -84,9 +84,9 @@ export const createMetricAnomalyExecutor =
typical,
influencers,
} = first(data as MappedAnomalyHit[])!;
const alertInstance = services.alertInstanceFactory(`${nodeType}-${metric}`);
const alert = services.alertInstanceFactory(`${nodeType}-${metric}`);
alertInstance.scheduleActions(FIRED_ACTIONS_ID, {
alert.scheduleActions(FIRED_ACTIONS_ID, {
alertState: stateToAlertMessage[AlertStates.ALERT],
timestamp: moment(anomalyStartTime).toISOString(),
anomalyScore,

View file

@ -9,9 +9,9 @@ import { schema } from '@kbn/config-schema';
import { i18n } from '@kbn/i18n';
import { MlPluginSetup } from '../../../../../ml/server';
import {
AlertType,
AlertInstanceState,
AlertInstanceContext,
AlertType as RuleType,
AlertInstanceState as AlertState,
AlertInstanceContext as AlertContext,
} from '../../../../../alerting/server';
import {
createMetricAnomalyExecutor,
@ -26,18 +26,18 @@ import { RecoveredActionGroupId } from '../../../../../alerting/common';
export type MetricAnomalyAllowedActionGroups = typeof FIRED_ACTIONS_ID;
export const registerMetricAnomalyAlertType = (
export const registerMetricAnomalyRuleType = (
libs: InfraBackendLibs,
ml?: MlPluginSetup
): AlertType<
): RuleType<
/**
* TODO: Remove this use of `any` by utilizing a proper type
*/
Record<string, any>,
never, // Only use if defining useSavedObjectReferences hook
Record<string, any>,
AlertInstanceState,
AlertInstanceContext,
AlertState,
AlertContext,
MetricAnomalyAllowedActionGroups,
RecoveredActionGroupId
> => ({

View file

@ -53,7 +53,7 @@ interface CompositeAggregationsResponse {
};
}
export interface EvaluatedAlertParams {
export interface EvaluatedRuleParams {
criteria: MetricExpressionParams[];
groupBy: string | undefined | string[];
filterQuery?: string;
@ -61,7 +61,7 @@ export interface EvaluatedAlertParams {
shouldDropPartialBuckets?: boolean;
}
export const evaluateAlert = <Params extends EvaluatedAlertParams = EvaluatedAlertParams>(
export const evaluateRule = <Params extends EvaluatedRuleParams = EvaluatedRuleParams>(
esClient: ElasticsearchClient,
params: Params,
config: InfraSource['configuration'],

View file

@ -19,7 +19,10 @@ import { createLifecycleRuleExecutorMock } from '../../../../../rule_registry/se
import { InfraSources } from '../../sources';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mocks';
import { AlertInstanceContext, AlertInstanceState } from '../../../../../alerting/server';
import {
AlertInstanceContext as AlertContext,
AlertInstanceState as AlertState,
} from '../../../../../alerting/server';
import {
Aggregators,
Comparator,
@ -763,8 +766,7 @@ const mockLibs: any = {
const executor = createMetricThresholdExecutor(mockLibs);
const alertsServices = alertsMock.createAlertServices();
const services: AlertServicesMock &
LifecycleAlertServices<AlertInstanceState, AlertInstanceContext, string> = {
const services: AlertServicesMock & LifecycleAlertServices<AlertState, AlertContext, string> = {
...alertsServices,
...ruleRegistryMocks.createLifecycleAlertServices(alertsServices),
};

View file

@ -12,10 +12,13 @@ import { ALERT_REASON } from '@kbn/rule-data-utils';
import {
ActionGroupIdsOf,
RecoveredActionGroup,
AlertInstanceState,
AlertInstanceContext,
AlertInstanceState as AlertState,
AlertInstanceContext as AlertContext,
} from '../../../../../alerting/common';
import { AlertTypeState, AlertInstance } from '../../../../../alerting/server';
import {
AlertTypeState as RuleTypeState,
AlertInstance as Alert,
} from '../../../../../alerting/server';
import { InfraBackendLibs } from '../../infra_types';
import {
buildErrorAlertReason,
@ -28,47 +31,47 @@ import {
import { UNGROUPED_FACTORY_KEY } from '../common/utils';
import { createFormatter } from '../../../../common/formatters';
import { AlertStates, Comparator } from './types';
import { evaluateAlert, EvaluatedAlertParams } from './lib/evaluate_alert';
import { evaluateRule, EvaluatedRuleParams } from './lib/evaluate_rule';
export type MetricThresholdAlertTypeParams = Record<string, any>;
export type MetricThresholdAlertTypeState = AlertTypeState & {
export type MetricThresholdRuleParams = Record<string, any>;
export type MetricThresholdRuleTypeState = RuleTypeState & {
groups: string[];
groupBy?: string | string[];
filterQuery?: string;
};
export type MetricThresholdAlertInstanceState = AlertInstanceState; // no specific instace state used
export type MetricThresholdAlertInstanceContext = AlertInstanceContext; // no specific instace state used
export type MetricThresholdAlertState = AlertState; // no specific instace state used
export type MetricThresholdAlertContext = AlertContext; // no specific instace state used
type MetricThresholdAllowedActionGroups = ActionGroupIdsOf<
typeof FIRED_ACTIONS | typeof WARNING_ACTIONS
>;
type MetricThresholdAlertInstance = AlertInstance<
MetricThresholdAlertInstanceState,
MetricThresholdAlertInstanceContext,
type MetricThresholdAlert = Alert<
MetricThresholdAlertState,
MetricThresholdAlertContext,
MetricThresholdAllowedActionGroups
>;
type MetricThresholdAlertInstanceFactory = (
type MetricThresholdAlertFactory = (
id: string,
reason: string,
threshold?: number | undefined,
value?: number | undefined
) => MetricThresholdAlertInstance;
) => MetricThresholdAlert;
export const createMetricThresholdExecutor = (libs: InfraBackendLibs) =>
libs.metricsRules.createLifecycleRuleExecutor<
MetricThresholdAlertTypeParams,
MetricThresholdAlertTypeState,
MetricThresholdAlertInstanceState,
MetricThresholdAlertInstanceContext,
MetricThresholdRuleParams,
MetricThresholdRuleTypeState,
MetricThresholdAlertState,
MetricThresholdAlertContext,
MetricThresholdAllowedActionGroups
>(async function (options) {
const { services, params, state } = options;
const { criteria } = params;
if (criteria.length === 0) throw new Error('Cannot execute an alert with 0 conditions');
const { alertWithLifecycle, savedObjectsClient } = services;
const alertInstanceFactory: MetricThresholdAlertInstanceFactory = (id, reason) =>
const alertFactory: MetricThresholdAlertFactory = (id, reason) =>
alertWithLifecycle({
id,
fields: {
@ -94,8 +97,8 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs) =>
const timestamp = moment().toISOString();
const actionGroupId = FIRED_ACTIONS.id; // Change this to an Error action group when able
const reason = buildInvalidQueryAlertReason(params.filterQueryText);
const alertInstance = alertInstanceFactory(UNGROUPED_FACTORY_KEY, reason);
alertInstance.scheduleActions(actionGroupId, {
const alert = alertFactory(UNGROUPED_FACTORY_KEY, reason);
alert.scheduleActions(actionGroupId, {
group: UNGROUPED_FACTORY_KEY,
alertState: stateToAlertMessage[AlertStates.ERROR],
reason,
@ -128,9 +131,9 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs) =>
state.groups?.filter((g) => g !== UNGROUPED_FACTORY_KEY) ?? []
: [];
const alertResults = await evaluateAlert(
const alertResults = await evaluateRule(
services.scopedClusterClient.asCurrentUser,
params as EvaluatedAlertParams,
params as EvaluatedRuleParams,
config,
prevGroups
);
@ -227,8 +230,8 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs) =>
: nextState === AlertStates.WARNING
? WARNING_ACTIONS.id
: FIRED_ACTIONS.id;
const alertInstance = alertInstanceFactory(`${group}`, reason);
alertInstance.scheduleActions(actionGroupId, {
const alert = alertFactory(`${group}`, reason);
alert.scheduleActions(actionGroupId, {
group,
alertState: stateToAlertMessage[nextState],
reason,

View file

@ -9,7 +9,7 @@ import { schema } from '@kbn/config-schema';
import { i18n } from '@kbn/i18n';
import { ActionGroupIdsOf } from '../../../../../alerting/common';
import { AlertType, PluginSetupContract } from '../../../../../alerting/server';
import { METRIC_EXPLORER_AGGREGATIONS } from '../../../../common/http_api/metrics_explorer';
import { METRIC_EXPLORER_AGGREGATIONS } from '../../../../common/http_api';
import {
createMetricThresholdExecutor,
FIRED_ACTIONS,
@ -35,7 +35,7 @@ export type MetricThresholdAlertType = Omit<AlertType, 'ActionGroupIdsOf'> & {
ActionGroupIdsOf: MetricThresholdAllowedActionGroups;
};
export async function registerMetricThresholdAlertType(
export async function registerMetricThresholdRuleType(
alertingPlugin: PluginSetupContract,
libs: InfraBackendLibs
) {

View file

@ -1,36 +0,0 @@
/*
* 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 { PluginSetupContract } from '../../../../alerting/server';
import { registerMetricThresholdAlertType } from './metric_threshold/register_metric_threshold_alert_type';
import { registerMetricInventoryThresholdAlertType } from './inventory_metric_threshold/register_inventory_metric_threshold_alert_type';
import { registerMetricAnomalyAlertType } from './metric_anomaly/register_metric_anomaly_alert_type';
import { registerLogThresholdAlertType } from './log_threshold/register_log_threshold_alert_type';
import { InfraBackendLibs } from '../infra_types';
import { MlPluginSetup } from '../../../../ml/server';
const registerAlertTypes = (
alertingPlugin: PluginSetupContract,
libs: InfraBackendLibs,
ml?: MlPluginSetup
) => {
if (alertingPlugin) {
alertingPlugin.registerType(registerMetricAnomalyAlertType(libs, ml));
const registerFns = [
registerLogThresholdAlertType,
registerMetricInventoryThresholdAlertType,
registerMetricThresholdAlertType,
];
registerFns.forEach((fn) => {
fn(alertingPlugin, libs);
});
}
};
export { registerAlertTypes };

View file

@ -0,0 +1,35 @@
/*
* 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 { PluginSetupContract } from '../../../../alerting/server';
import { registerMetricThresholdRuleType } from './metric_threshold/register_metric_threshold_rule_type';
import { registerMetricInventoryThresholdRuleType } from './inventory_metric_threshold/register_inventory_metric_threshold_rule_type';
import { registerMetricAnomalyRuleType } from './metric_anomaly/register_metric_anomaly_rule_type';
import { registerLogThresholdRuleType } from './log_threshold/register_log_threshold_rule_type';
import { InfraBackendLibs } from '../infra_types';
import { MlPluginSetup } from '../../../../ml/server';
const registerRuleTypes = (
alertingPlugin: PluginSetupContract,
libs: InfraBackendLibs,
ml?: MlPluginSetup
) => {
if (alertingPlugin) {
alertingPlugin.registerType(registerMetricAnomalyRuleType(libs, ml));
const registerFns = [
registerLogThresholdRuleType,
registerMetricInventoryThresholdRuleType,
registerMetricThresholdRuleType,
];
registerFns.forEach((fn) => {
fn(alertingPlugin, libs);
});
}
};
export { registerRuleTypes };

View file

@ -27,7 +27,7 @@ import { KibanaFramework } from './lib/adapters/framework/kibana_framework_adapt
import { InfraKibanaLogEntriesAdapter } from './lib/adapters/log_entries/kibana_log_entries_adapter';
import { KibanaMetricsAdapter } from './lib/adapters/metrics/kibana_metrics_adapter';
import { InfraElasticsearchSourceStatusAdapter } from './lib/adapters/source_status';
import { registerAlertTypes } from './lib/alerting';
import { registerRuleTypes } from './lib/alerting';
import { InfraFieldsDomain } from './lib/domains/fields_domain';
import { InfraLogEntriesDomain } from './lib/domains/log_entries_domain';
import { InfraMetricsDomain } from './lib/domains/metrics_domain';
@ -161,7 +161,7 @@ export class InfraServerPlugin implements Plugin<InfraPluginSetup> {
]);
initInfraServer(this.libs);
registerAlertTypes(plugins.alerting, this.libs, plugins.ml);
registerRuleTypes(plugins.alerting, this.libs, plugins.ml);
core.http.registerRouteHandlerContext<InfraPluginRequestHandlerContext, 'infra'>(
'infra',

View file

@ -10,9 +10,9 @@ import { convertToKibanaClient } from '@kbn/test';
import { InfraSource } from '../../../../plugins/infra/common/source_configuration/source_configuration';
import { FtrProviderContext } from '../../ftr_provider_context';
import {
evaluateAlert,
EvaluatedAlertParams,
} from '../../../../plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert';
evaluateRule,
EvaluatedRuleParams,
} from '../../../../plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_rule';
import {
Aggregators,
CountMetricExpressionParams,
@ -27,7 +27,7 @@ export default function ({ getService }: FtrProviderContext) {
const esArchiver = getService('esArchiver');
const esClient = getService('es');
const baseParams: EvaluatedAlertParams = {
const baseParams: EvaluatedRuleParams = {
groupBy: void 0,
filterQuery: void 0,
criteria: [
@ -100,7 +100,7 @@ export default function ({ getService }: FtrProviderContext) {
};
const timeFrame = { end: DATES.ten_thousand_plus.max };
const kbnClient = convertToKibanaClient(esClient);
const results = await evaluateAlert(kbnClient, params, config, [], timeFrame);
const results = await evaluateRule(kbnClient, params, config, [], timeFrame);
expect(results).to.eql([
{
'*': {
@ -142,7 +142,7 @@ export default function ({ getService }: FtrProviderContext) {
};
const timeFrame = { end: DATES.ten_thousand_plus.max };
const kbnClient = convertToKibanaClient(esClient);
const results = await evaluateAlert(kbnClient, params, config, [], timeFrame);
const results = await evaluateRule(kbnClient, params, config, [], timeFrame);
expect(results).to.eql([
{
web: {
@ -184,7 +184,7 @@ export default function ({ getService }: FtrProviderContext) {
};
const timeFrame = { end: gauge.max };
const kbnClient = convertToKibanaClient(esClient);
const results = await evaluateAlert(kbnClient, params, configuration, [], timeFrame);
const results = await evaluateRule(kbnClient, params, configuration, [], timeFrame);
expect(results).to.eql([
{
'*': {
@ -208,7 +208,7 @@ export default function ({ getService }: FtrProviderContext) {
const params = { ...baseParams };
const timeFrame = { end: gauge.max };
const kbnClient = convertToKibanaClient(esClient);
const results = await evaluateAlert(kbnClient, params, configuration, [], timeFrame);
const results = await evaluateRule(kbnClient, params, configuration, [], timeFrame);
expect(results).to.eql([
{
'*': {
@ -246,7 +246,7 @@ export default function ({ getService }: FtrProviderContext) {
};
const timeFrame = { end: gauge.max };
const kbnClient = convertToKibanaClient(esClient);
const results = await evaluateAlert(kbnClient, params, configuration, [], timeFrame);
const results = await evaluateRule(kbnClient, params, configuration, [], timeFrame);
expect(results).to.eql([
{
dev: {
@ -287,7 +287,7 @@ export default function ({ getService }: FtrProviderContext) {
};
const timeFrame = { end: gauge.max };
const kbnClient = convertToKibanaClient(esClient);
const results = await evaluateAlert(kbnClient, params, configuration, [], timeFrame);
const results = await evaluateRule(kbnClient, params, configuration, [], timeFrame);
expect(results).to.eql([
{
dev: {
@ -329,7 +329,7 @@ export default function ({ getService }: FtrProviderContext) {
};
const timeFrame = { end: gauge.midpoint };
const kbnClient = convertToKibanaClient(esClient);
const results = await evaluateAlert(
const results = await evaluateRule(
kbnClient,
params,
configuration,
@ -392,7 +392,7 @@ export default function ({ getService }: FtrProviderContext) {
};
const timeFrame = { end: rate.max };
const kbnClient = convertToKibanaClient(esClient);
const results = await evaluateAlert(kbnClient, params, configuration, [], timeFrame);
const results = await evaluateRule(kbnClient, params, configuration, [], timeFrame);
expect(results).to.eql([
{
'*': {
@ -433,7 +433,7 @@ export default function ({ getService }: FtrProviderContext) {
};
const timeFrame = { end: rate.max };
const kbnClient = convertToKibanaClient(esClient);
const results = await evaluateAlert(kbnClient, params, configuration, [], timeFrame);
const results = await evaluateRule(kbnClient, params, configuration, [], timeFrame);
expect(results).to.eql([
{
dev: {