Reverting changes not related to event log aggregation

This commit is contained in:
Ying Mao 2022-03-07 11:17:54 -05:00
parent 188043d741
commit 939340e252
5 changed files with 1 additions and 207 deletions

View file

@ -30,7 +30,6 @@ export enum ReadOperations {
Get = 'get',
GetRuleState = 'getRuleState',
GetAlertSummary = 'getAlertSummary',
GetExecutionLog = 'getExecutionLog',
Find = 'find',
}

View file

@ -1,117 +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 { getRuleAlertSummaryRoute } from './get_rule_alert_summary';
import { httpServiceMock } from 'src/core/server/mocks';
import { licenseStateMock } from '../lib/license_state.mock';
import { mockHandlerArguments } from './_mock_handler_arguments';
import { SavedObjectsErrorHelpers } from 'src/core/server';
import { rulesClientMock } from '../rules_client.mock';
import { AlertSummary } from '../types';
const rulesClient = rulesClientMock.create();
jest.mock('../lib/license_api_access.ts', () => ({
verifyApiAccess: jest.fn(),
}));
beforeEach(() => {
jest.resetAllMocks();
});
describe('getRuleAlertSummaryRoute', () => {
const dateString = new Date().toISOString();
const mockedAlertSummary: AlertSummary = {
id: '',
name: '',
tags: [],
ruleTypeId: '',
consumer: '',
muteAll: false,
throttle: null,
enabled: false,
statusStartDate: dateString,
statusEndDate: dateString,
status: 'OK',
errorMessages: [],
alerts: {},
executionDuration: {
average: 1,
valuesWithTimestamp: {
'17 Nov 2021 @ 19:19:17': 3,
'18 Nov 2021 @ 19:19:17': 5,
'19 Nov 2021 @ 19:19:17': 5,
},
},
};
it('gets rule alert summary', async () => {
const licenseState = licenseStateMock.create();
const router = httpServiceMock.createRouter();
getRuleAlertSummaryRoute(router, licenseState);
const [config, handler] = router.get.mock.calls[0];
expect(config.path).toMatchInlineSnapshot(`"/internal/alerting/rule/{id}/_alert_summary"`);
rulesClient.getAlertSummary.mockResolvedValueOnce(mockedAlertSummary);
const [context, req, res] = mockHandlerArguments(
{ rulesClient },
{
params: {
id: '1',
},
query: {},
},
['ok']
);
await handler(context, req, res);
expect(rulesClient.getAlertSummary).toHaveBeenCalledTimes(1);
expect(rulesClient.getAlertSummary.mock.calls[0]).toMatchInlineSnapshot(`
Array [
Object {
"dateStart": undefined,
"id": "1",
"numberOfExecutions": undefined,
},
]
`);
expect(res.ok).toHaveBeenCalled();
});
it('returns NOT-FOUND when rule is not found', async () => {
const licenseState = licenseStateMock.create();
const router = httpServiceMock.createRouter();
getRuleAlertSummaryRoute(router, licenseState);
const [, handler] = router.get.mock.calls[0];
rulesClient.getAlertSummary = jest
.fn()
.mockRejectedValueOnce(SavedObjectsErrorHelpers.createGenericNotFoundError('alert', '1'));
const [context, req, res] = mockHandlerArguments(
{ rulesClient },
{
params: {
id: '1',
},
query: {},
},
['notFound']
);
expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(
`[Error: Saved object [alert/1] not found]`
);
});
});

View file

@ -20,7 +20,6 @@ import { disableRuleRoute } from './disable_rule';
import { enableRuleRoute } from './enable_rule';
import { findRulesRoute, findInternalRulesRoute } from './find_rules';
import { getRuleAlertSummaryRoute } from './get_rule_alert_summary';
import { getRuleExecutionLogRoute } from './get_rule_execution_log';
import { getRuleStateRoute } from './get_rule_state';
import { healthRoute } from './health';
import { resolveRuleRoute } from './resolve_rule';
@ -54,7 +53,6 @@ export function defineRoutes(opts: RouteOptions) {
findRulesRoute(router, licenseState, usageCounter);
findInternalRulesRoute(router, licenseState, usageCounter);
getRuleAlertSummaryRoute(router, licenseState);
getRuleExecutionLogRoute(router, licenseState);
getRuleStateRoute(router, licenseState);
healthRoute(router, licenseState, encryptedSavedObjects);
ruleTypesRoute(router, licenseState);

View file

@ -229,22 +229,6 @@ export interface GetAlertSummaryParams {
numberOfExecutions?: number;
}
export interface GetExecutionLogByIdParams {
id: string;
dateStart?: string;
// dateEnd?
}
export interface ExecutionLog {
count: number;
values: Array<{
timestamp: number;
duration: number;
status: 'failed' | 'succeeded';
message: string;
}>;
}
// NOTE: Changing this prefix will require a migration to update the prefix in all existing `rule` saved objects
const extractedSavedObjectParamReferenceNamePrefix = 'param:';
@ -647,76 +631,6 @@ export class RulesClient {
});
}
public async getExecutionLogForRule({
id,
dateStart,
}: // dateEnd?
GetExecutionLogByIdParams): Promise<ExecutionLog> {
this.logger.debug(`getExecutionLogForRule(): getting execution log for rule ${id}`);
const rule = (await this.get({ id, includeLegacyId: true })) as SanitizedRuleWithLegacyId;
// Make sure user has access to this rule
await this.authorization.ensureAuthorized({
ruleTypeId: rule.alertTypeId,
consumer: rule.consumer,
operation: ReadOperations.GetAlertSummary,
entity: AlertingAuthorizationEntity.Rule,
});
// default duration of instance summary is 60 * rule interval
const dateNow = new Date();
const durationMillis = parseDuration(rule.schedule.interval) * (numberOfExecutions ?? 60);
const defaultDateStart = new Date(dateNow.valueOf() - durationMillis);
const parsedDateStart = parseDate(dateStart, 'dateStart', defaultDateStart);
const eventLogClient = await this.getEventLogClient();
let events: IEvent[];
let executionEvents: IEvent[];
try {
const results = await eventLogClient.aggregateEventsBySavedObjectIds(
'alert',
[id],
{},
rule.legacyId !== null ? [rule.legacyId] : undefined
);
} catch (err) {
this.logger.debug(
`rulesClient.getExecutionLogForRule(): error searching event log for rule ${id}: ${err.message}`
);
}
// desired output
// {
// count: number;
// values: [
// {
// // this is shown in the screenshot
// executionTime: timestamp,
// duration: millis,
// status: failed/succeeded,
// message: log message - execution timeout is separate event log entry
// // other stuff that might be useful that we could probably get
// number of active alerts
// number of new alerts
// number of recovered alerts
// number of triggered actions
// any errors in the actions
// es search duration
// total search duration
// }
// ]
// }
return {
count: 0,
values: [],
};
}
public async find<Params extends RuleTypeParams = never>({
options: { fields, ...options } = {},
excludeFromPublicApi = false,

View file

@ -16,7 +16,7 @@ enum AlertingEntity {
}
const readOperations: Record<AlertingEntity, string[]> = {
rule: ['get', 'getRuleState', 'getAlertSummary', 'getExecutionLog', 'find'],
rule: ['get', 'getRuleState', 'getAlertSummary', 'find'],
alert: ['get', 'find'],
};