Utility.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. /**
  7. * Common Utilities ONLY USED IN ->DAEMON<-
  8. */
  9. var fclone = require('fclone');
  10. var fs = require('fs');
  11. var cst = require('../constants.js');
  12. var waterfall = require('async/waterfall');
  13. var util = require('util');
  14. var url = require('url');
  15. var dayjs = require('dayjs');
  16. var findPackageJson = require('./tools/find-package-json')
  17. var Utility = module.exports = {
  18. findPackageVersion : function(fullpath) {
  19. var version
  20. try {
  21. version = findPackageJson(fullpath).next().value.version
  22. } catch(e) {
  23. version = 'N/A'
  24. }
  25. return version
  26. },
  27. getDate : function() {
  28. return Date.now();
  29. },
  30. extendExtraConfig : function(proc, opts) {
  31. if (opts.env && opts.env.current_conf) {
  32. if (opts.env.current_conf.env &&
  33. typeof(opts.env.current_conf.env) === 'object' &&
  34. Object.keys(opts.env.current_conf.env).length === 0)
  35. delete opts.env.current_conf.env
  36. Utility.extendMix(proc.pm2_env, opts.env.current_conf);
  37. delete opts.env.current_conf;
  38. }
  39. },
  40. formatCLU : function(process) {
  41. if (!process.pm2_env) {
  42. return process;
  43. }
  44. var obj = Utility.clone(process.pm2_env);
  45. delete obj.env;
  46. return obj;
  47. },
  48. extend : function(destination, source){
  49. if (!source || typeof source != 'object') return destination;
  50. Object.keys(source).forEach(function(new_key) {
  51. if (source[new_key] != '[object Object]')
  52. destination[new_key] = source[new_key];
  53. });
  54. return destination;
  55. },
  56. // Same as extend but drop value with 'null'
  57. extendMix : function(destination, source){
  58. if (!source || typeof source != 'object') return destination;
  59. Object.keys(source).forEach(function(new_key) {
  60. if (source[new_key] == 'null')
  61. delete destination[new_key];
  62. else
  63. destination[new_key] = source[new_key]
  64. });
  65. return destination;
  66. },
  67. whichFileExists : function(file_arr) {
  68. var f = null;
  69. file_arr.some(function(file) {
  70. try {
  71. fs.statSync(file);
  72. } catch(e) {
  73. return false;
  74. }
  75. f = file;
  76. return true;
  77. });
  78. return f;
  79. },
  80. clone : function(obj) {
  81. if (obj === null || obj === undefined) return {};
  82. return fclone(obj);
  83. },
  84. overrideConsole : function(bus) {
  85. if (cst.PM2_LOG_DATE_FORMAT && typeof cst.PM2_LOG_DATE_FORMAT == 'string') {
  86. // Generate timestamp prefix
  87. function timestamp(){
  88. return `${dayjs(Date.now()).format(cst.PM2_LOG_DATE_FORMAT)}:`;
  89. }
  90. var hacks = ['info', 'log', 'error', 'warn'], consoled = {};
  91. // store console functions.
  92. hacks.forEach(function(method){
  93. consoled[method] = console[method];
  94. });
  95. hacks.forEach(function(k){
  96. console[k] = function(){
  97. if (bus) {
  98. bus.emit('log:PM2', {
  99. process : {
  100. pm_id : 'PM2',
  101. name : 'PM2',
  102. rev : null
  103. },
  104. at : Utility.getDate(),
  105. data : util.format.apply(this, arguments) + '\n'
  106. });
  107. }
  108. // do not destroy variable insertion
  109. arguments[0] && (arguments[0] = timestamp() + ' PM2 ' + k + ': ' + arguments[0]);
  110. consoled[k].apply(console, arguments);
  111. };
  112. });
  113. }
  114. },
  115. startLogging : function(stds, callback) {
  116. /**
  117. * Start log outgoing messages
  118. * @method startLogging
  119. * @param {} callback
  120. * @return
  121. */
  122. // Make sure directories of `logs` and `pids` exist.
  123. // try {
  124. // ['logs', 'pids'].forEach(function(n){
  125. // console.log(n);
  126. // (function(_path){
  127. // !fs.existsSync(_path) && fs.mkdirSync(_path, '0755');
  128. // })(path.resolve(cst.PM2_ROOT_PATH, n));
  129. // });
  130. // } catch(err) {
  131. // return callback(new Error('can not create directories (logs/pids):' + err.message));
  132. // }
  133. // waterfall.
  134. var flows = [];
  135. // types of stdio, should be sorted as `std(entire log)`, `out`, `err`.
  136. var types = Object.keys(stds).sort(function(x, y){
  137. return -x.charCodeAt(0) + y.charCodeAt(0);
  138. });
  139. // Create write streams.
  140. (function createWS(io){
  141. if(io.length != 1){
  142. return false;
  143. }
  144. io = io[0];
  145. // If `std` is a Stream type, try next `std`.
  146. // compatible with `pm2 reloadLogs`
  147. if(typeof stds[io] == 'object' && !isNaN(stds[io].fd)){
  148. return createWS(types.splice(0, 1));
  149. }
  150. flows.push(function(next){
  151. var file = stds[io];
  152. // if file contains ERR or /dev/null, dont try to create stream since he dont want logs
  153. if (!file || file.indexOf('NULL') > -1 || file.indexOf('/dev/null') > -1)
  154. return next();
  155. stds[io] = fs.createWriteStream(file, {flags: 'a'})
  156. .once('error', next)
  157. .on('open', function(){
  158. stds[io].removeListener('error', next);
  159. stds[io].on('error', function(err) {
  160. console.error(err);
  161. });
  162. next();
  163. });
  164. stds[io]._file = file;
  165. });
  166. return createWS(types.splice(0, 1));
  167. })(types.splice(0, 1));
  168. waterfall(flows, callback);
  169. },
  170. /**
  171. * Function parse the module name and returns it as canonic:
  172. * - Makes the name based on installation filename.
  173. * - Removes the Github author, module version and git branch from original name.
  174. *
  175. * @param {string} module_name
  176. * @returns {string} Canonic module name (without trimed parts).
  177. * @example Always returns 'pm2-slack' for inputs 'ma-zal/pm2-slack', 'ma-zal/pm2-slack#own-branch',
  178. * 'pm2-slack-1.0.0.tgz' or 'pm2-slack@1.0.0'.
  179. */
  180. getCanonicModuleName: function(module_name) {
  181. if (typeof module_name !== 'string') return null;
  182. var canonic_module_name = module_name;
  183. // Returns the module name from a .tgz package name (or the original name if it is not a valid pkg).
  184. // Input: The package name (e.g. "foo.tgz", "foo-1.0.0.tgz", "folder/foo.tgz")
  185. // Output: The module name
  186. if (canonic_module_name.match(/\.tgz($|\?)/)) {
  187. if (canonic_module_name.match(/^(.+\/)?([^\/]+)\.tgz($|\?)/)) {
  188. canonic_module_name = canonic_module_name.match(/^(.+\/)?([^\/]+)\.tgz($|\?)/)[2];
  189. if (canonic_module_name.match(/^(.+)-[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9_]+\.[0-9]+)?$/)) {
  190. canonic_module_name = canonic_module_name.match(/^(.+)-[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9_]+\.[0-9]+)?$/)[1];
  191. }
  192. }
  193. }
  194. //pm2 install git+https://github.com/user/module
  195. if(canonic_module_name.indexOf('git+') !== -1) {
  196. canonic_module_name = canonic_module_name.split('/').pop();
  197. }
  198. //pm2 install https://github.com/user/module
  199. if(canonic_module_name.indexOf('http') !== -1) {
  200. var uri = url.parse(canonic_module_name);
  201. canonic_module_name = uri.pathname.split('/').pop();
  202. }
  203. //pm2 install file:///home/user/module
  204. else if(canonic_module_name.indexOf('file://') === 0) {
  205. canonic_module_name = canonic_module_name.replace(/\/$/, '').split('/').pop();
  206. }
  207. //pm2 install username/module
  208. else if(canonic_module_name.indexOf('/') !== -1) {
  209. if (canonic_module_name.charAt(0) !== "@"){
  210. canonic_module_name = canonic_module_name.split('/')[1];
  211. }
  212. }
  213. //pm2 install @somescope/module@2.1.0-beta
  214. if(canonic_module_name.lastIndexOf('@') > 0) {
  215. canonic_module_name = canonic_module_name.substr(0,canonic_module_name.lastIndexOf("@"));
  216. }
  217. //pm2 install module#some-branch
  218. if(canonic_module_name.indexOf('#') !== -1) {
  219. canonic_module_name = canonic_module_name.split('#')[0];
  220. }
  221. if (canonic_module_name.indexOf('.git') !== -1) {
  222. canonic_module_name = canonic_module_name.replace('.git', '');
  223. }
  224. return canonic_module_name;
  225. },
  226. checkPathIsNull: function(path) {
  227. return path === 'NULL' || path === '/dev/null' || path === '\\\\.\\NUL';
  228. },
  229. generateUUID: function () {
  230. var s = [];
  231. var hexDigits = "0123456789abcdef";
  232. for (var i = 0; i < 36; i++) {
  233. s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  234. }
  235. s[14] = "4";
  236. s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
  237. s[8] = s[13] = s[18] = s[23] = "-";
  238. return s.join("");
  239. }
  240. };