-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetricsUpdate.js
More file actions
108 lines (98 loc) · 3.62 KB
/
metricsUpdate.js
File metadata and controls
108 lines (98 loc) · 3.62 KB
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
const os = require('os');
const fetch = require('node-fetch');
const CREATE_URL = 'http://localhost:4000/webhooks/metric/create';
const UPDATE_URL = 'http://localhost:4000/webhooks/metric/update';
const PUSH_INTERVAL = 60 * 1000;
// --- Helpers ---
function getCPUUsagePercent() {
return new Promise(resolve => {
const start = os.cpus();
setTimeout(() => {
const end = os.cpus();
let idleDiff = 0, totalDiff = 0;
for (let i = 0; i < start.length; i++) {
const s = start[i].times, e = end[i].times;
const idle = e.idle - s.idle;
const total = Object.keys(s).reduce((acc, t) => acc + (e[t] - s[t]), 0);
idleDiff += idle;
totalDiff += total;
}
const usage = 100 - (idleDiff / totalDiff) * 100;
resolve(Number(usage.toFixed(2)));
}, 100);
});
}
function getMemoryUsagePercent() {
const free = os.freemem();
const total = os.totalmem();
return Number((((total - free) / total) * 100).toFixed(2));
}
// Create metrics (first run, idempotent)
async function ensureMetricsExist(metricsArray) {
try {
const response = await fetch(CREATE_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ metrics: metricsArray }),
});
// Log result, but ignore errors about duplicates
const data = await response.json().catch(() => ({}));
if (!response.ok) {
console.warn('Metric creation API response:', data);
}
} catch (err) {
console.warn('Error during metric creation:', err.message);
}
}
// Update metrics (continuous)
async function updateMetrics(metricsArray) {
try {
const response = await fetch(UPDATE_URL, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(metricsArray), // array as root!
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
console.error('API Status:', response.status);
console.error('API Response:', data);
throw new Error(data.error || JSON.stringify(data) || 'Update failed');
}
if (data && data.results) {
data.results.forEach(r => {
if (r.success) {
console.log(`[${new Date().toISOString()}] Updated ${r.metric.metricName}: ${r.metric.value}`);
} else {
console.error(`Metric update failed for:`, r.input, 'Reason:', r.error);
}
});
} else {
metricsArray.forEach(({ name, value }) =>
console.log(`[${new Date().toISOString()}] Updated ${name}: ${value}`)
);
}
} catch (err) {
console.error(`Error updating metrics:`, err.message);
}
}
async function mainLoop() {
// First: Ensure metrics exist (ignore duplicate errors)
const metricsMeta = [
{ name: 'pc_cpu_usage_percent', value: 0 },
{ name: 'pc_mem_usage_percent', value: 0 }
];
await ensureMetricsExist(metricsMeta);
// Now: Loop for continuous updates
while (true) {
const cpu = await getCPUUsagePercent();
const mem = getMemoryUsagePercent();
// Update both by name
await updateMetrics([
{ name: 'pc_cpu_usage_percent', value: cpu },
{ name: 'pc_mem_usage_percent', value: mem }
]);
await new Promise(resolve => setTimeout(resolve, PUSH_INTERVAL));
}
}
// --- Start ---
mainLoop();