cpu.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. const os = require('os')
  2. const fs = require('fs')
  3. const exec = require('child_process').exec
  4. const parallel = require('./parallel')
  5. /**
  6. * Gathers Clock, PageSize and system uptime through /proc/uptime
  7. * This method is mocked in procfile tests
  8. */
  9. function updateCpu (cpu, next) {
  10. if (cpu !== null) {
  11. getRealUptime(function (err, uptime) {
  12. if (err) return next(err)
  13. cpu.uptime = uptime
  14. next(null, cpu)
  15. })
  16. return
  17. }
  18. parallel([
  19. getClockAndPageSize,
  20. getRealUptime
  21. ], function (err, data) {
  22. if (err) return next(err)
  23. cpu = {
  24. clockTick: data[0].clockTick,
  25. pageSize: data[0].pageSize,
  26. uptime: data[1]
  27. }
  28. next(null, cpu)
  29. })
  30. }
  31. module.exports = updateCpu
  32. /**
  33. * Fallback on os.uptime(), though /proc/uptime is more precise
  34. */
  35. function getRealUptime (next) {
  36. fs.readFile('/proc/uptime', 'utf8', function (err, uptime) {
  37. if (err || uptime === undefined) {
  38. if (!process.env.PIDUSAGE_SILENT) {
  39. console.warn("[pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value")
  40. }
  41. return next(null, os.uptime() || (new Date() / 1000))
  42. }
  43. return next(null, parseFloat(uptime.split(' ')[0]))
  44. })
  45. }
  46. function getClockAndPageSize (next) {
  47. parallel([
  48. function getClockTick (cb) {
  49. getconf('CLK_TCK', { default: 100 }, cb)
  50. },
  51. function getPageSize (cb) {
  52. getconf('PAGESIZE', { default: 4096 }, cb)
  53. }
  54. ], function (err, data) {
  55. if (err) return next(err)
  56. next(null, { clockTick: data[0], pageSize: data[1] })
  57. })
  58. }
  59. function getconf (keyword, options, next) {
  60. if (typeof options === 'function') {
  61. next = options
  62. options = { default: '' }
  63. }
  64. exec('getconf ' + keyword, function (error, stdout, stderr) {
  65. if (error !== null) {
  66. if (!process.env.PIDUSAGE_SILENT) {
  67. console.error('Error while calling "getconf ' + keyword + '"', error)
  68. }
  69. return next(null, options.default)
  70. }
  71. stdout = parseInt(stdout)
  72. if (!isNaN(stdout)) {
  73. return next(null, stdout)
  74. }
  75. return next(null, options.default)
  76. })
  77. }