-
Notifications
You must be signed in to change notification settings - Fork 18
/
metrics.ts
74 lines (65 loc) · 1.91 KB
/
metrics.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
import AWS = require('aws-sdk')
import { MetricData, MetricDatum } from 'aws-sdk/clients/cloudwatch'
AWS.config.update({ region: process.env.VSH_IOT_REGION })
const iot = new AWS.Iot()
const cw = new AWS.CloudWatch()
const staleThingsCountQuery = () => {
const timestampInPast =
Math.floor(new Date().getTime() / 1000) - 60 * 60 * 24 * 30 //30 days ago
return `thingName:vsht* AND connectivity.connected:false AND ((NOT shadow.reported.connected:*) OR shadow.metadata.reported.connected.timestamp < ${timestampInPast})`
}
const OnlineThingsCountQuery = () =>
'thingName:vsht* AND connectivity.connected:true'
const OfflineThingsCountQuery = () =>
'thingName:vsht* AND connectivity.connected:false'
async function getStats(
query: string,
metricName: string
): Promise<MetricDatum> {
const params = {
queryString: query,
}
return new Promise((resolve, reject) => {
iot.getStatistics(params, function (err, data) {
if (err) {
reject(err)
} else {
resolve({
MetricName: metricName,
Dimensions: [],
Unit: 'None',
Value: data.statistics.count,
})
}
})
})
}
async function publishMetricData(data: MetricData): Promise<boolean> {
var params = {
MetricData: data,
Namespace: 'VSH/FleetManagement',
}
return new Promise((resolve, reject) => {
cw.putMetricData(params, function (err, data) {
if (err) {
reject(err)
} else {
resolve(true)
}
})
})
}
export const metrics = async function (event, context) {
const data = await Promise.all([
getStats(staleThingsCountQuery(), 'staleThings'),
getStats(OnlineThingsCountQuery(), 'onlineThings'),
getStats(OfflineThingsCountQuery(), 'offlineThings'),
])
try {
await publishMetricData(data)
console.log('published metric data::', data)
return data
} catch (e) {
console.log('EXCEPTION::', e.message)
}
}