This repository has been archived by the owner on Mar 18, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
70 lines (64 loc) · 2.25 KB
/
utils.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
const monitoring = require('@google-cloud/monitoring')
const regression = require('regression')
function numDigitis (n) {
return n ? Math.floor(Math.log10(n)) + 1 : 1
}
function printValues (values) {
try {
const sortedByValue = values.concat().sort(({value: v1}, {value: v2}) => v1 - v2)
const smallestValue = sortedByValue[0].value
const largestValue = sortedByValue[sortedByValue.length - 1].value
const largestValueLength = numDigitis(largestValue)
const width = 20
for (const {value, time} of values) {
const percent = (value - smallestValue) / (largestValue - smallestValue)
const percentInt = Math.floor(percent * width)
const s = Array.from(new Array(percentInt)).reduce((acc) => acc + '#', '') + Array.from(new Array(width - percentInt)).reduce((acc) => acc + ' ', '')
const valueString = Array.from(new Array(largestValueLength - numDigitis(value))).reduce((acc) => acc + ' ', '') + value
process.stdout.write(`${time.toISOString()} ${valueString} ${s}\n`)
}
} catch (err) {
console.log('Failed to print values', err)
}
}
async function fetchValues (projectId, subscriptionId, metric, sampleMinutes = 60) {
const client = new monitoring.MetricServiceClient()
const filter = `metric.type = "${metric}" resource.labels.subscription_id = "${subscriptionId}"`
const request = {
name: client.projectPath(projectId),
filter: filter,
interval: {
startTime: {
seconds: Date.now() / 1000 - 60 * sampleMinutes
},
endTime: {
seconds: Date.now() / 1000
}
}
}
const res = await client
.listTimeSeries(request)
const {points} = res[0][0]
return points
.map(({interval: {startTime, endTime}, value: {int64Value}}) => ({
time: new Date(startTime.seconds * 1000),
value: parseInt(int64Value)
}))
}
function isLinRegHealthy (values, confidence) {
const data = values.map(({value}, i) => {
return [i, value]
})
const result = regression.linear(data)
return result.r2 > confidence ? result.equation[0] >= 0 : true
}
function isSumHealthy (values, condition) {
const sum = values.reduce((acc, {value}) => acc + value, 0)
return condition(sum)
}
module.exports = {
isLinRegHealthy,
isSumHealthy,
fetchValues,
printValues
}