/
index.js
110 lines (83 loc) · 2.02 KB
/
index.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
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
109
110
'use strict';
/*jshint node:true, esnext:true */
let fs = require('fs');
let ls = require('line-stream');
let units = {
B : 1,
kB : 1000
};
let startsWithVmSizeRgx = /^VmSize:/;
let startsWithVmDataRgx = /^VmData:/;
let startsWithSERRgx = /^se\.sum_exec_runtime/;
let endsWithIntAndUnitRgx = /([0-9]+) ([A-Za-z]+)$/;
let endsWithFloatRgx = /([0-9]+\.?[0-9]*)$/;
let parseEndsWithIntAndUnit = function(line) {
let parts = line.split(' ');
let unit = parts.pop();
let num = parts.pop();
return parseInt(num, 10) * units[unit];
};
let parseEndsWithFloat = function(line) {
let parts = line.split(' ');
return parseFloat( parts.pop() );
};
let parseProcPidFileLines = function(pid, fileName, onLine, onDone) {
let fn = ['/proc', pid, fileName].join('/');
let l = ls();
let out = {};
let died = false;
l.on('data', function(line) {
if (died) { return; }
try {
onLine(line, out);
} catch (ex) {
died = true;
onDone(ex);
}
});
l.on('error', function(err) {
died = true;
onDone(err);
});
l.on('close', function() {
if (died) { return; }
onDone(null, out);
});
fs.createReadStream(fn)
.on('error', function(err) {
died = true;
onDone(err);
})
.pipe(l);
};
let getMemory = function(pid, cb) {
parseProcPidFileLines(
pid,
'status',
function(line, out) {
if (startsWithVmSizeRgx.test(line)) {
out.vmSize = parseEndsWithIntAndUnit(line);
}
else if (startsWithVmDataRgx.test(line)) {
out.vmData = parseEndsWithIntAndUnit(line);
}
},
cb
);
};
let getCPU = function(pid, cb) {
parseProcPidFileLines(
pid,
'sched',
function(line, out) {
if (startsWithSERRgx.test(line)) {
out.sumExecRuntime = parseEndsWithFloat(line);
}
},
cb
);
};
module.exports = {
getMemory : getMemory,
getCPU : getCPU
};