HttpInterface.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * Copyright 2013-2022 the PM2 project authors. All rights reserved.
  3. * Use of this source code is governed by a license that
  4. * can be found in the LICENSE file.
  5. */
  6. var http = require('http');
  7. var os = require('os');
  8. var pm2 = require('../index.js');
  9. var urlT = require('url');
  10. var cst = require('../constants.js');
  11. // Default, attach to default local PM2
  12. pm2.connect(function() {
  13. startWebServer(pm2);
  14. });
  15. function startWebServer(pm2) {
  16. http.createServer(function (req, res) {
  17. // Add CORS headers to allow browsers to fetch data directly
  18. res.setHeader('Access-Control-Allow-Origin', '*');
  19. res.setHeader('Access-Control-Allow-Headers', 'Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With');
  20. res.setHeader('Access-Control-Allow-Methods', 'GET');
  21. // We always send json
  22. res.setHeader('Content-Type','application/json');
  23. var path = urlT.parse(req.url).pathname;
  24. if (path == '/') {
  25. // Main monit route
  26. pm2.list(function(err, list) {
  27. if (err) {
  28. return res.send(err);
  29. }
  30. var data = {
  31. system_info: { hostname: os.hostname(),
  32. uptime: os.uptime()
  33. },
  34. monit: { loadavg: os.loadavg(),
  35. total_mem: os.totalmem(),
  36. free_mem: os.freemem(),
  37. cpu: os.cpus(),
  38. interfaces: os.networkInterfaces()
  39. },
  40. processes: list
  41. };
  42. if (cst.WEB_STRIP_ENV_VARS === true) {
  43. for (var i = data.processes.length - 1; i >= 0; i--) {
  44. var proc = data.processes[i];
  45. // Strip important environment variables
  46. if (typeof proc.pm2_env === 'undefined' && typeof proc.pm2_env.env === 'undefined') return;
  47. delete proc.pm2_env.env;
  48. }
  49. }
  50. res.statusCode = 200;
  51. res.write(JSON.stringify(data));
  52. return res.end();
  53. })
  54. }
  55. else {
  56. // 404
  57. res.statusCode = 404;
  58. res.write(JSON.stringify({err : '404'}));
  59. return res.end();
  60. }
  61. }).listen(process.env.PM2_WEB_PORT || cst.WEB_PORT, cst.WEB_IPADDR, function() {
  62. console.log('Web interface listening on %s:%s', cst.WEB_IPADDR, cst.WEB_PORT);
  63. });
  64. }