-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
profiling.ts
77 lines (73 loc) · 2.94 KB
/
profiling.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
import PrometheusMetrics from './prometheus/metrics';
export default class Profiling {
readonly metrics: PrometheusMetrics;
constructor(metrics: PrometheusMetrics) {
this.metrics = metrics;
}
timeAsyncCode = async (func: () => void, action: string, labels: any | null = null) => {
const prevCpuTime = process.cpuUsage();
const prevRealTime = Date.now();
try {
return await func();
} finally {
const lbl = `_${action}`;
if (!labels) {
labels = {};
} else if (labels.device && !labels.zone) {
labels = this.metrics.deviceLabels[labels.device];
}
if (!labels.name) labels.name = lbl;
if (!labels.device) labels.device = lbl;
if (!labels.zone) labels.zone = lbl;
if (!labels.zones) labels.zones = lbl;
const deltaNow = Date.now() - prevRealTime;
const cpuUsage = process.cpuUsage(prevCpuTime);
if (deltaNow > 0) {
// Avoid violation of Prometheus API due to time warp
this.metrics.counter_self_timer
.labels('real', action, labels.device, labels.name, labels.zone, labels.zones)
.inc(deltaNow * 1e-3);
}
this.metrics.counter_self_timer
.labels('user', action, labels.device, labels.name, labels.zone, labels.zones)
.inc(cpuUsage.user * 1e-6);
this.metrics.counter_self_timer
.labels('system', action, labels.device, labels.name, labels.zone, labels.zones)
.inc(cpuUsage.system * 1e-6);
this.metrics.counter_self_counter.labels(action, labels.device, labels.name, labels.zone, labels.zones).inc();
}
};
timeCode = (func: () => void, action: string, labels: any | null = null) => {
const prevCpuTime = process.cpuUsage();
const prevRealTime = Date.now();
try {
return func();
} finally {
const lbl = `_${action}`;
if (!labels) {
labels = {};
} else if (labels.device && !labels.zone) {
labels = this.metrics.deviceLabels[labels.device];
}
if (!labels.name) labels.name = lbl;
if (!labels.device) labels.device = lbl;
if (!labels.zone) labels.zone = lbl;
if (!labels.zones) labels.zones = lbl;
const deltaNow = Date.now() - prevRealTime;
const cpuUsage = process.cpuUsage(prevCpuTime);
if (deltaNow > 0) {
// Avoid violation of Prometheus API due to time warp
this.metrics.counter_self_timer
.labels('real', action, labels.device, labels.name, labels.zone, labels.zones)
.inc(deltaNow * 1e-3);
}
this.metrics.counter_self_timer
.labels('user', action, labels.device, labels.name, labels.zone, labels.zones)
.inc(cpuUsage.user * 1e-6);
this.metrics.counter_self_timer
.labels('system', action, labels.device, labels.name, labels.zone, labels.zones)
.inc(cpuUsage.system * 1e-6);
this.metrics.counter_self_counter.labels(action, labels.device, labels.name, labels.zone, labels.zones).inc();
}
};
}