generated from adobe/franklin-library
-
Notifications
You must be signed in to change notification settings - Fork 14
/
alerts.js
349 lines (326 loc) · 10.2 KB
/
alerts.js
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/*
* Copyright 2019 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
const fetchAPI = require('@adobe/helix-fetch');
const { getIncubatorName } = require('../utils');
const { fetch } = process.env.HELIX_FETCH_FORCE_HTTP1
? fetchAPI.context({ httpsProtocols: ['http1'] })
: fetchAPI;
const CHANNEL_TYPE = 'email';
const INCIDENT_PREFERENCE = 'PER_POLICY';
const CONDITION_NAME = 'Location Failure';
const CONDITION_PRIORITY = 'critical';
const CONDITION_THRESHOLD = 2;
/* eslint-disable no-console */
async function getChannelInfo(auth, channelName, email) {
try {
const resp = await fetch('https://api.newrelic.com/v2/alerts_channels.json', {
headers: {
'X-Api-Key': auth,
},
});
if (!resp.ok) {
throw new Error(await resp.text());
}
const body = await resp.json();
const allChannels = body.channels || [];
const channel = allChannels.find((c) => c.type === CHANNEL_TYPE
&& c.name === channelName && c.configuration.recipients === email);
return {
channel,
allChannels,
};
} catch (e) {
console.error('Unable to retrieve channels:', e.message);
return {};
}
}
async function purgeIncubatorChannel(auth, name, allPolicies) {
const incubatorPolicy = allPolicies ? allPolicies.find((policy) => policy.name === name) : null;
if (incubatorPolicy) {
console.log('Removing incubator notification channel', incubatorPolicy.name);
try {
const resp = await fetch(`https://api.newrelic.com/v2/alerts_channels/${incubatorPolicy.id}.json`, {
method: 'DELETE',
headers: {
'X-Api-Key': auth,
},
});
const body = await resp.text();
if (!resp.ok) {
throw new Error(body);
}
} catch (e) {
console.error('Unable to remove incubator notification channel', e.message);
}
}
}
async function reuseOrCreateChannel(auth, name, email, incubator) {
const channelName = incubator ? getIncubatorName(name) : name;
const info = await getChannelInfo(auth, channelName, email);
const { allChannels } = info;
let { channel } = info;
if (channel) {
console.log(`Reusing notification channel ${channel.name}`);
} else {
console.log('Creating notification channel', channelName);
try {
const resp = await fetch('https://api.newrelic.com/v2/alerts_channels.json', {
method: 'POST',
headers: {
'X-Api-Key': auth,
},
json: {
channel: {
name: channelName,
type: CHANNEL_TYPE,
configuration: {
recipients: email,
include_json_attachment: false,
},
},
},
});
if (!resp.ok) {
throw new Error(await resp.text());
}
const body = await resp.json();
[channel] = body.channels || [];
if (!incubator) {
// delete same name incubator channel
purgeIncubatorChannel(auth, getIncubatorName(name), allChannels);
}
} catch (e) {
console.error('Notification channel creation failed:', e.message);
process.exit(1);
}
}
return channel ? channel.id : null;
}
async function getConditions(auth, policy) {
if (!policy || !policy.id) return [];
try {
const resp = await fetch(`https://api.newrelic.com/v2/alerts_location_failure_conditions/policies/${policy.id}.json`, {
headers: {
'X-Api-Key': auth,
},
});
if (!resp.ok) {
throw new Error(await resp.text());
}
const body = await resp.json();
const conds = body.location_failure_conditions || [];
return conds.filter((condition) => condition.name === CONDITION_NAME);
} catch (e) {
console.error('Unable to retrieve conditions:', e.message);
return [];
}
}
async function createCondition(auth, policy, monitorId) {
if (!policy || !policy.id) return;
console.log('Creating condition in alert policy');
try {
const resp = await fetch(`https://api.newrelic.com/v2/alerts_location_failure_conditions/policies/${policy.id}.json`, {
method: 'POST',
headers: {
'X-Api-Key': auth,
},
json: {
location_failure_condition: {
name: CONDITION_NAME,
enabled: true,
entities: [
monitorId,
],
terms: [{
threshold: CONDITION_THRESHOLD,
priority: CONDITION_PRIORITY,
}],
},
},
});
const body = await resp.text();
if (!resp.ok) {
throw new Error(body);
}
} catch (e) {
console.error('Unable to add alert policy condition:', e.message);
}
}
async function updateCondition(auth, condition, monitorId) {
try {
if (condition.entities && condition.entities.includes(monitorId)) {
console.log('Alert policy condition is up to date');
} else {
console.log('Updating alert policy condition');
condition.entities.push(monitorId);
const resp = await fetch(`https://api.newrelic.com/v2/alerts_location_failure_conditions/${condition.id}.json`, {
method: 'PUT',
headers: {
'X-Api-Key': auth,
},
json: {
location_failure_condition: condition,
},
});
const body = await resp.text();
if (!resp.ok) {
throw new Error(body);
}
}
} catch (e) {
console.error('Unable to update alert policy condition', e.message);
}
}
async function getPolicyInfo(auth, policyName) {
try {
const resp = await fetch('https://api.newrelic.com/v2/alerts_policies.json', {
headers: {
'X-Api-Key': auth,
},
});
if (!resp.ok) {
throw new Error(await resp.text());
}
const body = await resp.json();
const allPolicies = body.policies
? body.policies.map(({ id, name }) => ({ id, name }))
: [];
return {
policy: policyName ? allPolicies.find((pol) => pol.name === policyName) : null,
allPolicies,
};
} catch (e) {
console.error('Unable to retrieve alert policies:', e.message);
return {};
}
}
async function createPolicy(auth, name) {
console.log('Creating alert policy', name);
try {
const resp = await fetch('https://api.newrelic.com/v2/alerts_policies.json', {
method: 'POST',
headers: {
'X-Api-Key': auth,
},
json: {
policy: {
name,
incident_preference: INCIDENT_PREFERENCE,
},
},
});
if (!resp.ok) {
throw new Error(await resp.text());
}
const body = await resp.json();
return body.policy;
} catch (e) {
console.error('Alert policy creation failed:', e.message);
process.exit(1);
}
return null;
}
async function updatePolicy(auth, policy, groupPolicy, monitorId, channelId, policies, incubator) {
if (channelId && policy) {
// add notification channel
console.log('Linking notification channel to alert policy', policy.name);
try {
const resp = await fetch('https://api.newrelic.com/v2/alerts_policy_channels.json', {
method: 'PUT',
headers: {
'X-Api-Key': auth,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
channel_ids: channelId,
policy_id: policy.id,
}).toString(),
});
const body = await resp.text();
if (!resp.ok) {
throw new Error(body);
}
} catch (e) {
console.error('Unable to add notification channel to alert policy', e.message);
}
}
const [condition] = await getConditions(auth, policy);
if (!condition) {
// add condition
await createCondition(auth, policy, monitorId);
} else {
// update condition
await updateCondition(auth, condition, monitorId);
}
if (!incubator && groupPolicy) {
const group = policies ? policies.find((pol) => pol.name === groupPolicy) : null;
if (group) {
// make sure policy and group policy are not the same
if (policy && policy.id && policy.id === group.id) {
console.error('Group alert policy and alert policy must differ');
return;
}
console.log('Verifying group alert policy', group.name);
await updatePolicy(auth, group, null, monitorId);
} else {
console.error(`Group alert policy ${groupPolicy} not found`);
}
}
}
async function purgeIncubatorPolicy(auth, name, allPolicies) {
const incubatorPolicyName = getIncubatorName(name);
const incubatorPolicy = allPolicies
? allPolicies.find((policy) => policy.name === incubatorPolicyName)
: null;
if (incubatorPolicy) {
console.log('Removing incubator alert policy', incubatorPolicy.name);
try {
const resp = await fetch(`https://api.newrelic.com/v2/alerts_policies/${incubatorPolicy.id}.json`, {
method: 'DELETE',
headers: {
'X-Api-Key': auth,
},
});
const body = await resp.text();
if (!resp.ok) {
throw new Error(body);
}
} catch (e) {
console.error('Unable to remove incubator alert policy', e.message);
}
}
}
async function updateOrCreatePolicies(auth, name, groupPolicy, monitorId, channelId, incubator) {
const policyName = incubator ? getIncubatorName(name) : name;
const info = await getPolicyInfo(auth, policyName);
const { allPolicies } = info;
let { policy } = info;
if (channelId && !policy) {
// create policy
policy = await createPolicy(auth, policyName);
}
// update policy
await updatePolicy(auth, policy, groupPolicy, monitorId, channelId, allPolicies, incubator);
if (!incubator) {
// TODO: delete same name incubator policy
await purgeIncubatorPolicy(auth, name, allPolicies);
}
}
module.exports = {
updateOrCreatePolicies,
reuseOrCreateChannel,
CHANNEL_TYPE,
INCIDENT_PREFERENCE,
CONDITION_NAME,
CONDITION_PRIORITY,
CONDITION_THRESHOLD,
};