code-poltergeist-system-monitor 1.0.6

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of code-poltergeist-system-monitor might be problematic. Click here for more details.

Files changed (33) hide show
  1. package/index.js +74 -0
  2. package/package.json +21 -0
  3. package/te/node_modules/.package-lock.json +44 -0
  4. package/te/node_modules/code-poltergeist-system-monitor/index.js +74 -0
  5. package/te/node_modules/code-poltergeist-system-monitor/package.json +21 -0
  6. package/te/node_modules/systeminformation/LICENSE +20 -0
  7. package/te/node_modules/systeminformation/README.md +1116 -0
  8. package/te/node_modules/systeminformation/lib/audio.js +222 -0
  9. package/te/node_modules/systeminformation/lib/battery.js +311 -0
  10. package/te/node_modules/systeminformation/lib/bluetooth.js +231 -0
  11. package/te/node_modules/systeminformation/lib/cli.js +91 -0
  12. package/te/node_modules/systeminformation/lib/cpu.js +1834 -0
  13. package/te/node_modules/systeminformation/lib/docker.js +758 -0
  14. package/te/node_modules/systeminformation/lib/dockerSocket.js +327 -0
  15. package/te/node_modules/systeminformation/lib/filesystem.js +1510 -0
  16. package/te/node_modules/systeminformation/lib/graphics.js +1125 -0
  17. package/te/node_modules/systeminformation/lib/index.d.ts +1041 -0
  18. package/te/node_modules/systeminformation/lib/index.js +504 -0
  19. package/te/node_modules/systeminformation/lib/internet.js +237 -0
  20. package/te/node_modules/systeminformation/lib/memory.js +575 -0
  21. package/te/node_modules/systeminformation/lib/network.js +1783 -0
  22. package/te/node_modules/systeminformation/lib/osinfo.js +1179 -0
  23. package/te/node_modules/systeminformation/lib/printer.js +210 -0
  24. package/te/node_modules/systeminformation/lib/processes.js +1296 -0
  25. package/te/node_modules/systeminformation/lib/system.js +742 -0
  26. package/te/node_modules/systeminformation/lib/usb.js +279 -0
  27. package/te/node_modules/systeminformation/lib/users.js +363 -0
  28. package/te/node_modules/systeminformation/lib/util.js +1373 -0
  29. package/te/node_modules/systeminformation/lib/virtualbox.js +107 -0
  30. package/te/node_modules/systeminformation/lib/wifi.js +834 -0
  31. package/te/node_modules/systeminformation/package.json +99 -0
  32. package/te/package-lock.json +52 -0
  33. package/te/package.json +15 -0
@@ -0,0 +1,1296 @@
1
+ 'use strict';
2
+ // @ts-check
3
+ // ==================================================================================
4
+ // processes.js
5
+ // ----------------------------------------------------------------------------------
6
+ // Description: System Information - library
7
+ // for Node.js
8
+ // Copyright: (c) 2014 - 2024
9
+ // Author: Sebastian Hildebrandt
10
+ // ----------------------------------------------------------------------------------
11
+ // License: MIT
12
+ // ==================================================================================
13
+ // 10. Processes
14
+ // ----------------------------------------------------------------------------------
15
+
16
+ const os = require('os');
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+ const exec = require('child_process').exec;
20
+ const execSync = require('child_process').execSync;
21
+
22
+ const util = require('./util');
23
+
24
+ let _platform = process.platform;
25
+
26
+ const _linux = (_platform === 'linux' || _platform === 'android');
27
+ const _darwin = (_platform === 'darwin');
28
+ const _windows = (_platform === 'win32');
29
+ const _freebsd = (_platform === 'freebsd');
30
+ const _openbsd = (_platform === 'openbsd');
31
+ const _netbsd = (_platform === 'netbsd');
32
+ const _sunos = (_platform === 'sunos');
33
+
34
+ const _processes_cpu = {
35
+ all: 0,
36
+ all_utime: 0,
37
+ all_stime: 0,
38
+ list: {},
39
+ ms: 0,
40
+ result: {}
41
+ };
42
+ const _services_cpu = {
43
+ all: 0,
44
+ all_utime: 0,
45
+ all_stime: 0,
46
+ list: {},
47
+ ms: 0,
48
+ result: {}
49
+ };
50
+ const _process_cpu = {
51
+ all: 0,
52
+ all_utime: 0,
53
+ all_stime: 0,
54
+ list: {},
55
+ ms: 0,
56
+ result: {}
57
+ };
58
+
59
+ const _winStatusValues = {
60
+ '0': 'unknown',
61
+ '1': 'other',
62
+ '2': 'ready',
63
+ '3': 'running',
64
+ '4': 'blocked',
65
+ '5': 'suspended blocked',
66
+ '6': 'suspended ready',
67
+ '7': 'terminated',
68
+ '8': 'stopped',
69
+ '9': 'growing',
70
+ };
71
+
72
+ function parseTimeUnix(time) {
73
+ let result = time;
74
+ let parts = time.replace(/ +/g, ' ').split(' ');
75
+ if (parts.length === 5) {
76
+ result = parts[4] + '-' + ('0' + ('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.indexOf(parts[1].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ('0' + parts[2]).slice(-2) + ' ' + parts[3];
77
+ }
78
+ return result;
79
+ }
80
+
81
+ function parseElapsedTime(etime) {
82
+ let current = new Date();
83
+ current = new Date(current.getTime() - current.getTimezoneOffset() * 60000);
84
+
85
+ const elapsed = etime.split('-');
86
+
87
+ const timeIndex = elapsed.length - 1;
88
+ const days = timeIndex > 0 ? parseInt(elapsed[timeIndex - 1]) : 0;
89
+
90
+ const timeStr = elapsed[timeIndex].split(':');
91
+ const hours = timeStr.length === 3 ? parseInt(timeStr[0] || 0) : 0;
92
+ const mins = parseInt(timeStr[timeStr.length === 3 ? 1 : 0] || 0);
93
+ const secs = parseInt(timeStr[timeStr.length === 3 ? 2 : 1] || 0);
94
+ const ms = (((((days * 24 + hours) * 60) + mins) * 60 + secs) * 1000);
95
+
96
+ let res = new Date(current.getTime());
97
+ let result = res.toISOString().substring(0, 10) + ' ' + res.toISOString().substring(11, 19);
98
+ try {
99
+ res = new Date(current.getTime() - ms);
100
+ result = res.toISOString().substring(0, 10) + ' ' + res.toISOString().substring(11, 19);
101
+ } catch (e) {
102
+ util.noop();
103
+ }
104
+ return result;
105
+ }
106
+
107
+ // --------------------------
108
+ // PS - services
109
+ // pass a comma separated string with services to check (mysql, apache, postgresql, ...)
110
+ // this function gives an array back, if the services are running.
111
+
112
+ function services(srv, callback) {
113
+
114
+ // fallback - if only callback is given
115
+ if (util.isFunction(srv) && !callback) {
116
+ callback = srv;
117
+ srv = '';
118
+ }
119
+
120
+ return new Promise((resolve) => {
121
+ process.nextTick(() => {
122
+ if (typeof srv !== 'string') {
123
+ if (callback) { callback([]); }
124
+ return resolve([]);
125
+ }
126
+
127
+ if (srv) {
128
+ let srvString = '';
129
+ srvString.__proto__.toLowerCase = util.stringToLower;
130
+ srvString.__proto__.replace = util.stringReplace;
131
+ srvString.__proto__.trim = util.stringTrim;
132
+
133
+ const s = util.sanitizeShellString(srv);
134
+ const l = util.mathMin(s.length, 2000);
135
+ for (let i = 0; i <= l; i++) {
136
+ if (s[i] !== undefined) {
137
+ srvString = srvString + s[i];
138
+ }
139
+ }
140
+
141
+ srvString = srvString.trim().toLowerCase().replace(/, /g, '|').replace(/,+/g, '|');
142
+ if (srvString === '') {
143
+ srvString = '*';
144
+ }
145
+ if (util.isPrototypePolluted() && srvString !== '*') {
146
+ srvString = '------';
147
+ }
148
+ let srvs = srvString.split('|');
149
+ let result = [];
150
+ let dataSrv = [];
151
+
152
+ if (_linux || _freebsd || _openbsd || _netbsd || _darwin) {
153
+ if ((_linux || _freebsd || _openbsd || _netbsd) && srvString === '*') {
154
+ try {
155
+ const tmpsrv = execSync('systemctl --all --type=service --no-legend 2> /dev/null', util.execOptsLinux).toString().split('\n');
156
+ srvs = [];
157
+ for (const s of tmpsrv) {
158
+ const name = s.split('.service')[0];
159
+ if (name && s.indexOf(' not-found ') === -1) {
160
+ srvs.push(name.trim());
161
+ }
162
+ }
163
+ srvString = srvs.join('|');
164
+ } catch (d) {
165
+ try {
166
+ srvString = '';
167
+ const tmpsrv = execSync('service --status-all 2> /dev/null', util.execOptsLinux).toString().split('\n');
168
+ for (const s of tmpsrv) {
169
+ const parts = s.split(']');
170
+ if (parts.length === 2) {
171
+ srvString += (srvString !== '' ? '|' : '') + parts[1].trim();
172
+ }
173
+ }
174
+ srvs = srvString.split('|');
175
+ } catch (e) {
176
+ try {
177
+ const srvStr = execSync('ls /etc/init.d/ -m 2> /dev/null', util.execOptsLinux).toString().split('\n').join('');
178
+ srvString = '';
179
+ if (srvStr) {
180
+ const tmpsrv = srvStr.split(',');
181
+ for (const s of tmpsrv) {
182
+ const name = s.trim();
183
+ if (name) {
184
+ srvString += (srvString !== '' ? '|' : '') + name;
185
+ }
186
+ }
187
+ srvs = srvString.split('|');
188
+ }
189
+ } catch (f) {
190
+ srvString = '';
191
+ srvs = [];
192
+ }
193
+ }
194
+ }
195
+ }
196
+ if ((_darwin) && srvString === '*') { // service enumeration not yet suported on mac OS
197
+ if (callback) { callback(result); }
198
+ resolve(result);
199
+ }
200
+ let args = (_darwin) ? ['-caxo', 'pcpu,pmem,pid,command'] : ['-axo', 'pcpu,pmem,pid,command'];
201
+ if (srvString !== '' && srvs.length > 0) {
202
+ util.execSafe('ps', args).then((stdout) => {
203
+ if (stdout) {
204
+ let lines = stdout.replace(/ +/g, ' ').replace(/,+/g, '.').split('\n');
205
+ srvs.forEach(function (srv) {
206
+ let ps;
207
+ if (_darwin) {
208
+ ps = lines.filter(function (e) {
209
+ return (e.toLowerCase().indexOf(srv) !== -1);
210
+ });
211
+
212
+ } else {
213
+ ps = lines.filter(function (e) {
214
+ return (e.toLowerCase().indexOf(' ' + srv.toLowerCase() + ':') !== -1) || (e.toLowerCase().indexOf('/' + srv.toLowerCase()) !== -1);
215
+ });
216
+ }
217
+ const pids = [];
218
+ for (const p of ps) {
219
+ const pid = p.trim().split(' ')[2];
220
+ if (pid) {
221
+ pids.push(parseInt(pid, 10));
222
+ }
223
+ }
224
+ result.push({
225
+ name: srv,
226
+ running: ps.length > 0,
227
+ startmode: '',
228
+ pids: pids,
229
+ cpu: parseFloat((ps.reduce(function (pv, cv) {
230
+ return pv + parseFloat(cv.trim().split(' ')[0]);
231
+ }, 0)).toFixed(2)),
232
+ mem: parseFloat((ps.reduce(function (pv, cv) {
233
+ return pv + parseFloat(cv.trim().split(' ')[1]);
234
+ }, 0)).toFixed(2))
235
+ });
236
+ });
237
+ if (_linux) {
238
+ // calc process_cpu - ps is not accurate in linux!
239
+ let cmd = 'cat /proc/stat | grep "cpu "';
240
+ for (let i in result) {
241
+ for (let j in result[i].pids) {
242
+ cmd += (';cat /proc/' + result[i].pids[j] + '/stat');
243
+ }
244
+ }
245
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
246
+ let curr_processes = stdout.toString().split('\n');
247
+
248
+ // first line (all - /proc/stat)
249
+ let all = parseProcStat(curr_processes.shift());
250
+
251
+ // process
252
+ let list_new = {};
253
+ let resultProcess = {};
254
+ curr_processes.forEach((element) => {
255
+ resultProcess = calcProcStatLinux(element, all, _services_cpu);
256
+
257
+ if (resultProcess.pid) {
258
+ let listPos = -1;
259
+ for (let i in result) {
260
+ for (let j in result[i].pids) {
261
+ if (parseInt(result[i].pids[j]) === parseInt(resultProcess.pid)) {
262
+ listPos = i;
263
+ }
264
+ }
265
+ }
266
+ if (listPos >= 0) {
267
+ result[listPos].cpu += resultProcess.cpuu + resultProcess.cpus;
268
+ }
269
+
270
+ // save new values
271
+ list_new[resultProcess.pid] = {
272
+ cpuu: resultProcess.cpuu,
273
+ cpus: resultProcess.cpus,
274
+ utime: resultProcess.utime,
275
+ stime: resultProcess.stime,
276
+ cutime: resultProcess.cutime,
277
+ cstime: resultProcess.cstime
278
+ };
279
+ }
280
+ });
281
+
282
+ // store old values
283
+ _services_cpu.all = all;
284
+ _services_cpu.list = Object.assign({}, list_new);
285
+ _services_cpu.ms = Date.now() - _services_cpu.ms;
286
+ _services_cpu.result = Object.assign({}, result);
287
+ if (callback) { callback(result); }
288
+ resolve(result);
289
+ });
290
+ } else {
291
+ if (callback) { callback(result); }
292
+ resolve(result);
293
+ }
294
+ } else {
295
+ args = ['-o', 'comm'];
296
+ util.execSafe('ps', args).then((stdout) => {
297
+ if (stdout) {
298
+ let lines = stdout.replace(/ +/g, ' ').replace(/,+/g, '.').split('\n');
299
+ srvs.forEach(function (srv) {
300
+ let ps = lines.filter(function (e) {
301
+ return e.indexOf(srv) !== -1;
302
+ });
303
+ result.push({
304
+ name: srv,
305
+ running: ps.length > 0,
306
+ startmode: '',
307
+ cpu: 0,
308
+ mem: 0
309
+ });
310
+ });
311
+ if (callback) { callback(result); }
312
+ resolve(result);
313
+ } else {
314
+ srvs.forEach(function (srv) {
315
+ result.push({
316
+ name: srv,
317
+ running: false,
318
+ startmode: '',
319
+ cpu: 0,
320
+ mem: 0
321
+ });
322
+ });
323
+ if (callback) { callback(result); }
324
+ resolve(result);
325
+ }
326
+ });
327
+ }
328
+ });
329
+ } else {
330
+ if (callback) { callback(result); }
331
+ resolve(result);
332
+ }
333
+ }
334
+ if (_windows) {
335
+ try {
336
+ let wincommand = 'Get-CimInstance Win32_Service';
337
+ if (srvs[0] !== '*') {
338
+ wincommand += ' -Filter "';
339
+ srvs.forEach((srv) => {
340
+ wincommand += `Name='${srv}' or `;
341
+ });
342
+ wincommand = `${wincommand.slice(0, -4)}"`;
343
+ }
344
+ wincommand += ' | select Name,Caption,Started,StartMode,ProcessId | fl';
345
+ util.powerShell(wincommand).then((stdout, error) => {
346
+ if (!error) {
347
+ let serviceSections = stdout.split(/\n\s*\n/);
348
+ serviceSections.forEach((element) => {
349
+ if (element.trim() !== '') {
350
+ let lines = element.trim().split('\r\n');
351
+ let srvName = util.getValue(lines, 'Name', ':', true).toLowerCase();
352
+ let srvCaption = util.getValue(lines, 'Caption', ':', true).toLowerCase();
353
+ let started = util.getValue(lines, 'Started', ':', true);
354
+ let startMode = util.getValue(lines, 'StartMode', ':', true);
355
+ let pid = util.getValue(lines, 'ProcessId', ':', true);
356
+ if (srvString === '*' || srvs.indexOf(srvName) >= 0 || srvs.indexOf(srvCaption) >= 0) {
357
+ result.push({
358
+ name: srvName,
359
+ running: (started.toLowerCase() === 'true'),
360
+ startmode: startMode,
361
+ pids: [pid],
362
+ cpu: 0,
363
+ mem: 0
364
+ });
365
+ dataSrv.push(srvName);
366
+ dataSrv.push(srvCaption);
367
+ }
368
+ }
369
+
370
+ });
371
+
372
+ if (srvString !== '*') {
373
+ let srvsMissing = srvs.filter(function (e) {
374
+ return dataSrv.indexOf(e) === -1;
375
+ });
376
+ srvsMissing.forEach(function (srvName) {
377
+ result.push({
378
+ name: srvName,
379
+ running: false,
380
+ startmode: '',
381
+ pids: [],
382
+ cpu: 0,
383
+ mem: 0
384
+ });
385
+ });
386
+ }
387
+ if (callback) { callback(result); }
388
+ resolve(result);
389
+ } else {
390
+ srvs.forEach(function (srvName) {
391
+ result.push({
392
+ name: srvName,
393
+ running: false,
394
+ startmode: '',
395
+ cpu: 0,
396
+ mem: 0
397
+ });
398
+ });
399
+ if (callback) { callback(result); }
400
+ resolve(result);
401
+ }
402
+ });
403
+ } catch (e) {
404
+ if (callback) { callback(result); }
405
+ resolve(result);
406
+ }
407
+ }
408
+ } else {
409
+ if (callback) { callback([]); }
410
+ resolve([]);
411
+ }
412
+ });
413
+ });
414
+ }
415
+
416
+ exports.services = services;
417
+
418
+ function parseProcStat(line) {
419
+ let parts = line.replace(/ +/g, ' ').split(' ');
420
+ let user = (parts.length >= 2 ? parseInt(parts[1]) : 0);
421
+ let nice = (parts.length >= 3 ? parseInt(parts[2]) : 0);
422
+ let system = (parts.length >= 4 ? parseInt(parts[3]) : 0);
423
+ let idle = (parts.length >= 5 ? parseInt(parts[4]) : 0);
424
+ let iowait = (parts.length >= 6 ? parseInt(parts[5]) : 0);
425
+ let irq = (parts.length >= 7 ? parseInt(parts[6]) : 0);
426
+ let softirq = (parts.length >= 8 ? parseInt(parts[7]) : 0);
427
+ let steal = (parts.length >= 9 ? parseInt(parts[8]) : 0);
428
+ let guest = (parts.length >= 10 ? parseInt(parts[9]) : 0);
429
+ let guest_nice = (parts.length >= 11 ? parseInt(parts[10]) : 0);
430
+ return user + nice + system + idle + iowait + irq + softirq + steal + guest + guest_nice;
431
+ }
432
+
433
+ function calcProcStatLinux(line, all, _cpu_old) {
434
+ let statparts = line.replace(/ +/g, ' ').split(')');
435
+ if (statparts.length >= 2) {
436
+ let parts = statparts[1].split(' ');
437
+ if (parts.length >= 16) {
438
+ let pid = parseInt(statparts[0].split(' ')[0]);
439
+ let utime = parseInt(parts[12]);
440
+ let stime = parseInt(parts[13]);
441
+ let cutime = parseInt(parts[14]);
442
+ let cstime = parseInt(parts[15]);
443
+
444
+ // calc
445
+ let cpuu = 0;
446
+ let cpus = 0;
447
+ if (_cpu_old.all > 0 && _cpu_old.list[pid]) {
448
+ cpuu = (utime + cutime - _cpu_old.list[pid].utime - _cpu_old.list[pid].cutime) / (all - _cpu_old.all) * 100; // user
449
+ cpus = (stime + cstime - _cpu_old.list[pid].stime - _cpu_old.list[pid].cstime) / (all - _cpu_old.all) * 100; // system
450
+ } else {
451
+ cpuu = (utime + cutime) / (all) * 100; // user
452
+ cpus = (stime + cstime) / (all) * 100; // system
453
+ }
454
+ return {
455
+ pid: pid,
456
+ utime: utime,
457
+ stime: stime,
458
+ cutime: cutime,
459
+ cstime: cstime,
460
+ cpuu: cpuu,
461
+ cpus: cpus
462
+ };
463
+ } else {
464
+ return {
465
+ pid: 0,
466
+ utime: 0,
467
+ stime: 0,
468
+ cutime: 0,
469
+ cstime: 0,
470
+ cpuu: 0,
471
+ cpus: 0
472
+ };
473
+ }
474
+ } else {
475
+ return {
476
+ pid: 0,
477
+ utime: 0,
478
+ stime: 0,
479
+ cutime: 0,
480
+ cstime: 0,
481
+ cpuu: 0,
482
+ cpus: 0
483
+ };
484
+ }
485
+ }
486
+
487
+ function calcProcStatWin(procStat, all, _cpu_old) {
488
+ // calc
489
+ let cpuu = 0;
490
+ let cpus = 0;
491
+ if (_cpu_old.all > 0 && _cpu_old.list[procStat.pid]) {
492
+ cpuu = (procStat.utime - _cpu_old.list[procStat.pid].utime) / (all - _cpu_old.all) * 100; // user
493
+ cpus = (procStat.stime - _cpu_old.list[procStat.pid].stime) / (all - _cpu_old.all) * 100; // system
494
+ } else {
495
+ cpuu = (procStat.utime) / (all) * 100; // user
496
+ cpus = (procStat.stime) / (all) * 100; // system
497
+ }
498
+ return {
499
+ pid: procStat.pid,
500
+ utime: procStat.utime,
501
+ stime: procStat.stime,
502
+ cpuu: cpuu > 0 ? cpuu : 0,
503
+ cpus: cpus > 0 ? cpus : 0
504
+ };
505
+ }
506
+
507
+
508
+
509
+ // --------------------------
510
+ // running processes
511
+
512
+ function processes(callback) {
513
+
514
+ let parsedhead = [];
515
+
516
+ function getName(command) {
517
+ command = command || '';
518
+ let result = command.split(' ')[0];
519
+ if (result.substr(-1) === ':') {
520
+ result = result.substr(0, result.length - 1);
521
+ }
522
+ if (result.substr(0, 1) !== '[') {
523
+ let parts = result.split('/');
524
+ if (isNaN(parseInt(parts[parts.length - 1]))) {
525
+ result = parts[parts.length - 1];
526
+ } else {
527
+ result = parts[0];
528
+ }
529
+ }
530
+ return result;
531
+ }
532
+
533
+ function parseLine(line) {
534
+
535
+ let offset = 0;
536
+ let offset2 = 0;
537
+
538
+ function checkColumn(i) {
539
+ offset = offset2;
540
+ if (parsedhead[i]) {
541
+ offset2 = line.substring(parsedhead[i].to + offset, 10000).indexOf(' ');
542
+ } else {
543
+ offset2 = 10000;
544
+ }
545
+ }
546
+
547
+ checkColumn(0);
548
+ const pid = parseInt(line.substring(parsedhead[0].from + offset, parsedhead[0].to + offset2));
549
+ checkColumn(1);
550
+ const ppid = parseInt(line.substring(parsedhead[1].from + offset, parsedhead[1].to + offset2));
551
+ checkColumn(2);
552
+ const cpu = parseFloat(line.substring(parsedhead[2].from + offset, parsedhead[2].to + offset2).replace(/,/g, '.'));
553
+ checkColumn(3);
554
+ const mem = parseFloat(line.substring(parsedhead[3].from + offset, parsedhead[3].to + offset2).replace(/,/g, '.'));
555
+ checkColumn(4);
556
+ const priority = parseInt(line.substring(parsedhead[4].from + offset, parsedhead[4].to + offset2));
557
+ checkColumn(5);
558
+ const vsz = parseInt(line.substring(parsedhead[5].from + offset, parsedhead[5].to + offset2));
559
+ checkColumn(6);
560
+ const rss = parseInt(line.substring(parsedhead[6].from + offset, parsedhead[6].to + offset2));
561
+ checkColumn(7);
562
+ const nice = parseInt(line.substring(parsedhead[7].from + offset, parsedhead[7].to + offset2)) || 0;
563
+ checkColumn(8);
564
+ const started = !_sunos ? parseElapsedTime(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim()) : parseTimeUnix(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim());
565
+ checkColumn(9);
566
+ let state = line.substring(parsedhead[9].from + offset, parsedhead[9].to + offset2).trim();
567
+ state = (state[0] === 'R' ? 'running' : (state[0] === 'S' ? 'sleeping' : (state[0] === 'T' ? 'stopped' : (state[0] === 'W' ? 'paging' : (state[0] === 'X' ? 'dead' : (state[0] === 'Z' ? 'zombie' : ((state[0] === 'D' || state[0] === 'U') ? 'blocked' : 'unknown')))))));
568
+ checkColumn(10);
569
+ let tty = line.substring(parsedhead[10].from + offset, parsedhead[10].to + offset2).trim();
570
+ if (tty === '?' || tty === '??') { tty = ''; }
571
+ checkColumn(11);
572
+ const user = line.substring(parsedhead[11].from + offset, parsedhead[11].to + offset2).trim();
573
+ checkColumn(12);
574
+ let cmdPath = '';
575
+ let command = '';
576
+ let params = '';
577
+ let fullcommand = line.substring(parsedhead[12].from + offset, parsedhead[12].to + offset2).trim();
578
+ if (fullcommand.substr(fullcommand.length - 1) === ']') { fullcommand = fullcommand.slice(0, -1); }
579
+ if (fullcommand.substr(0, 1) === '[') { command = fullcommand.substring(1); }
580
+ else {
581
+ const p1 = fullcommand.indexOf('(');
582
+ const p2 = fullcommand.indexOf(')');
583
+ const p3 = fullcommand.indexOf('/');
584
+ const p4 = fullcommand.indexOf(':');
585
+ if (p1 < p2 && p1 < p3 && p3 < p2) {
586
+ command = fullcommand.split(' ')[0];
587
+ command = command.replace(/:/g, '');
588
+ } else {
589
+ if (p4 > 0 && (p3 === -1 || p3 > 3)) {
590
+ command = fullcommand.split(' ')[0];
591
+ command = command.replace(/:/g, '');
592
+ } else {
593
+ // try to figure out where parameter starts
594
+ let firstParamPos = fullcommand.indexOf(' -');
595
+ let firstParamPathPos = fullcommand.indexOf(' /');
596
+ firstParamPos = (firstParamPos >= 0 ? firstParamPos : 10000);
597
+ firstParamPathPos = (firstParamPathPos >= 0 ? firstParamPathPos : 10000);
598
+ const firstPos = Math.min(firstParamPos, firstParamPathPos);
599
+ let tmpCommand = fullcommand.substr(0, firstPos);
600
+ const tmpParams = fullcommand.substr(firstPos);
601
+ const lastSlashPos = tmpCommand.lastIndexOf('/');
602
+ if (lastSlashPos >= 0) {
603
+ cmdPath = tmpCommand.substr(0, lastSlashPos);
604
+ tmpCommand = tmpCommand.substr(lastSlashPos + 1);
605
+ }
606
+
607
+ if (firstPos === 10000 && tmpCommand.indexOf(' ') > -1) {
608
+ const parts = tmpCommand.split(' ');
609
+ if (fs.existsSync(path.join(cmdPath, parts[0]))) {
610
+ command = parts.shift();
611
+ params = (parts.join(' ') + ' ' + tmpParams).trim();
612
+ } else {
613
+ command = tmpCommand.trim();
614
+ params = tmpParams.trim();
615
+ }
616
+ } else {
617
+ command = tmpCommand.trim();
618
+ params = tmpParams.trim();
619
+ }
620
+ }
621
+ }
622
+
623
+ }
624
+
625
+ return ({
626
+ pid: pid,
627
+ parentPid: ppid,
628
+ name: _linux ? getName(command) : command,
629
+ cpu: cpu,
630
+ cpuu: 0,
631
+ cpus: 0,
632
+ mem: mem,
633
+ priority: priority,
634
+ memVsz: vsz,
635
+ memRss: rss,
636
+ nice: nice,
637
+ started: started,
638
+ state: state,
639
+ tty: tty,
640
+ user: user,
641
+ command: command,
642
+ params: params,
643
+ path: cmdPath
644
+ });
645
+ }
646
+
647
+ function parseProcesses(lines) {
648
+ let result = [];
649
+ if (lines.length > 1) {
650
+ let head = lines[0];
651
+ parsedhead = util.parseHead(head, 8);
652
+ lines.shift();
653
+ lines.forEach(function (line) {
654
+ if (line.trim() !== '') {
655
+ result.push(parseLine(line));
656
+ }
657
+ });
658
+ }
659
+ return result;
660
+ }
661
+ function parseProcesses2(lines) {
662
+
663
+ function formatDateTime(time) {
664
+ const month = ('0' + (time.getMonth() + 1).toString()).slice(-2);
665
+ const year = time.getFullYear().toString();
666
+ const day = ('0' + time.getDate().toString()).slice(-2);
667
+ const hours = ('0' + time.getHours().toString()).slice(-2);
668
+ const mins = ('0' + time.getMinutes().toString()).slice(-2);
669
+ const secs = ('0' + time.getSeconds().toString()).slice(-2);
670
+
671
+ return (year + '-' + month + '-' + day + ' ' + hours + ':' + mins + ':' + secs);
672
+ }
673
+
674
+ function parseElapsed(etime) {
675
+ let started = '';
676
+ if (etime.indexOf('d') >= 0) {
677
+ const elapsed_parts = etime.split('d');
678
+ started = formatDateTime(new Date(Date.now() - (elapsed_parts[0] * 24 + elapsed_parts[1] * 1) * 60 * 60 * 1000));
679
+ } else if (etime.indexOf('h') >= 0) {
680
+ const elapsed_parts = etime.split('h');
681
+ started = formatDateTime(new Date(Date.now() - (elapsed_parts[0] * 60 + elapsed_parts[1] * 1) * 60 * 1000));
682
+ } else if (etime.indexOf(':') >= 0) {
683
+ const elapsed_parts = etime.split(':');
684
+ started = formatDateTime(new Date(Date.now() - (elapsed_parts.length > 1 ? (elapsed_parts[0] * 60 + elapsed_parts[1]) * 1000 : elapsed_parts[0] * 1000)));
685
+ }
686
+ return started;
687
+ }
688
+
689
+ let result = [];
690
+ lines.forEach(function (line) {
691
+ if (line.trim() !== '') {
692
+ line = line.trim().replace(/ +/g, ' ').replace(/,+/g, '.');
693
+ const parts = line.split(' ');
694
+ const command = parts.slice(9).join(' ');
695
+ const pmem = parseFloat((1.0 * parseInt(parts[3]) * 1024 / os.totalmem()).toFixed(1));
696
+ const started = parseElapsed(parts[5]);
697
+
698
+ result.push({
699
+ pid: parseInt(parts[0]),
700
+ parentPid: parseInt(parts[1]),
701
+ name: getName(command),
702
+ cpu: 0,
703
+ cpuu: 0,
704
+ cpus: 0,
705
+ mem: pmem,
706
+ priority: 0,
707
+ memVsz: parseInt(parts[2]),
708
+ memRss: parseInt(parts[3]),
709
+ nice: parseInt(parts[4]),
710
+ started: started,
711
+ state: (parts[6] === 'R' ? 'running' : (parts[6] === 'S' ? 'sleeping' : (parts[6] === 'T' ? 'stopped' : (parts[6] === 'W' ? 'paging' : (parts[6] === 'X' ? 'dead' : (parts[6] === 'Z' ? 'zombie' : ((parts[6] === 'D' || parts[6] === 'U') ? 'blocked' : 'unknown'))))))),
712
+ tty: parts[7],
713
+ user: parts[8],
714
+ command: command
715
+ });
716
+ }
717
+ });
718
+ return result;
719
+ }
720
+
721
+ return new Promise((resolve) => {
722
+ process.nextTick(() => {
723
+ let result = {
724
+ all: 0,
725
+ running: 0,
726
+ blocked: 0,
727
+ sleeping: 0,
728
+ unknown: 0,
729
+ list: []
730
+ };
731
+
732
+ let cmd = '';
733
+
734
+ if ((_processes_cpu.ms && Date.now() - _processes_cpu.ms >= 500) || _processes_cpu.ms === 0) {
735
+ if (_linux || _freebsd || _openbsd || _netbsd || _darwin || _sunos) {
736
+ if (_linux) { cmd = 'export LC_ALL=C; ps -axo pid:11,ppid:11,pcpu:6,pmem:6,pri:5,vsz:11,rss:11,ni:5,etime:30,state:5,tty:15,user:20,command; unset LC_ALL'; }
737
+ if (_freebsd || _openbsd || _netbsd) { cmd = 'export LC_ALL=C; ps -axo pid,ppid,pcpu,pmem,pri,vsz,rss,ni,etime,state,tty,user,command; unset LC_ALL'; }
738
+ if (_darwin) { cmd = 'ps -axo pid,ppid,pcpu,pmem,pri,vsz=temp_title_1,rss=temp_title_2,nice,etime=temp_title_3,state,tty,user,command -r'; }
739
+ if (_sunos) { cmd = 'ps -Ao pid,ppid,pcpu,pmem,pri,vsz,rss,nice,stime,s,tty,user,comm'; }
740
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
741
+ if (!error && stdout.toString().trim()) {
742
+ result.list = (parseProcesses(stdout.toString().split('\n'))).slice();
743
+ result.all = result.list.length;
744
+ result.running = result.list.filter(function (e) {
745
+ return e.state === 'running';
746
+ }).length;
747
+ result.blocked = result.list.filter(function (e) {
748
+ return e.state === 'blocked';
749
+ }).length;
750
+ result.sleeping = result.list.filter(function (e) {
751
+ return e.state === 'sleeping';
752
+ }).length;
753
+
754
+ if (_linux) {
755
+ // calc process_cpu - ps is not accurate in linux!
756
+ cmd = 'cat /proc/stat | grep "cpu "';
757
+ result.list.forEach((element) => {
758
+ cmd += (';cat /proc/' + element.pid + '/stat');
759
+ });
760
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
761
+ let curr_processes = stdout.toString().split('\n');
762
+
763
+ // first line (all - /proc/stat)
764
+ let all = parseProcStat(curr_processes.shift());
765
+
766
+ // process
767
+ let list_new = {};
768
+ let resultProcess = {};
769
+ curr_processes.forEach((element) => {
770
+ resultProcess = calcProcStatLinux(element, all, _processes_cpu);
771
+
772
+ if (resultProcess.pid) {
773
+
774
+ // store pcpu in outer array
775
+ let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid);
776
+ if (listPos >= 0) {
777
+ result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus;
778
+ result.list[listPos].cpuu = resultProcess.cpuu;
779
+ result.list[listPos].cpus = resultProcess.cpus;
780
+ }
781
+
782
+ // save new values
783
+ list_new[resultProcess.pid] = {
784
+ cpuu: resultProcess.cpuu,
785
+ cpus: resultProcess.cpus,
786
+ utime: resultProcess.utime,
787
+ stime: resultProcess.stime,
788
+ cutime: resultProcess.cutime,
789
+ cstime: resultProcess.cstime
790
+ };
791
+ }
792
+ });
793
+
794
+ // store old values
795
+ _processes_cpu.all = all;
796
+ _processes_cpu.list = Object.assign({}, list_new);
797
+ _processes_cpu.ms = Date.now() - _processes_cpu.ms;
798
+ _processes_cpu.result = Object.assign({}, result);
799
+ if (callback) { callback(result); }
800
+ resolve(result);
801
+ });
802
+ } else {
803
+ if (callback) { callback(result); }
804
+ resolve(result);
805
+ }
806
+ } else {
807
+ cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,stat,tty,user,comm';
808
+ if (_sunos) {
809
+ cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,s,tty,user,comm';
810
+ }
811
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
812
+ if (!error) {
813
+ let lines = stdout.toString().split('\n');
814
+ lines.shift();
815
+
816
+ result.list = parseProcesses2(lines).slice();
817
+ result.all = result.list.length;
818
+ result.running = result.list.filter(function (e) {
819
+ return e.state === 'running';
820
+ }).length;
821
+ result.blocked = result.list.filter(function (e) {
822
+ return e.state === 'blocked';
823
+ }).length;
824
+ result.sleeping = result.list.filter(function (e) {
825
+ return e.state === 'sleeping';
826
+ }).length;
827
+ if (callback) { callback(result); }
828
+ resolve(result);
829
+ } else {
830
+ if (callback) { callback(result); }
831
+ resolve(result);
832
+ }
833
+ });
834
+ }
835
+ });
836
+ } else if (_windows) {
837
+ try {
838
+ util.powerShell('Get-CimInstance Win32_Process | select-Object ProcessId,ParentProcessId,ExecutionState,Caption,CommandLine,ExecutablePath,UserModeTime,KernelModeTime,WorkingSetSize,Priority,PageFileUsage, @{n="CreationDate";e={$_.CreationDate.ToString("yyyy-MM-dd HH:mm:ss")}} | fl').then((stdout, error) => {
839
+ if (!error) {
840
+ let processSections = stdout.split(/\n\s*\n/);
841
+ let procs = [];
842
+ let procStats = [];
843
+ let list_new = {};
844
+ let allcpuu = 0;
845
+ let allcpus = 0;
846
+ processSections.forEach((element) => {
847
+ if (element.trim() !== '') {
848
+ let lines = element.trim().split('\r\n');
849
+ let pid = parseInt(util.getValue(lines, 'ProcessId', ':', true), 10);
850
+ let parentPid = parseInt(util.getValue(lines, 'ParentProcessId', ':', true), 10);
851
+ let statusValue = util.getValue(lines, 'ExecutionState', ':');
852
+ let name = util.getValue(lines, 'Caption', ':', true);
853
+ let commandLine = util.getValue(lines, 'CommandLine', ':', true);
854
+ // get additional command line data
855
+ let additionalCommand = false;
856
+ lines.forEach((line) => {
857
+ if (additionalCommand && line.toLowerCase().startsWith(' ')) {
858
+ commandLine += ' ' + line.trim();
859
+ } else {
860
+ additionalCommand = false;
861
+ }
862
+ if (line.toLowerCase().startsWith('commandline')) {
863
+ additionalCommand = true;
864
+ }
865
+ });
866
+ let commandPath = util.getValue(lines, 'ExecutablePath', ':', true);
867
+ let utime = parseInt(util.getValue(lines, 'UserModeTime', ':', true), 10);
868
+ let stime = parseInt(util.getValue(lines, 'KernelModeTime', ':', true), 10);
869
+ let memw = parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10);
870
+ allcpuu = allcpuu + utime;
871
+ allcpus = allcpus + stime;
872
+ result.all++;
873
+ if (!statusValue) { result.unknown++; }
874
+ if (statusValue === '3') { result.running++; }
875
+ if (statusValue === '4' || statusValue === '5') { result.blocked++; }
876
+
877
+ procStats.push({
878
+ pid: pid,
879
+ utime: utime,
880
+ stime: stime,
881
+ cpu: 0,
882
+ cpuu: 0,
883
+ cpus: 0,
884
+ });
885
+ procs.push({
886
+ pid: pid,
887
+ parentPid: parentPid,
888
+ name: name,
889
+ cpu: 0,
890
+ cpuu: 0,
891
+ cpus: 0,
892
+ mem: memw / os.totalmem() * 100,
893
+ priority: parseInt(util.getValue(lines, 'Priority', ':', true), 10),
894
+ memVsz: parseInt(util.getValue(lines, 'PageFileUsage', ':', true), 10),
895
+ memRss: Math.floor(parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10) / 1024),
896
+ nice: 0,
897
+ started: util.getValue(lines, 'CreationDate', ':', true),
898
+ state: (!statusValue ? _winStatusValues[0] : _winStatusValues[statusValue]),
899
+ tty: '',
900
+ user: '',
901
+ command: commandLine || name,
902
+ path: commandPath,
903
+ params: ''
904
+ });
905
+ }
906
+ });
907
+
908
+ result.sleeping = result.all - result.running - result.blocked - result.unknown;
909
+ result.list = procs;
910
+ procStats.forEach((element) => {
911
+ let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _processes_cpu);
912
+
913
+ // store pcpu in outer array
914
+ let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid);
915
+ if (listPos >= 0) {
916
+ result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus;
917
+ result.list[listPos].cpuu = resultProcess.cpuu;
918
+ result.list[listPos].cpus = resultProcess.cpus;
919
+ }
920
+
921
+ // save new values
922
+ list_new[resultProcess.pid] = {
923
+ cpuu: resultProcess.cpuu,
924
+ cpus: resultProcess.cpus,
925
+ utime: resultProcess.utime,
926
+ stime: resultProcess.stime
927
+ };
928
+ });
929
+
930
+ // store old values
931
+ _processes_cpu.all = allcpuu + allcpus;
932
+ _processes_cpu.all_utime = allcpuu;
933
+ _processes_cpu.all_stime = allcpus;
934
+ _processes_cpu.list = Object.assign({}, list_new);
935
+ _processes_cpu.ms = Date.now() - _processes_cpu.ms;
936
+ _processes_cpu.result = Object.assign({}, result);
937
+ }
938
+ if (callback) {
939
+ callback(result);
940
+ }
941
+ resolve(result);
942
+ });
943
+ } catch (e) {
944
+ if (callback) { callback(result); }
945
+ resolve(result);
946
+ }
947
+ } else {
948
+ if (callback) { callback(result); }
949
+ resolve(result);
950
+ }
951
+ } else {
952
+ if (callback) { callback(_processes_cpu.result); }
953
+ resolve(_processes_cpu.result);
954
+ }
955
+ });
956
+ });
957
+ }
958
+
959
+ exports.processes = processes;
960
+
961
+ // --------------------------
962
+ // PS - process load
963
+ // get detailed information about a certain process
964
+ // (PID, CPU-Usage %, Mem-Usage %)
965
+
966
+ function processLoad(proc, callback) {
967
+
968
+ // fallback - if only callback is given
969
+ if (util.isFunction(proc) && !callback) {
970
+ callback = proc;
971
+ proc = '';
972
+ }
973
+
974
+ return new Promise((resolve) => {
975
+ process.nextTick(() => {
976
+
977
+ proc = proc || '';
978
+
979
+ if (typeof proc !== 'string') {
980
+ if (callback) { callback([]); }
981
+ return resolve([]);
982
+ }
983
+
984
+ let processesString = '';
985
+ processesString.__proto__.toLowerCase = util.stringToLower;
986
+ processesString.__proto__.replace = util.stringReplace;
987
+ processesString.__proto__.trim = util.stringTrim;
988
+
989
+ const s = util.sanitizeShellString(proc);
990
+ const l = util.mathMin(s.length, 2000);
991
+
992
+ for (let i = 0; i <= l; i++) {
993
+ if (s[i] !== undefined) {
994
+ processesString = processesString + s[i];
995
+ }
996
+ }
997
+
998
+ processesString = processesString.trim().toLowerCase().replace(/, /g, '|').replace(/,+/g, '|');
999
+ if (processesString === '') {
1000
+ processesString = '*';
1001
+ }
1002
+ if (util.isPrototypePolluted() && processesString !== '*') {
1003
+ processesString = '------';
1004
+ }
1005
+ let processes = processesString.split('|');
1006
+ let result = [];
1007
+
1008
+ const procSanitized = util.isPrototypePolluted() ? '' : (util.sanitizeShellString(proc) || '*');
1009
+
1010
+ // from here new
1011
+ // let result = {
1012
+ // 'proc': procSanitized,
1013
+ // 'pid': null,
1014
+ // 'cpu': 0,
1015
+ // 'mem': 0
1016
+ // };
1017
+ if (procSanitized && processes.length && processes[0] !== '------') {
1018
+ if (_windows) {
1019
+ try {
1020
+ util.powerShell('Get-CimInstance Win32_Process | select ProcessId,Caption,UserModeTime,KernelModeTime,WorkingSetSize | fl').then((stdout, error) => {
1021
+ if (!error) {
1022
+ let processSections = stdout.split(/\n\s*\n/);
1023
+ let procStats = [];
1024
+ let list_new = {};
1025
+ let allcpuu = 0;
1026
+ let allcpus = 0;
1027
+
1028
+ // go through all processes
1029
+ processSections.forEach((element) => {
1030
+ if (element.trim() !== '') {
1031
+ let lines = element.trim().split('\r\n');
1032
+ let pid = parseInt(util.getValue(lines, 'ProcessId', ':', true), 10);
1033
+ let name = util.getValue(lines, 'Caption', ':', true);
1034
+ let utime = parseInt(util.getValue(lines, 'UserModeTime', ':', true), 10);
1035
+ let stime = parseInt(util.getValue(lines, 'KernelModeTime', ':', true), 10);
1036
+ let mem = parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10);
1037
+ allcpuu = allcpuu + utime;
1038
+ allcpus = allcpus + stime;
1039
+
1040
+ procStats.push({
1041
+ pid: pid,
1042
+ name,
1043
+ utime: utime,
1044
+ stime: stime,
1045
+ cpu: 0,
1046
+ cpuu: 0,
1047
+ cpus: 0,
1048
+ mem
1049
+ });
1050
+ let pname = '';
1051
+ let inList = false;
1052
+ processes.forEach(function (proc) {
1053
+ if (name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) {
1054
+ inList = true;
1055
+ pname = proc;
1056
+ }
1057
+ });
1058
+
1059
+ if (processesString === '*' || inList) {
1060
+ let processFound = false;
1061
+ result.forEach(function (item) {
1062
+ if (item.proc.toLowerCase() === pname.toLowerCase()) {
1063
+ item.pids.push(pid);
1064
+ item.mem += mem / os.totalmem() * 100;
1065
+ processFound = true;
1066
+ }
1067
+ });
1068
+ if (!processFound) {
1069
+ result.push({
1070
+ proc: pname,
1071
+ pid: pid,
1072
+ pids: [pid],
1073
+ cpu: 0,
1074
+ mem: mem / os.totalmem() * 100
1075
+ });
1076
+ }
1077
+ }
1078
+ }
1079
+ });
1080
+
1081
+ // add missing processes
1082
+ if (processesString !== '*') {
1083
+ let processesMissing = processes.filter(function (name) {
1084
+ return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0;
1085
+
1086
+ });
1087
+ processesMissing.forEach(function (procName) {
1088
+ result.push({
1089
+ proc: procName,
1090
+ pid: null,
1091
+ pids: [],
1092
+ cpu: 0,
1093
+ mem: 0
1094
+ });
1095
+ });
1096
+ }
1097
+
1098
+ // calculate proc stats for each proc
1099
+ procStats.forEach((element) => {
1100
+ let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _process_cpu);
1101
+
1102
+ let listPos = -1;
1103
+ for (let j = 0; j < result.length; j++) {
1104
+ if (result[j].pid === resultProcess.pid || result[j].pids.indexOf(resultProcess.pid) >= 0) { listPos = j; }
1105
+ }
1106
+ if (listPos >= 0) {
1107
+ result[listPos].cpu += resultProcess.cpuu + resultProcess.cpus;
1108
+ }
1109
+
1110
+ // save new values
1111
+ list_new[resultProcess.pid] = {
1112
+ cpuu: resultProcess.cpuu,
1113
+ cpus: resultProcess.cpus,
1114
+ utime: resultProcess.utime,
1115
+ stime: resultProcess.stime
1116
+ };
1117
+ });
1118
+
1119
+ // store old values
1120
+ _process_cpu.all = allcpuu + allcpus;
1121
+ _process_cpu.all_utime = allcpuu;
1122
+ _process_cpu.all_stime = allcpus;
1123
+ _process_cpu.list = Object.assign({}, list_new);
1124
+ _process_cpu.ms = Date.now() - _process_cpu.ms;
1125
+ _process_cpu.result = JSON.parse(JSON.stringify(result));
1126
+ if (callback) {
1127
+ callback(result);
1128
+ }
1129
+ resolve(result);
1130
+ }
1131
+ });
1132
+ } catch (e) {
1133
+ if (callback) { callback(result); }
1134
+ resolve(result);
1135
+ }
1136
+ }
1137
+
1138
+ if (_darwin || _linux || _freebsd || _openbsd || _netbsd) {
1139
+ const params = ['-axo', 'pid,ppid,pcpu,pmem,comm'];
1140
+ util.execSafe('ps', params).then((stdout) => {
1141
+ if (stdout) {
1142
+ let procStats = [];
1143
+ let lines = stdout.toString().split('\n').filter(function (line) {
1144
+ if (processesString === '*') { return true; }
1145
+ if (line.toLowerCase().indexOf('grep') !== -1) { return false; } // remove this??
1146
+ let found = false;
1147
+ processes.forEach(function (item) {
1148
+ found = found || (line.toLowerCase().indexOf(item.toLowerCase()) >= 0);
1149
+ });
1150
+ return found;
1151
+ });
1152
+ lines.shift();
1153
+ lines.forEach(function (line) {
1154
+ let data = line.trim().replace(/ +/g, ' ').split(' ');
1155
+ if (data.length > 4) {
1156
+ const linuxName = data[4].indexOf('/') >= 0 ? data[4].substring(0, data[4].indexOf('/')) : data[4];
1157
+ const name = _linux ? (linuxName) : data[4].substring(data[4].lastIndexOf('/') + 1);
1158
+ procStats.push({
1159
+ name,
1160
+ pid: parseInt(data[0]) || 0,
1161
+ ppid: parseInt(data[1]) || 0,
1162
+ cpu: parseFloat(data[2].replace(',', '.')),
1163
+ mem: parseFloat(data[3].replace(',', '.'))
1164
+ });
1165
+ }
1166
+ });
1167
+
1168
+ procStats.forEach(function (item) {
1169
+ let listPos = -1;
1170
+ let inList = false;
1171
+ let name = item.name;
1172
+ for (let j = 0; j < result.length; j++) {
1173
+ if (item.name.toLowerCase().indexOf(result[j].proc.toLowerCase()) >= 0) {
1174
+ listPos = j;
1175
+ }
1176
+ }
1177
+ processes.forEach(function (proc) {
1178
+
1179
+ if (item.name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) {
1180
+ inList = true;
1181
+ name = proc;
1182
+ }
1183
+ });
1184
+ if ((processesString === '*') || inList) {
1185
+ if (listPos < 0) {
1186
+ if (name) {
1187
+ result.push({
1188
+ proc: name,
1189
+ pid: item.pid,
1190
+ pids: [item.pid],
1191
+ cpu: item.cpu,
1192
+ mem: item.mem
1193
+ });
1194
+ }
1195
+ } else {
1196
+ if (item.ppid < 10) {
1197
+ result[listPos].pid = item.pid;
1198
+ }
1199
+ result[listPos].pids.push(item.pid);
1200
+ result[listPos].cpu += item.cpu;
1201
+ result[listPos].mem += item.mem;
1202
+ }
1203
+ }
1204
+ });
1205
+
1206
+ if (processesString !== '*') {
1207
+ // add missing processes
1208
+ let processesMissing = processes.filter(function (name) {
1209
+ return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0;
1210
+ });
1211
+ processesMissing.forEach(function (procName) {
1212
+ result.push({
1213
+ proc: procName,
1214
+ pid: null,
1215
+ pids: [],
1216
+ cpu: 0,
1217
+ mem: 0
1218
+ });
1219
+ });
1220
+ }
1221
+ if (_linux) {
1222
+ // calc process_cpu - ps is not accurate in linux!
1223
+ result.forEach(function (item) {
1224
+ item.cpu = 0;
1225
+ });
1226
+ let cmd = 'cat /proc/stat | grep "cpu "';
1227
+ for (let i in result) {
1228
+ for (let j in result[i].pids) {
1229
+ cmd += (';cat /proc/' + result[i].pids[j] + '/stat');
1230
+ }
1231
+ }
1232
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
1233
+ let curr_processes = stdout.toString().split('\n');
1234
+
1235
+ // first line (all - /proc/stat)
1236
+ let all = parseProcStat(curr_processes.shift());
1237
+
1238
+ // process
1239
+ let list_new = {};
1240
+ let resultProcess = {};
1241
+ curr_processes.forEach((element) => {
1242
+ resultProcess = calcProcStatLinux(element, all, _process_cpu);
1243
+
1244
+ if (resultProcess.pid) {
1245
+
1246
+ // find result item
1247
+ let resultItemId = -1;
1248
+ for (let i in result) {
1249
+ if (result[i].pids.indexOf(resultProcess.pid) >= 0) {
1250
+ resultItemId = i;
1251
+ }
1252
+ }
1253
+ // store pcpu in outer result
1254
+ if (resultItemId >= 0) {
1255
+ result[resultItemId].cpu += resultProcess.cpuu + resultProcess.cpus;
1256
+ }
1257
+
1258
+ // save new values
1259
+ list_new[resultProcess.pid] = {
1260
+ cpuu: resultProcess.cpuu,
1261
+ cpus: resultProcess.cpus,
1262
+ utime: resultProcess.utime,
1263
+ stime: resultProcess.stime,
1264
+ cutime: resultProcess.cutime,
1265
+ cstime: resultProcess.cstime
1266
+ };
1267
+ }
1268
+ });
1269
+
1270
+ result.forEach(function (item) {
1271
+ item.cpu = Math.round(item.cpu * 100) / 100;
1272
+ });
1273
+
1274
+ _process_cpu.all = all;
1275
+ _process_cpu.list = Object.assign({}, list_new);
1276
+ _process_cpu.ms = Date.now() - _process_cpu.ms;
1277
+ _process_cpu.result = Object.assign({}, result);
1278
+ if (callback) { callback(result); }
1279
+ resolve(result);
1280
+ });
1281
+ } else {
1282
+ if (callback) { callback(result); }
1283
+ resolve(result);
1284
+ }
1285
+ } else {
1286
+ if (callback) { callback(result); }
1287
+ resolve(result);
1288
+ }
1289
+ });
1290
+ }
1291
+ }
1292
+ });
1293
+ });
1294
+ }
1295
+
1296
+ exports.processLoad = processLoad;