-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.ts
85 lines (77 loc) · 2.07 KB
/
handler.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
import { Context, ScheduledEvent, ScheduledHandler } from 'aws-lambda';
import axios, { AxiosRequestConfig } from 'axios';
import 'source-map-support/register';
import { getState, setState } from './dynamo';
const VERSION = process.env.VERSION;
const targetEndpoint = process.env.targetEndpoint;
const slackWebhookUrl = process.env.slackWebhookUrl;
let state: string;
let prevState: string;
const colors: { [key: string]: string } = {
error: 'warning',
healthy: 'good',
timeout: 'warning',
unhealthy: 'danger',
};
export const main: ScheduledHandler = async (
_event: ScheduledEvent,
_context: Context,
) => {
console.log(`uptime-monitoring v${VERSION}`);
await getState()
.then((value) => {
prevState = value;
})
.catch((err) => {
console.log(err);
prevState = 'unknown';
});
console.log(`prevState: ${prevState}`);
const targetConfig: AxiosRequestConfig = {
headers: { 'User-Agent': 'uptime-monitoring' },
timeout: 5000,
validateStatus: (_status) => {
return true;
},
};
await axios
.get(targetEndpoint, targetConfig)
.then((res) => {
if (res.status === 200) {
state = 'healthy';
} else {
state = 'unhealthy';
}
})
.catch((err) => {
console.log(err);
if (err.code === 'ECONNABORTED') {
state = 'timeout';
} else {
state = 'error';
}
});
await setState(state);
console.log(`state: ${state}`);
if (state !== prevState) {
console.log(`state changed: ${prevState} to ${state}`);
const message: string = JSON.stringify({
attachments: [
{
color: colors[state],
text: `<!here> health check state changed: ${prevState} to ${state}`,
title: 'uptime-monitoring',
},
],
});
const slackConfig: AxiosRequestConfig = {
headers: { 'Content-type': 'application/json' },
timeout: 2000,
};
await axios.post(slackWebhookUrl, message, slackConfig).catch((err) => {
console.log(err);
});
} else {
console.log(`state stayed ${state}`);
}
};