-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
create_rule.ts
147 lines (141 loc) · 4.06 KB
/
create_rule.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
* 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 { schema } from '@kbn/config-schema';
import { validateDurationSchema, RuleTypeDisabledError } from '../lib';
import { CreateOptions } from '../rules_client';
import {
RewriteRequestCase,
RewriteResponseCase,
handleDisabledApiKeysError,
verifyAccessAndContext,
countUsageOfPredefinedIds,
} from './lib';
import {
SanitizedRule,
validateNotifyWhenType,
RuleTypeParams,
BASE_ALERTING_API_PATH,
RuleNotifyWhenType,
} from '../types';
import { RouteOptions } from '.';
export const bodySchema = schema.object({
name: schema.string(),
rule_type_id: schema.string(),
enabled: schema.boolean({ defaultValue: true }),
consumer: schema.string(),
tags: schema.arrayOf(schema.string(), { defaultValue: [] }),
throttle: schema.nullable(schema.string({ validate: validateDurationSchema })),
params: schema.recordOf(schema.string(), schema.any(), { defaultValue: {} }),
schedule: schema.object({
interval: schema.string({ validate: validateDurationSchema }),
}),
actions: schema.arrayOf(
schema.object({
group: schema.string(),
id: schema.string(),
params: schema.recordOf(schema.string(), schema.any(), { defaultValue: {} }),
}),
{ defaultValue: [] }
),
notify_when: schema.string({ validate: validateNotifyWhenType }),
});
const rewriteBodyReq: RewriteRequestCase<CreateOptions<RuleTypeParams>['data']> = ({
rule_type_id: alertTypeId,
notify_when: notifyWhen,
...rest
}) => ({
...rest,
alertTypeId,
notifyWhen,
});
const rewriteBodyRes: RewriteResponseCase<SanitizedRule<RuleTypeParams>> = ({
actions,
alertTypeId,
scheduledTaskId,
createdBy,
updatedBy,
createdAt,
updatedAt,
apiKeyOwner,
notifyWhen,
muteAll,
mutedInstanceIds,
snoozeSchedule,
executionStatus: { lastExecutionDate, lastDuration, ...executionStatus },
...rest
}) => ({
...rest,
rule_type_id: alertTypeId,
scheduled_task_id: scheduledTaskId,
snooze_schedule: snoozeSchedule,
created_by: createdBy,
updated_by: updatedBy,
created_at: createdAt,
updated_at: updatedAt,
api_key_owner: apiKeyOwner,
notify_when: notifyWhen,
mute_all: muteAll,
muted_alert_ids: mutedInstanceIds,
execution_status: {
...executionStatus,
last_execution_date: lastExecutionDate,
last_duration: lastDuration,
},
actions: actions.map(({ group, id, actionTypeId, params }) => ({
group,
id,
params,
connector_type_id: actionTypeId,
})),
});
export const createRuleRoute = ({ router, licenseState, usageCounter }: RouteOptions) => {
router.post(
{
path: `${BASE_ALERTING_API_PATH}/rule/{id?}`,
validate: {
params: schema.maybe(
schema.object({
id: schema.maybe(schema.string()),
})
),
body: bodySchema,
},
},
handleDisabledApiKeysError(
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
const rulesClient = (await context.alerting).getRulesClient();
const rule = req.body;
const params = req.params;
countUsageOfPredefinedIds({
predefinedId: params?.id,
spaceId: rulesClient.getSpaceId(),
usageCounter,
});
try {
const createdRule: SanitizedRule<RuleTypeParams> =
await rulesClient.create<RuleTypeParams>({
data: rewriteBodyReq({
...rule,
notify_when: rule.notify_when as RuleNotifyWhenType,
}),
options: { id: params?.id },
});
return res.ok({
body: rewriteBodyRes(createdRule),
});
} catch (e) {
if (e instanceof RuleTypeDisabledError) {
return e.sendResponse(res);
}
throw e;
}
})
)
)
);
};