Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RAM] Add data model for scheduled and recurring snoozes #131019

Merged
merged 60 commits into from
May 18, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
a98faba
[RAM] Add data model for scheduled and recurring snoozes
Zacqary Apr 26, 2022
fdbe1b5
Merge remote-tracking branch 'upstream/main' into 130724-snooze-sched…
Zacqary Apr 26, 2022
bc20443
Update migration tests
Zacqary Apr 26, 2022
de7a37f
Make snoozeIndefinitely required
Zacqary Apr 26, 2022
7fec109
Fix remaining muteAlls
Zacqary Apr 26, 2022
ab4f21b
Replace snoozeEndTime with snoozeSchedule
Zacqary Apr 26, 2022
27c5702
Merge remote-tracking branch 'upstream/main' into 130724-snooze-sched…
Zacqary Apr 26, 2022
29173d8
Fix typecheck
Zacqary Apr 26, 2022
0822788
Merge branch 'main' into 130724-snooze-sched-datamodel
Zacqary Apr 26, 2022
274c0c0
Fix typecheck
Zacqary Apr 26, 2022
cabd5c3
Merge branch '130724-snooze-sched-datamodel' of https://github.com/Za…
Zacqary Apr 26, 2022
7c918a5
Revert muteAll => snoozeIndefinitely rename
Zacqary Apr 27, 2022
5b57cb8
Revert more snoozeIndefinitely refs
Zacqary Apr 27, 2022
5df3868
Revert README
Zacqary Apr 27, 2022
7f8acf1
Merge remote-tracking branch 'upstream/main' into 130724-snooze-sched…
Zacqary Apr 27, 2022
d128eac
Restore updated taskrunner test
Zacqary Apr 27, 2022
59c5a1b
Fix RuleStatusDropdown test
Zacqary Apr 27, 2022
03d2d29
Add timeZone to SO
Zacqary Apr 28, 2022
32344fe
Merge remote-tracking branch 'upstream/main' into 130724-snooze-sched…
Zacqary Apr 28, 2022
e3c28e8
Update timezone usage
Zacqary Apr 28, 2022
b93d460
Implement RRule
Zacqary Apr 28, 2022
f9dfc6e
Merge remote-tracking branch 'upstream/main' into 130724-snooze-sched…
Zacqary Apr 29, 2022
370fd45
Fix task runner test
Zacqary Apr 29, 2022
6dda9a2
Add rrule types
Zacqary Apr 29, 2022
128950f
Push snoozeEndTime from server and fix unsnooze
Zacqary Apr 29, 2022
8f3546f
Fix Jest Tests 5
Zacqary Apr 29, 2022
8b69fad
Fix rulestatusdropdown test
Zacqary Apr 29, 2022
01ae2b2
Fix jest tests 1
Zacqary Apr 29, 2022
3af6c23
Fix snooze_end_time refs in functional tests
Zacqary Apr 29, 2022
c526de9
Fix snooze API integration tests
Zacqary May 2, 2022
6527c36
Move isRuleSnoozed to server
Zacqary May 2, 2022
0f9826b
Merge remote-tracking branch 'upstream/main' into 130724-snooze-sched…
Zacqary May 2, 2022
7eec7af
Update x-pack/plugins/alerting/server/lib/is_rule_snoozed.ts
Zacqary May 4, 2022
41414cb
Require timeZone in rulesnooze
Zacqary May 4, 2022
fda4b4b
Merge remote-tracking branch 'upstream/main' into 130724-snooze-sched…
Zacqary May 4, 2022
d2542a5
Merge remote-tracking branch 'upstream/main' into 130724-snooze-sched…
Zacqary May 4, 2022
fadb744
Merge remote-tracking branch 'upstream/main' into 130724-snooze-sched…
Zacqary May 10, 2022
0603855
Add automatic isSnoozedUntil savedobject flag
Zacqary May 10, 2022
fc99605
Check isSnoozedUntil against now
Zacqary May 10, 2022
857c36f
Fix jest
Zacqary May 11, 2022
4e1cc32
Merge remote-tracking branch 'upstream/main' into 130724-snooze-sched…
Zacqary May 11, 2022
52f281f
Fix typecheck
Zacqary May 11, 2022
92511d2
Merge remote-tracking branch 'upstream/main' into 130724-snooze-sched…
Zacqary May 11, 2022
2434080
Fix jest
Zacqary May 11, 2022
70a2aa7
Fix snoozedUntil date parsing
Zacqary May 11, 2022
3646458
Fix rewriterule
Zacqary May 12, 2022
2c53cb7
Add error handling for RRule
Zacqary May 12, 2022
ed75133
Fix re-snoozing
Zacqary May 16, 2022
20c37dc
Merge remote-tracking branch 'upstream/main' into 130724-snooze-sched…
Zacqary May 16, 2022
083782c
Add comments to rulesnoozetype
Zacqary May 16, 2022
f11125d
Restructure data model to use rRule for everything
Zacqary May 16, 2022
409c606
Fix functional tests
Zacqary May 16, 2022
eb1f391
Fix jest
Zacqary May 17, 2022
ffeb94d
Fix functional tests
Zacqary May 17, 2022
f8fe600
Fix functional tests
Zacqary May 17, 2022
22e839e
Fix functional tests
Zacqary May 18, 2022
25f8f7d
Clarify isRuleSnoozed
Zacqary May 18, 2022
3edaa0c
Merge remote-tracking branch 'upstream/main' into 130724-snooze-sched…
Zacqary May 18, 2022
02baeea
Use rrule to parse byweekday
Zacqary May 18, 2022
07bb7e9
[CI] Auto-commit changed files from 'node scripts/precommit_hook.js -…
kibanamachine May 18, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions x-pack/plugins/alerting/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ export * from './disabled_action_groups';
export * from './rule_notify_when_type';
export * from './parse_duration';
export * from './execution_log_types';
export * from './rule_snooze_type';
export * from './is_rule_snoozed';

export interface AlertingFrameworkHealth {
isSufficientlySecure: boolean;
Expand Down
188 changes: 188 additions & 0 deletions x-pack/plugins/alerting/common/is_rule_snoozed.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
/*
* 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 moment from 'moment';
import sinon from 'sinon';
import { isRuleSnoozed } from './is_rule_snoozed';

const LOCAL_OFFSET = moment('2020-01-01T00:00:00.000').format('Z');
Zacqary marked this conversation as resolved.
Show resolved Hide resolved
const DATE_9999 = '9999-12-31T12:34:56.789' + LOCAL_OFFSET;
const DATE_1970 = '1970-01-01T00:00:00.000' + LOCAL_OFFSET;
const DATE_1970_PLUS_6_HOURS = '1970-01-01T06:00:00.000' + LOCAL_OFFSET;
const DATE_2020 = '2020-01-01T00:00:00.000' + LOCAL_OFFSET;
const DATE_2020_MINUS_1_HOUR = '2019-12-31T23:00:00.000' + LOCAL_OFFSET;
const DATE_2020_MINUS_1_MONTH = '2019-12-01T00:00:00.000' + LOCAL_OFFSET;

const NOW = DATE_2020;

let fakeTimer: sinon.SinonFakeTimers;

describe('isRuleSnoozed', () => {
beforeAll(() => {
fakeTimer = sinon.useFakeTimers(new Date(NOW));
});

afterAll(() => fakeTimer.restore());

test('returns false when snooze has not yet started', () => {
const snoozeSchedule = [
{
startTime: DATE_9999,
duration: 100000000,
},
];
expect(isRuleSnoozed({ snoozeSchedule })).toBe(false);
});

test('returns true when snooze has started', () => {
const snoozeSchedule = [
{
startTime: NOW,
duration: 100000000,
},
];
expect(isRuleSnoozed({ snoozeSchedule })).toBe(true);
});

test('returns false when snooze has ended', () => {
const snoozeSchedule = [
{
startTime: DATE_1970,
duration: 100000000,
},
];
expect(isRuleSnoozed({ snoozeSchedule })).toBe(false);
});

test('returns true when snooze is indefinite', () => {
const snoozeSchedule = [
{
startTime: DATE_9999,
duration: 100000000,
},
];
expect(isRuleSnoozed({ snoozeSchedule, snoozeIndefinitely: true })).toBe(true);
});

test('returns as expected for an indefinitely recurring snooze', () => {
const snoozeScheduleA = [
{
startTime: DATE_1970,
duration: 60 * 1000,
repeatInterval: '1d',
},
];
expect(isRuleSnoozed({ snoozeSchedule: snoozeScheduleA })).toBe(true);
const snoozeScheduleB = [
{
startTime: DATE_1970_PLUS_6_HOURS,
duration: 60 * 1000,
repeatInterval: '1d',
},
];
expect(isRuleSnoozed({ snoozeSchedule: snoozeScheduleB })).toBe(false);
const snoozeScheduleC = [
{
startTime: DATE_2020_MINUS_1_HOUR,
duration: 60 * 1000,
repeatInterval: '1h',
},
];
expect(isRuleSnoozed({ snoozeSchedule: snoozeScheduleC })).toBe(true);
});

test('returns as expected for a recurring snooze with limited occurrences', () => {
const snoozeScheduleA = [
{
startTime: DATE_1970,
duration: 60 * 1000,
repeatInterval: '1h',
occurrences: 600000,
},
];
expect(isRuleSnoozed({ snoozeSchedule: snoozeScheduleA })).toBe(true);
const snoozeScheduleB = [
{
startTime: DATE_1970,
duration: 60 * 1000,
repeatInterval: '1h',
occurrences: 25,
},
];
expect(isRuleSnoozed({ snoozeSchedule: snoozeScheduleB })).toBe(false);

// FIXME: THIS FAILS due to not compensating for leap years. Also 1M intervals exhibit confusing behavior
// Either we should add something to compensate for this, or disable the use of M and y, and only allow for explicit day lengths
// const snoozeScheduleC = [
// {
// startTime: DATE_1970,
// duration: 60 * 1000,
// repeatInterval: '1y',
// occurrences: 60,
// },
// ];
// expect(isRuleSnoozed({ snoozeSchedule: snoozeScheduleC })).toBe(true);
});

test('returns as expected for a recurring snooze with an end date', () => {
const snoozeScheduleA = [
{
startTime: DATE_1970,
duration: 60 * 1000,
repeatInterval: '1h',
repeatEndTime: DATE_9999,
},
];
expect(isRuleSnoozed({ snoozeSchedule: snoozeScheduleA })).toBe(true);
const snoozeScheduleB = [
{
startTime: DATE_1970,
duration: 60 * 1000,
repeatInterval: '1h',
repeatEndTime: DATE_2020_MINUS_1_HOUR,
},
];
expect(isRuleSnoozed({ snoozeSchedule: snoozeScheduleB })).toBe(false);
});

test('returns as expected for a recurring snooze on a day of the week', () => {
const snoozeScheduleA = [
{
startTime: DATE_1970,
duration: 60 * 1000,
repeatInterval: 'DOW:135', // Monday Wednesday Friday; Jan 1 2020 was a Wednesday
},
];
expect(isRuleSnoozed({ snoozeSchedule: snoozeScheduleA })).toBe(true);
const snoozeScheduleB = [
{
startTime: DATE_1970,
duration: 60 * 1000,
repeatInterval: 'DOW:2467', // Tue, Thu, Sat, Sun
},
];
expect(isRuleSnoozed({ snoozeSchedule: snoozeScheduleB })).toBe(false);
const snoozeScheduleC = [
{
startTime: DATE_2020_MINUS_1_MONTH,
duration: 60 * 1000,
repeatInterval: 'DOW:135',
occurrences: 12,
},
];
expect(isRuleSnoozed({ snoozeSchedule: snoozeScheduleC })).toBe(false);
const snoozeScheduleD = [
{
startTime: DATE_2020_MINUS_1_MONTH,
duration: 60 * 1000,
repeatInterval: 'DOW:135',
occurrences: 15,
},
];
expect(isRuleSnoozed({ snoozeSchedule: snoozeScheduleD })).toBe(true);
});
});
81 changes: 81 additions & 0 deletions x-pack/plugins/alerting/common/is_rule_snoozed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* 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 moment from 'moment';
import { parseInterval } from '@kbn/data-plugin/common';
import { SanitizedRule, RuleTypeParams } from './rule';

type RuleSnoozeProps = Pick<SanitizedRule<RuleTypeParams>, 'snoozeIndefinitely' | 'snoozeSchedule'>;

export function getRuleSnoozeEndTime(rule: RuleSnoozeProps): Date | null {
if (rule.snoozeSchedule == null) {
return null;
}

const now = Date.now();
for (const snooze of rule.snoozeSchedule) {
const { startTime, duration, repeatInterval, occurrences, repeatEndTime } = snooze;
const startTimeMS = Date.parse(startTime);
const initialEndTime = startTimeMS + duration;
// If now is during the first occurrence of the snooze

if (now >= startTimeMS && now < initialEndTime) return new Date(initialEndTime);

// Check to see if now is during a recurrence of the snooze
if (repeatInterval) {
let occurrence;
let occurrenceStartTime;
if (repeatEndTime) {
const repeatEndTimeMS = Date.parse(repeatEndTime);
if (now >= repeatEndTimeMS) continue;
}
const timeFromInitialStart = now - startTimeMS;

// Handle day-of-week recurrences
if (repeatInterval.startsWith('DOW:')) {
const [, daysOfWeekString] = repeatInterval.split(':');
const repeatDays = daysOfWeekString
.split('')
.map((d) => Number(d))
.sort();
const today = moment(now).isoWeekday();

if (!repeatDays.includes(today)) continue;

const weeksFromInitialStart = moment(now).diff(moment(startTime), 'weeks');
const occurrencesPerWeek = repeatDays.length;
occurrence = weeksFromInitialStart * occurrencesPerWeek + repeatDays.indexOf(today);
const nowMoment = moment(now);
occurrenceStartTime = moment(startTime)
.year(nowMoment.year())
.dayOfYear(nowMoment.dayOfYear())
.valueOf();
} else {
const interval = parseInterval(repeatInterval)?.asMilliseconds();
if (!interval) continue;

occurrence = Math.floor(timeFromInitialStart / interval);
occurrenceStartTime = interval * occurrence + startTimeMS;
}

if (occurrences && occurrence > occurrences) continue;

const occurrenceEndTime = occurrenceStartTime + duration;

if (now >= occurrenceStartTime && now < occurrenceEndTime) return new Date(occurrenceEndTime);
}
}

return null;
}

export function isRuleSnoozed(rule: RuleSnoozeProps) {
if (rule.snoozeIndefinitely) {
return true;
}
return Boolean(getRuleSnoozeEndTime(rule));
}
5 changes: 3 additions & 2 deletions x-pack/plugins/alerting/common/rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
} from '@kbn/core/server';
import { RuleNotifyWhenType } from './rule_notify_when_type';
import { RuleSnooze } from './rule_snooze_type';

export type RuleTypeState = Record<string, unknown>;
export type RuleTypeParams = Record<string, unknown>;
Expand Down Expand Up @@ -104,11 +105,11 @@ export interface Rule<Params extends RuleTypeParams = never> {
apiKeyOwner: string | null;
throttle: string | null;
notifyWhen: RuleNotifyWhenType | null;
muteAll: boolean;
mutedInstanceIds: string[];
executionStatus: RuleExecutionStatus;
monitoring?: RuleMonitoring;
snoozeEndTime?: Date | null; // Remove ? when this parameter is made available in the public API
snoozeIndefinitely?: boolean;
snoozeSchedule?: RuleSnooze; // Remove ? when this parameter is made available in the public API
}

export type SanitizedRule<Params extends RuleTypeParams = never> = Omit<Rule<Params>, 'apiKey'>;
Expand Down
15 changes: 15 additions & 0 deletions x-pack/plugins/alerting/common/rule_snooze_type.ts
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.
*/

export type RuleSnooze = Array<{
pmuellr marked this conversation as resolved.
Show resolved Hide resolved
startTime: string;
duration: number;
id?: string;
repeatInterval?: string;
occurrences?: number;
repeatEndTime?: string;
}>;
10 changes: 5 additions & 5 deletions x-pack/plugins/alerting/server/routes/find_rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,12 @@ const rewriteBodyRes: RewriteResponseCase<FindResult<RuleTypeParams>> = ({
updatedAt,
apiKeyOwner,
notifyWhen,
muteAll,
mutedInstanceIds,
executionStatus,
actions,
scheduledTaskId,
snoozeEndTime,
snoozeIndefinitely,
snoozeSchedule,
...rest
}) => ({
...rest,
Expand All @@ -95,11 +95,11 @@ const rewriteBodyRes: RewriteResponseCase<FindResult<RuleTypeParams>> = ({
updated_at: updatedAt,
api_key_owner: apiKeyOwner,
notify_when: notifyWhen,
mute_all: muteAll,
muted_alert_ids: mutedInstanceIds,
scheduled_task_id: scheduledTaskId,
// Remove this object spread boolean check after snoozeEndTime is added to the public API
...(snoozeEndTime !== undefined ? { snooze_end_time: snoozeEndTime } : {}),
// Remove these object spread boolean check after snooze props is added to the public API
...(snoozeIndefinitely !== undefined ? { snooze_indefinitely: snoozeIndefinitely } : {}),
...(snoozeSchedule !== undefined ? { snooze_schedule: snoozeSchedule } : {}),
execution_status: executionStatus && {
...omit(executionStatus, 'lastExecutionDate', 'lastDuration'),
last_execution_date: executionStatus.lastExecutionDate,
Expand Down
10 changes: 5 additions & 5 deletions x-pack/plugins/alerting/server/routes/get_rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ const rewriteBodyRes: RewriteResponseCase<SanitizedRule<RuleTypeParams>> = ({
updatedAt,
apiKeyOwner,
notifyWhen,
muteAll,
mutedInstanceIds,
executionStatus,
actions,
scheduledTaskId,
snoozeEndTime,
snoozeIndefinitely,
snoozeSchedule,
...rest
}) => ({
...rest,
Expand All @@ -46,10 +46,10 @@ const rewriteBodyRes: RewriteResponseCase<SanitizedRule<RuleTypeParams>> = ({
updated_at: updatedAt,
api_key_owner: apiKeyOwner,
notify_when: notifyWhen,
mute_all: muteAll,
muted_alert_ids: mutedInstanceIds,
// Remove this object spread boolean check after snoozeEndTime is added to the public API
...(snoozeEndTime !== undefined ? { snooze_end_time: snoozeEndTime } : {}),
// Remove these object spread boolean check after snooze props is added to the public API
...(snoozeIndefinitely !== undefined ? { snooze_indefinitely: snoozeIndefinitely } : {}),
...(snoozeSchedule !== undefined ? { snooze_schedule: snoozeSchedule } : {}),
scheduled_task_id: scheduledTaskId,
execution_status: executionStatus && {
...omit(executionStatus, 'lastExecutionDate', 'lastDuration'),
Expand Down
Loading