sysinfo.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /*
  2. Copyright 2019-2021 Intel Corporation
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. var PDH_FMT_LONG = 0x00000100;
  14. var PDH_FMT_DOUBLE = 0x00000200;
  15. var promise = require('promise');
  16. if (process.platform == 'win32')
  17. {
  18. var GM = require('_GenericMarshal');
  19. GM.kernel32 = GM.CreateNativeProxy('kernel32.dll');
  20. GM.kernel32.CreateMethod('GlobalMemoryStatusEx');
  21. GM.pdh = GM.CreateNativeProxy('pdh.dll');
  22. GM.pdh.CreateMethod('PdhAddEnglishCounterA');
  23. GM.pdh.CreateMethod('PdhCloseQuery');
  24. GM.pdh.CreateMethod('PdhCollectQueryData');
  25. GM.pdh.CreateMethod('PdhGetFormattedCounterValue');
  26. GM.pdh.CreateMethod('PdhGetFormattedCounterArrayA');
  27. GM.pdh.CreateMethod('PdhOpenQueryA');
  28. GM.pdh.CreateMethod('PdhRemoveCounter');
  29. }
  30. function windows_cpuUtilization()
  31. {
  32. var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
  33. p.counter = GM.CreateVariable(16);
  34. p.cpu = GM.CreatePointer();
  35. p.cpuTotal = GM.CreatePointer();
  36. var err = 0;
  37. if ((err = GM.pdh.PdhOpenQueryA(0, 0, p.cpu).Val) != 0) { p._rej(err); return; }
  38. // This gets the CPU Utilization for each proc
  39. if ((err = GM.pdh.PdhAddEnglishCounterA(p.cpu.Deref(), GM.CreateVariable('\\Processor(*)\\% Processor Time'), 0, p.cpuTotal).Val) != 0) { p._rej(err); return; }
  40. if ((err = GM.pdh.PdhCollectQueryData(p.cpu.Deref()).Val != 0)) { p._rej(err); return; }
  41. p._timeout = setTimeout(function (po)
  42. {
  43. var u = { cpus: [] };
  44. var bufSize = GM.CreateVariable(4);
  45. var itemCount = GM.CreateVariable(4);
  46. var buffer, szName, item;
  47. var e;
  48. if ((e = GM.pdh.PdhCollectQueryData(po.cpu.Deref()).Val != 0)) { po._rej(e); return; }
  49. if ((e = GM.pdh.PdhGetFormattedCounterArrayA(po.cpuTotal.Deref(), PDH_FMT_DOUBLE, bufSize, itemCount, 0).Val) == -2147481646)
  50. {
  51. buffer = GM.CreateVariable(bufSize.toBuffer().readUInt32LE());
  52. }
  53. else
  54. {
  55. po._rej(e);
  56. return;
  57. }
  58. if ((e = GM.pdh.PdhGetFormattedCounterArrayA(po.cpuTotal.Deref(), PDH_FMT_DOUBLE, bufSize, itemCount, buffer).Val) != 0) { po._rej(e); return; }
  59. for(var i=0;i<itemCount.toBuffer().readUInt32LE();++i)
  60. {
  61. item = buffer.Deref(i * 24, 24);
  62. szName = item.Deref(0, GM.PointerSize).Deref();
  63. if (szName.String == '_Total')
  64. {
  65. u.total = item.Deref(16, 8).toBuffer().readDoubleLE();
  66. }
  67. else
  68. {
  69. u.cpus[parseInt(szName.String)] = item.Deref(16, 8).toBuffer().readDoubleLE();
  70. }
  71. }
  72. GM.pdh.PdhRemoveCounter(po.cpuTotal.Deref());
  73. GM.pdh.PdhCloseQuery(po.cpu.Deref());
  74. p._res(u);
  75. }, 100, p);
  76. return (p);
  77. }
  78. function windows_memUtilization()
  79. {
  80. var info = GM.CreateVariable(64);
  81. info.Deref(0, 4).toBuffer().writeUInt32LE(64);
  82. GM.kernel32.GlobalMemoryStatusEx(info);
  83. var ret =
  84. {
  85. MemTotal: require('bignum').fromBuffer(info.Deref(8, 8).toBuffer(), { endian: 'little' }),
  86. MemFree: require('bignum').fromBuffer(info.Deref(16, 8).toBuffer(), { endian: 'little' })
  87. };
  88. ret.percentFree = ((ret.MemFree.div(require('bignum')('1048576')).toNumber() / ret.MemTotal.div(require('bignum')('1048576')).toNumber()) * 100);//.toFixed(2);
  89. ret.percentConsumed = ((ret.MemTotal.sub(ret.MemFree).div(require('bignum')('1048576')).toNumber() / ret.MemTotal.div(require('bignum')('1048576')).toNumber()) * 100);//.toFixed(2);
  90. ret.MemTotal = ret.MemTotal.toString();
  91. ret.MemFree = ret.MemFree.toString();
  92. return (ret);
  93. }
  94. var cpuLastIdle = [];
  95. var cpuLastSum = [];
  96. function linux_cpuUtilization() {
  97. var ret = { cpus: [] };
  98. var info = require('fs').readFileSync('/proc/stat');
  99. var lines = info.toString().split('\n');
  100. var columns;
  101. var x, y;
  102. var cpuNo = 0;
  103. var currSum, currIdle, utilization;
  104. for (var i in lines) {
  105. columns = lines[i].split(' ');
  106. if (!columns[0].startsWith('cpu')) { break; }
  107. x = 0, currSum = 0;
  108. while (columns[++x] == '');
  109. for (y = x; y < columns.length; ++y) { currSum += parseInt(columns[y]); }
  110. currIdle = parseInt(columns[3 + x]);
  111. var diffIdle = currIdle - cpuLastIdle[cpuNo];
  112. var diffSum = currSum - cpuLastSum[cpuNo];
  113. utilization = (100 - ((diffIdle / diffSum) * 100));
  114. cpuLastSum[cpuNo] = currSum;
  115. cpuLastIdle[cpuNo] = currIdle;
  116. if (!ret.total) {
  117. ret.total = utilization;
  118. } else {
  119. ret.cpus.push(utilization);
  120. }
  121. ++cpuNo;
  122. }
  123. var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
  124. p._res(ret);
  125. return (p);
  126. }
  127. function linux_memUtilization()
  128. {
  129. var ret = {};
  130. var info = require('fs').readFileSync('/proc/meminfo').toString().split('\n');
  131. var tokens;
  132. for(var i in info)
  133. {
  134. tokens = info[i].split(' ');
  135. switch(tokens[0])
  136. {
  137. case 'MemTotal:':
  138. ret.total = parseInt(tokens[tokens.length - 2]);
  139. break;
  140. case 'MemFree:':
  141. ret.free = parseInt(tokens[tokens.length - 2]);
  142. break;
  143. }
  144. }
  145. ret.percentFree = ((ret.free / ret.total) * 100);//.toFixed(2);
  146. ret.percentConsumed = (((ret.total - ret.free) / ret.total) * 100);//.toFixed(2);
  147. return (ret);
  148. }
  149. function macos_cpuUtilization()
  150. {
  151. var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
  152. var child = require('child_process').execFile('/bin/sh', ['sh']);
  153. child.stdout.str = '';
  154. child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
  155. child.stdin.write('top -l 1 | grep -E "^CPU"\nexit\n');
  156. child.waitExit();
  157. var lines = child.stdout.str.split('\n');
  158. if (lines[0].length > 0)
  159. {
  160. var usage = lines[0].split(':')[1];
  161. var bdown = usage.split(',');
  162. var tot = parseFloat(bdown[0].split('%')[0].trim()) + parseFloat(bdown[1].split('%')[0].trim());
  163. ret._res({total: tot, cpus: []});
  164. }
  165. else
  166. {
  167. ret._rej('parse error');
  168. }
  169. return (ret);
  170. }
  171. function macos_memUtilization()
  172. {
  173. var mem = { };
  174. var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
  175. var child = require('child_process').execFile('/bin/sh', ['sh']);
  176. child.stdout.str = '';
  177. child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
  178. child.stdin.write('top -l 1 | grep -E "^Phys"\nexit\n');
  179. child.waitExit();
  180. var lines = child.stdout.str.split('\n');
  181. if (lines[0].length > 0)
  182. {
  183. var usage = lines[0].split(':')[1];
  184. var bdown = usage.split(',');
  185. mem.MemTotal = parseInt(bdown[0].trim().split(' ')[0]);
  186. mem.MemFree = parseInt(bdown[1].trim().split(' ')[0]);
  187. mem.percentFree = ((mem.MemFree / mem.MemTotal) * 100);//.toFixed(2);
  188. mem.percentConsumed = (((mem.MemTotal - mem.MemFree) / mem.MemTotal) * 100);//.toFixed(2);
  189. return (mem);
  190. }
  191. else
  192. {
  193. throw ('Parse Error');
  194. }
  195. }
  196. function windows_thermals()
  197. {
  198. var ret = [];
  199. try {
  200. ret = require('win-wmi').query('ROOT\\WMI', 'SELECT CurrentTemperature,InstanceName FROM MSAcpi_ThermalZoneTemperature',['CurrentTemperature','InstanceName']);
  201. if (ret[0]) {
  202. for (var i = 0; i < ret.length; ++i) {
  203. ret[i]['CurrentTemperature'] = ((parseFloat(ret[i]['CurrentTemperature']) / 10) - 273.15).toFixed(2);
  204. }
  205. }
  206. } catch (ex) { }
  207. return (ret);
  208. }
  209. function linux_thermals()
  210. {
  211. child = require('child_process').execFile('/bin/sh', ['sh']);
  212. child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
  213. child.stderr.str = ''; child.stderr.on('data', function (c) { this.str += c.toString(); });
  214. child.stdin.write("cat /sys/class/thermal/thermal_zone*/temp | awk '{ print $0 / 1000 }'\nexit\n");
  215. child.waitExit();
  216. var ret = child.stdout.str.trim().split('\n');
  217. if (ret.length == 1 && ret[0] == '') { ret = []; }
  218. return (ret);
  219. }
  220. function macos_thermals()
  221. {
  222. var ret = [];
  223. var child = require('child_process').execFile('/bin/sh', ['sh']);
  224. child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
  225. child.stderr.on('data', function () { });
  226. child.stdin.write('powermetrics --help | grep SMC\nexit\n');
  227. child.waitExit();
  228. if (child.stdout.str.trim() != '')
  229. {
  230. child = require('child_process').execFile('/bin/sh', ['sh']);
  231. child.stdout.str = ''; child.stdout.on('data', function (c)
  232. {
  233. this.str += c.toString();
  234. var tokens = this.str.trim().split('\n');
  235. for (var i in tokens)
  236. {
  237. if (tokens[i].split(' die temperature: ').length > 1)
  238. {
  239. ret.push(tokens[i].split(' ')[3]);
  240. this.parent.kill();
  241. }
  242. }
  243. });
  244. child.stderr.str = ''; child.stderr.on('data', function (c) { this.str += c.toString(); });
  245. child.stdin.write('powermetrics -s smc\n');
  246. child.waitExit(5000);
  247. }
  248. return (ret);
  249. }
  250. const platformConfig = {
  251. linux: { cpuUtilization: linux_cpuUtilization, memUtilization: linux_memUtilization, thermals: linux_thermals },
  252. win32: { cpuUtilization: windows_cpuUtilization, memUtilization: windows_memUtilization, thermals: windows_thermals },
  253. darwin: { cpuUtilization: macos_cpuUtilization, memUtilization: macos_memUtilization, thermals: macos_thermals }
  254. };
  255. module.exports = platformConfig[process.platform];