@ohos-ports/pm2 0.0.0-stage → 7.1.2-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (267) hide show
  1. package/CHANGELOG.md +2607 -0
  2. package/CONTRIBUTING.md +124 -0
  3. package/GNU-AGPL-3.0.txt +665 -0
  4. package/LICENSE +1 -0
  5. package/README.md +255 -2
  6. package/SECURITY.md +41 -0
  7. package/bin/pm2 +3 -0
  8. package/bin/pm2-dev +3 -0
  9. package/bin/pm2-docker +3 -0
  10. package/bin/pm2-runtime +3 -0
  11. package/bin/pm2.ps1 +3 -0
  12. package/constants.js +113 -0
  13. package/index.js +12 -0
  14. package/lib/API/Configuration.js +212 -0
  15. package/lib/API/Containerizer.js +335 -0
  16. package/lib/API/Dashboard.js +726 -0
  17. package/lib/API/Deploy.js +117 -0
  18. package/lib/API/Extra.js +798 -0
  19. package/lib/API/ExtraMgmt/Docker.js +30 -0
  20. package/lib/API/Log.js +388 -0
  21. package/lib/API/LogManagement.js +351 -0
  22. package/lib/API/Modules/LOCAL.js +122 -0
  23. package/lib/API/Modules/Modularizer.js +148 -0
  24. package/lib/API/Modules/NPM.js +443 -0
  25. package/lib/API/Modules/TAR.js +368 -0
  26. package/lib/API/Modules/flagExt.js +46 -0
  27. package/lib/API/Modules/index.js +120 -0
  28. package/lib/API/Monit.js +247 -0
  29. package/lib/API/Serve.js +497 -0
  30. package/lib/API/Startup.js +630 -0
  31. package/lib/API/UX/helpers.js +213 -0
  32. package/lib/API/UX/index.js +9 -0
  33. package/lib/API/UX/pm2-describe.js +197 -0
  34. package/lib/API/UX/pm2-ls-minimal.js +31 -0
  35. package/lib/API/UX/pm2-ls.js +581 -0
  36. package/lib/API/Version.js +383 -0
  37. package/lib/API/interpreter.json +12 -0
  38. package/lib/API/pm2-plus/PM2IO.js +381 -0
  39. package/lib/API/pm2-plus/auth-strategies/CliAuth.js +306 -0
  40. package/lib/API/pm2-plus/auth-strategies/WebAuth.js +195 -0
  41. package/lib/API/pm2-plus/helpers.js +97 -0
  42. package/lib/API/pm2-plus/link.js +126 -0
  43. package/lib/API/pm2-plus/pres/motd +16 -0
  44. package/lib/API/pm2-plus/pres/motd.update +26 -0
  45. package/lib/API/pm2-plus/pres/welcome +28 -0
  46. package/lib/API/pm2-plus/process-selector.js +52 -0
  47. package/lib/API/schema.json +375 -0
  48. package/lib/API.js +1980 -0
  49. package/lib/Client.js +793 -0
  50. package/lib/Common.js +949 -0
  51. package/lib/Configuration.js +309 -0
  52. package/lib/Daemon.js +468 -0
  53. package/lib/Event.js +37 -0
  54. package/lib/God/ActionMethods.js +955 -0
  55. package/lib/God/ClusterMode.js +192 -0
  56. package/lib/God/ForkMode.js +205 -0
  57. package/lib/God/Methods.js +292 -0
  58. package/lib/God/Reload.js +300 -0
  59. package/lib/God/StdioLogger.js +239 -0
  60. package/lib/God.js +653 -0
  61. package/lib/HttpInterface.js +75 -0
  62. package/lib/OtelManager.js +74 -0
  63. package/lib/ProcessContainer.js +321 -0
  64. package/lib/ProcessContainerBun.js +355 -0
  65. package/lib/ProcessContainerFork.js +42 -0
  66. package/lib/ProcessContainerForkBun.js +31 -0
  67. package/lib/ProcessUtils.js +74 -0
  68. package/lib/TreeKill.js +111 -0
  69. package/lib/Utility.js +304 -0
  70. package/lib/VersionCheck.js +46 -0
  71. package/lib/Watcher.js +117 -0
  72. package/lib/Worker.js +200 -0
  73. package/lib/binaries/CLI.js +1092 -0
  74. package/lib/binaries/DevCLI.js +183 -0
  75. package/lib/binaries/Runtime.js +101 -0
  76. package/lib/binaries/Runtime4Docker.js +192 -0
  77. package/lib/completion.js +229 -0
  78. package/lib/completion.sh +40 -0
  79. package/lib/motd +36 -0
  80. package/lib/templates/Dockerfiles/Dockerfile-nodejs.tpl +8 -0
  81. package/lib/templates/ecosystem-es.tpl +24 -0
  82. package/lib/templates/ecosystem-simple-es.tpl +8 -0
  83. package/lib/templates/ecosystem-simple.tpl +6 -0
  84. package/lib/templates/ecosystem.tpl +22 -0
  85. package/lib/templates/init-scripts/launchd.tpl +35 -0
  86. package/lib/templates/init-scripts/openrc.tpl +52 -0
  87. package/lib/templates/init-scripts/pm2-init-amazon.sh +86 -0
  88. package/lib/templates/init-scripts/rcd-openbsd.tpl +41 -0
  89. package/lib/templates/init-scripts/rcd.tpl +44 -0
  90. package/lib/templates/init-scripts/smf.tpl +43 -0
  91. package/lib/templates/init-scripts/systemd-online.tpl +22 -0
  92. package/lib/templates/init-scripts/systemd.tpl +22 -0
  93. package/lib/templates/init-scripts/upstart.tpl +103 -0
  94. package/lib/templates/logrotate.d/pm2 +10 -0
  95. package/lib/templates/sample-apps/http-server/README.md +14 -0
  96. package/lib/templates/sample-apps/http-server/api.js +9 -0
  97. package/lib/templates/sample-apps/http-server/ecosystem.config.js +14 -0
  98. package/lib/templates/sample-apps/http-server/package.json +11 -0
  99. package/lib/templates/sample-apps/pm2-plus-metrics-actions/README.md +45 -0
  100. package/lib/templates/sample-apps/pm2-plus-metrics-actions/custom-metrics.js +66 -0
  101. package/lib/templates/sample-apps/pm2-plus-metrics-actions/ecosystem.config.js +12 -0
  102. package/lib/templates/sample-apps/pm2-plus-metrics-actions/package.json +11 -0
  103. package/lib/templates/sample-apps/python-app/README.md +4 -0
  104. package/lib/templates/sample-apps/python-app/echo.py +7 -0
  105. package/lib/templates/sample-apps/python-app/ecosystem.config.js +12 -0
  106. package/lib/templates/sample-apps/python-app/package.json +11 -0
  107. package/lib/tools/Config.js +251 -0
  108. package/lib/tools/SysMetrics.js +375 -0
  109. package/lib/tools/copydirSync.js +101 -0
  110. package/lib/tools/deleteFolderRecursive.js +19 -0
  111. package/lib/tools/find-package-json.js +74 -0
  112. package/lib/tools/fmt.js +72 -0
  113. package/lib/tools/interpreter.js +88 -0
  114. package/lib/tools/isbinaryfile.js +94 -0
  115. package/lib/tools/json5.js +752 -0
  116. package/lib/tools/multimeter/bar.js +111 -0
  117. package/lib/tools/multimeter/charm/encode.js +18 -0
  118. package/lib/tools/multimeter/charm/index.js +305 -0
  119. package/lib/tools/multimeter/index.js +76 -0
  120. package/lib/tools/open.js +56 -0
  121. package/lib/tools/passwd.js +58 -0
  122. package/lib/tools/pm2-config-keys.js +165 -0
  123. package/lib/tools/prompt.js +76 -0
  124. package/lib/tools/serviceStop.js +149 -0
  125. package/lib/tools/sexec.js +55 -0
  126. package/lib/tools/treeify.js +113 -0
  127. package/lib/tools/typestrip.js +55 -0
  128. package/lib/tools/which.js +120 -0
  129. package/lib/tools/xdg-open +861 -0
  130. package/modules/blessed/LICENSE +20 -0
  131. package/modules/blessed/README.md +34 -0
  132. package/modules/blessed/index.js +1 -0
  133. package/modules/blessed/lib/alias.js +526 -0
  134. package/modules/blessed/lib/blessed.js +32 -0
  135. package/modules/blessed/lib/colors.js +530 -0
  136. package/modules/blessed/lib/events.js +189 -0
  137. package/modules/blessed/lib/gpmclient.js +221 -0
  138. package/modules/blessed/lib/helpers.js +165 -0
  139. package/modules/blessed/lib/keys.js +339 -0
  140. package/modules/blessed/lib/program.js +4297 -0
  141. package/modules/blessed/lib/tput.js +3022 -0
  142. package/modules/blessed/lib/unicode.js +885 -0
  143. package/modules/blessed/lib/widget.js +32 -0
  144. package/modules/blessed/lib/widgets/box.js +34 -0
  145. package/modules/blessed/lib/widgets/element.js +2570 -0
  146. package/modules/blessed/lib/widgets/list.js +599 -0
  147. package/modules/blessed/lib/widgets/log.js +83 -0
  148. package/modules/blessed/lib/widgets/node.js +282 -0
  149. package/modules/blessed/lib/widgets/screen.js +2298 -0
  150. package/modules/blessed/lib/widgets/scrollablebox.js +389 -0
  151. package/modules/blessed/lib/widgets/scrollabletext.js +35 -0
  152. package/modules/blessed/lib/widgets/text.js +35 -0
  153. package/modules/blessed/usr/linux +0 -0
  154. package/modules/blessed/usr/windows-ansi +0 -0
  155. package/modules/blessed/usr/xterm +0 -0
  156. package/modules/blessed/usr/xterm-256color +0 -0
  157. package/modules/blessed/usr/xterm.termcap +243 -0
  158. package/modules/chokidar/LICENSE +21 -0
  159. package/modules/chokidar/VENDORED.md +76 -0
  160. package/modules/chokidar/index.js +979 -0
  161. package/modules/chokidar/lib/brace-expand.js +180 -0
  162. package/modules/chokidar/lib/constants.js +66 -0
  163. package/modules/chokidar/lib/fsevents-handler.js +526 -0
  164. package/modules/chokidar/lib/nodefs-handler.js +654 -0
  165. package/modules/fclone.js +49 -0
  166. package/modules/pm2-axon/index.js +2 -0
  167. package/modules/pm2-axon/lib/configurable/History.md +5 -0
  168. package/modules/pm2-axon/lib/configurable/Makefile +7 -0
  169. package/modules/pm2-axon/lib/configurable/Readme.md +57 -0
  170. package/modules/pm2-axon/lib/configurable/index.js +2 -0
  171. package/modules/pm2-axon/lib/configurable/lib/configurable.js +47 -0
  172. package/modules/pm2-axon/lib/configurable/package.json +68 -0
  173. package/modules/pm2-axon/lib/index.js +44 -0
  174. package/modules/pm2-axon/lib/plugins/queue.js +71 -0
  175. package/modules/pm2-axon/lib/plugins/round-robin.js +55 -0
  176. package/modules/pm2-axon/lib/sockets/pub-emitter.js +26 -0
  177. package/modules/pm2-axon/lib/sockets/pub.js +77 -0
  178. package/modules/pm2-axon/lib/sockets/pull.js +37 -0
  179. package/modules/pm2-axon/lib/sockets/push.js +32 -0
  180. package/modules/pm2-axon/lib/sockets/rep.js +73 -0
  181. package/modules/pm2-axon/lib/sockets/req.js +101 -0
  182. package/modules/pm2-axon/lib/sockets/sock.js +430 -0
  183. package/modules/pm2-axon/lib/sockets/sub-emitter.js +92 -0
  184. package/modules/pm2-axon/lib/sockets/sub.js +147 -0
  185. package/modules/pm2-axon/lib/utils.js +19 -0
  186. package/modules/pm2-axon-rpc/index.js +3 -0
  187. package/modules/pm2-axon-rpc/lib/client.js +63 -0
  188. package/modules/pm2-axon-rpc/lib/server.js +139 -0
  189. package/modules/pm2-io-agent/LICENSE +661 -0
  190. package/modules/pm2-io-agent/README.md +62 -0
  191. package/modules/pm2-io-agent/config.js +30 -0
  192. package/modules/pm2-io-agent/constants.js +118 -0
  193. package/modules/pm2-io-agent/index.js +2 -0
  194. package/modules/pm2-io-agent/src/InteractorClient.js +513 -0
  195. package/modules/pm2-io-agent/src/InteractorDaemon.js +455 -0
  196. package/modules/pm2-io-agent/src/PM2Client.js +112 -0
  197. package/modules/pm2-io-agent/src/PM2Interface.js +180 -0
  198. package/modules/pm2-io-agent/src/TransporterInterface.js +173 -0
  199. package/modules/pm2-io-agent/src/Utility.js +392 -0
  200. package/modules/pm2-io-agent/src/WatchDog.js +70 -0
  201. package/modules/pm2-io-agent/src/push/DataRetriever.js +77 -0
  202. package/modules/pm2-io-agent/src/push/PushInteractor.js +206 -0
  203. package/modules/pm2-io-agent/src/push/TransactionAggregator.js +670 -0
  204. package/modules/pm2-io-agent/src/reverse/ReverseInteractor.js +128 -0
  205. package/modules/pm2-io-agent/src/transporters/Transporter.js +129 -0
  206. package/modules/pm2-io-agent/src/transporters/WebsocketTransport.js +202 -0
  207. package/modules/pm2-io-agent/src/utils/BinaryHeap.js +135 -0
  208. package/modules/pm2-io-agent/src/utils/EDS.js +111 -0
  209. package/modules/pm2-io-agent/src/utils/probes/Histogram.js +204 -0
  210. package/modules/pm2-io-agent/src/utils/units.js +10 -0
  211. package/modules/pm2-io-bpm/configuration.js +141 -0
  212. package/modules/pm2-io-bpm/constants.js +10 -0
  213. package/modules/pm2-io-bpm/featureManager.js +110 -0
  214. package/modules/pm2-io-bpm/features/dependencies.js +48 -0
  215. package/modules/pm2-io-bpm/features/events.js +50 -0
  216. package/modules/pm2-io-bpm/features/metrics.js +102 -0
  217. package/modules/pm2-io-bpm/features/notify.js +238 -0
  218. package/modules/pm2-io-bpm/features/profiling.js +70 -0
  219. package/modules/pm2-io-bpm/features/tracing.js +174 -0
  220. package/modules/pm2-io-bpm/index.js +11 -0
  221. package/modules/pm2-io-bpm/metrics/eventLoopMetrics.js +136 -0
  222. package/modules/pm2-io-bpm/metrics/httpMetrics.js +175 -0
  223. package/modules/pm2-io-bpm/metrics/network.js +132 -0
  224. package/modules/pm2-io-bpm/metrics/runtime.js +161 -0
  225. package/modules/pm2-io-bpm/metrics/v8.js +104 -0
  226. package/modules/pm2-io-bpm/otel/constants.js +7 -0
  227. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/platform/index.js +17 -0
  228. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/platform/node/index.js +17 -0
  229. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/platform/node/util.js +51 -0
  230. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/transform.js +137 -0
  231. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/types.js +24 -0
  232. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/utils.js +23 -0
  233. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/zipkin.js +149 -0
  234. package/modules/pm2-io-bpm/pmx.js +380 -0
  235. package/modules/pm2-io-bpm/profilers/addonProfiler.js +193 -0
  236. package/modules/pm2-io-bpm/profilers/inspectorProfiler.js +302 -0
  237. package/modules/pm2-io-bpm/serviceManager.js +21 -0
  238. package/modules/pm2-io-bpm/services/actions.js +159 -0
  239. package/modules/pm2-io-bpm/services/inspector.js +43 -0
  240. package/modules/pm2-io-bpm/services/metrics.js +186 -0
  241. package/modules/pm2-io-bpm/services/runtimeStats.js +54 -0
  242. package/modules/pm2-io-bpm/services/transport.js +11 -0
  243. package/modules/pm2-io-bpm/transports/IPCTransport.js +115 -0
  244. package/modules/pm2-io-bpm/utils/BinaryHeap.js +134 -0
  245. package/modules/pm2-io-bpm/utils/EDS.js +113 -0
  246. package/modules/pm2-io-bpm/utils/EWMA.js +32 -0
  247. package/modules/pm2-io-bpm/utils/autocast.js +61 -0
  248. package/modules/pm2-io-bpm/utils/metrics/counter.js +33 -0
  249. package/modules/pm2-io-bpm/utils/metrics/gauge.js +23 -0
  250. package/modules/pm2-io-bpm/utils/metrics/histogram.js +192 -0
  251. package/modules/pm2-io-bpm/utils/metrics/meter.js +46 -0
  252. package/modules/pm2-io-bpm/utils/miscellaneous.js +19 -0
  253. package/modules/pm2-io-bpm/utils/module.js +67 -0
  254. package/modules/pm2-io-bpm/utils/shimmer.js +19 -0
  255. package/modules/pm2-io-bpm/utils/stackParser.js +160 -0
  256. package/modules/pm2-io-bpm/utils/transactionAggregator.js +429 -0
  257. package/modules/pm2-io-bpm/utils/units.js +16 -0
  258. package/modules/vizion/LICENSE +13 -0
  259. package/modules/vizion/README.md +133 -0
  260. package/modules/vizion/index.js +1 -0
  261. package/modules/vizion/lib/git/git.js +247 -0
  262. package/modules/vizion/lib/vizion.js +52 -0
  263. package/package.json +170 -4
  264. package/paths.js +121 -0
  265. package/pm2 +11 -0
  266. package/types/index.d.ts +732 -0
  267. package/types/tsconfig.json +14 -0
package/lib/Utility.js ADDED
@@ -0,0 +1,304 @@
1
+ /**
2
+ * Copyright 2013-present 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
+ /**
8
+ * Common Utilities ONLY USED IN ->DAEMON<-
9
+ */
10
+
11
+ var fclone = require('../modules/fclone');
12
+ var fs = require('fs');
13
+ var cst = require('../constants.js');
14
+ var waterfall = require('async/waterfall');
15
+ var util = require('util');
16
+ var dayjs = require('dayjs');
17
+ var findPackageJson = require('./tools/find-package-json')
18
+ var pm2Keys = require('./tools/pm2-config-keys.js');
19
+
20
+ var Utility = module.exports = {
21
+ isPm2ConfigKey : pm2Keys.isPm2ConfigKey,
22
+ isPm2InternalKey : pm2Keys.isPm2InternalKey,
23
+ /**
24
+ * Flatten pm2_env.env into pm2_env (so it is exported to the child process).
25
+ *
26
+ * Shell variables named like a PM2 option are already stripped upstream, by
27
+ * Common.prepareAppConf and by the --update-env merge in API.js: whatever is
28
+ * left in `env` at this point the user asked for, so `env: { port: 3000 }`
29
+ * has to land in the child. Only the daemon's own bookkeeping is off limits.
30
+ */
31
+ extendEnv : function(destination, env) {
32
+ if (!env || typeof env != 'object') return destination;
33
+
34
+ Object.keys(env).forEach(function(key) {
35
+ if (pm2Keys.isPm2InternalKey(key)) return;
36
+ if (env[key] != '[object Object]')
37
+ destination[key] = env[key];
38
+ });
39
+
40
+ return destination;
41
+ },
42
+ findPackageVersion : function(fullpath) {
43
+ var version
44
+
45
+ try {
46
+ version = findPackageJson(fullpath).next().value.version
47
+ } catch(e) {
48
+ version = 'N/A'
49
+ }
50
+ return version
51
+ },
52
+ getDate : function() {
53
+ return Date.now();
54
+ },
55
+ extendExtraConfig : function(proc, opts) {
56
+ if (opts.env && opts.env.current_conf) {
57
+ if (opts.env.current_conf.env &&
58
+ typeof(opts.env.current_conf.env) === 'object' &&
59
+ Object.keys(opts.env.current_conf.env).length === 0)
60
+ delete opts.env.current_conf.env
61
+
62
+ Utility.extendMix(proc.pm2_env, opts.env.current_conf);
63
+ delete opts.env.current_conf;
64
+ }
65
+ },
66
+ formatCLU : function(process) {
67
+ if (!process.pm2_env) {
68
+ return process;
69
+ }
70
+
71
+ var obj = Utility.clone(process.pm2_env);
72
+ delete obj.env;
73
+
74
+ return obj;
75
+ },
76
+ extend : function(destination, source){
77
+ if (!source || typeof source != 'object') return destination;
78
+
79
+ Object.keys(source).forEach(function(new_key) {
80
+ if (source[new_key] != '[object Object]')
81
+ destination[new_key] = source[new_key];
82
+ });
83
+
84
+ return destination;
85
+ },
86
+ // Same as extend but drop value with 'null'
87
+ extendMix : function(destination, source){
88
+ if (!source || typeof source != 'object') return destination;
89
+
90
+ Object.keys(source).forEach(function(new_key) {
91
+ if (source[new_key] == 'null')
92
+ delete destination[new_key];
93
+ else
94
+ destination[new_key] = source[new_key]
95
+ });
96
+
97
+ return destination;
98
+ },
99
+
100
+ whichFileExists : function(file_arr) {
101
+ var f = null;
102
+
103
+ file_arr.some(function(file) {
104
+ try {
105
+ fs.statSync(file);
106
+ } catch(e) {
107
+ return false;
108
+ }
109
+ f = file;
110
+ return true;
111
+ });
112
+ return f;
113
+ },
114
+ clone : function(obj) {
115
+ if (obj === null || obj === undefined) return {};
116
+ return fclone(obj);
117
+ },
118
+ overrideConsole : function(bus) {
119
+ if (cst.PM2_LOG_DATE_FORMAT && typeof cst.PM2_LOG_DATE_FORMAT == 'string') {
120
+ // Generate timestamp prefix
121
+ function timestamp(){
122
+ return `${dayjs(Date.now()).format(cst.PM2_LOG_DATE_FORMAT)}:`;
123
+ }
124
+
125
+ var hacks = ['info', 'log', 'error', 'warn'], consoled = {};
126
+
127
+ // store console functions.
128
+ hacks.forEach(function(method){
129
+ consoled[method] = console[method];
130
+ });
131
+
132
+ hacks.forEach(function(k){
133
+ console[k] = function(){
134
+ if (bus) {
135
+ bus.emit('log:PM2', {
136
+ process : {
137
+ pm_id : 'PM2',
138
+ name : 'PM2',
139
+ rev : null
140
+ },
141
+ at : Utility.getDate(),
142
+ data : util.format.apply(this, arguments) + '\n'
143
+ });
144
+ }
145
+ // do not destroy variable insertion
146
+ arguments[0] && (arguments[0] = timestamp() + ' PM2 ' + k + ': ' + arguments[0]);
147
+ consoled[k].apply(console, arguments);
148
+ };
149
+ });
150
+ }
151
+ },
152
+ startLogging : function(stds, callback) {
153
+ /**
154
+ * Start log outgoing messages
155
+ * @method startLogging
156
+ * @param {} callback
157
+ * @return
158
+ */
159
+ // Make sure directories of `logs` and `pids` exist.
160
+ // try {
161
+ // ['logs', 'pids'].forEach(function(n){
162
+ // console.log(n);
163
+ // (function(_path){
164
+ // !fs.existsSync(_path) && fs.mkdirSync(_path, '0755');
165
+ // })(path.resolve(cst.PM2_ROOT_PATH, n));
166
+ // });
167
+ // } catch(err) {
168
+ // return callback(new Error('can not create directories (logs/pids):' + err.message));
169
+ // }
170
+
171
+ // waterfall.
172
+ var flows = [];
173
+ // types of stdio, should be sorted as `std(entire log)`, `out`, `err`.
174
+ var types = Object.keys(stds).sort(function(x, y){
175
+ return -x.charCodeAt(0) + y.charCodeAt(0);
176
+ });
177
+
178
+ // Create write streams.
179
+ (function createWS(io){
180
+ if(io.length != 1){
181
+ return false;
182
+ }
183
+ io = io[0];
184
+
185
+ // If `std` is a Stream type, try next `std`.
186
+ // compatible with `pm2 reloadLogs`
187
+ if(typeof stds[io] == 'object' && !isNaN(stds[io].fd)){
188
+ return createWS(types.splice(0, 1));
189
+ }
190
+
191
+ flows.push(function(next){
192
+ var file = stds[io];
193
+
194
+ // Already reopened by a concurrent call (pm2 reloadLogs x2):
195
+ // keep its stream (crashed with file.indexOf is not a function)
196
+ if (file && typeof file !== 'string')
197
+ return next();
198
+
199
+ // if file contains ERR or /dev/null, dont try to create stream since he dont want logs
200
+ if (!file || file.indexOf('NULL') > -1 || file.indexOf('/dev/null') > -1)
201
+ return next();
202
+
203
+ stds[io] = fs.createWriteStream(file, {flags: 'a'})
204
+ .once('error', next)
205
+ .on('open', function(){
206
+ stds[io].removeListener('error', next);
207
+
208
+ stds[io].on('error', function(err) {
209
+ console.error(err);
210
+ });
211
+
212
+ next();
213
+ });
214
+ stds[io]._file = file;
215
+ });
216
+ return createWS(types.splice(0, 1));
217
+ })(types.splice(0, 1));
218
+
219
+ waterfall(flows, callback);
220
+ },
221
+
222
+ /**
223
+ * Function parse the module name and returns it as canonic:
224
+ * - Makes the name based on installation filename.
225
+ * - Removes the Github author, module version and git branch from original name.
226
+ *
227
+ * @param {string} module_name
228
+ * @returns {string} Canonic module name (without trimed parts).
229
+ * @example Always returns 'pm2-slack' for inputs 'ma-zal/pm2-slack', 'ma-zal/pm2-slack#own-branch',
230
+ * 'pm2-slack-1.0.0.tgz' or 'pm2-slack@1.0.0'.
231
+ */
232
+ getCanonicModuleName: function(module_name) {
233
+ if (typeof module_name !== 'string') return null;
234
+ var canonic_module_name = module_name;
235
+
236
+ // Returns the module name from a .tgz package name (or the original name if it is not a valid pkg).
237
+ // Input: The package name (e.g. "foo.tgz", "foo-1.0.0.tgz", "folder/foo.tgz")
238
+ // Output: The module name
239
+ if (canonic_module_name.match(/\.tgz($|\?)/)) {
240
+ if (canonic_module_name.match(/^(.+\/)?([^\/]+)\.tgz($|\?)/)) {
241
+ canonic_module_name = canonic_module_name.match(/^(.+\/)?([^\/]+)\.tgz($|\?)/)[2];
242
+ if (canonic_module_name.match(/^(.+)-[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9_]+\.[0-9]+)?$/)) {
243
+ canonic_module_name = canonic_module_name.match(/^(.+)-[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9_]+\.[0-9]+)?$/)[1];
244
+ }
245
+ }
246
+ }
247
+
248
+ //pm2 install git+https://github.com/user/module
249
+ if(canonic_module_name.indexOf('git+') !== -1) {
250
+ canonic_module_name = canonic_module_name.split('/').pop();
251
+ }
252
+
253
+ //pm2 install https://github.com/user/module
254
+ if(canonic_module_name.indexOf('http://') !== -1 || canonic_module_name.indexOf('https://') !== -1) {
255
+ var uri = new URL(canonic_module_name);
256
+ canonic_module_name = uri.pathname.split('/').pop();
257
+ }
258
+
259
+ //pm2 install file:///home/user/module
260
+ else if(canonic_module_name.indexOf('file://') === 0) {
261
+ canonic_module_name = canonic_module_name.replace(/\/$/, '').split('/').pop();
262
+ }
263
+
264
+ //pm2 install username/module
265
+ else if(canonic_module_name.indexOf('/') !== -1) {
266
+ if (canonic_module_name.charAt(0) !== "@"){
267
+ canonic_module_name = canonic_module_name.split('/')[1];
268
+ }
269
+ }
270
+
271
+ //pm2 install @somescope/module@2.1.0-beta
272
+ if(canonic_module_name.lastIndexOf('@') > 0) {
273
+ canonic_module_name = canonic_module_name.substr(0,canonic_module_name.lastIndexOf("@"));
274
+ }
275
+
276
+ //pm2 install module#some-branch
277
+ if(canonic_module_name.indexOf('#') !== -1) {
278
+ canonic_module_name = canonic_module_name.split('#')[0];
279
+ }
280
+
281
+ if (canonic_module_name.indexOf('.git') !== -1) {
282
+ canonic_module_name = canonic_module_name.replace('.git', '');
283
+ }
284
+
285
+ return canonic_module_name;
286
+ },
287
+
288
+ checkPathIsNull: function(path) {
289
+ return path === 'NULL' || path === '/dev/null' || path === '\\\\.\\NUL';
290
+ },
291
+
292
+ generateUUID: function () {
293
+ var s = [];
294
+ var hexDigits = "0123456789abcdef";
295
+ for (var i = 0; i < 36; i++) {
296
+ s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
297
+ }
298
+ s[14] = "4";
299
+ s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
300
+ s[8] = s[13] = s[18] = s[23] = "-";
301
+ return s.join("");
302
+ }
303
+
304
+ };
@@ -0,0 +1,46 @@
1
+
2
+ var vCheck = require('@pm2/pm2-version-check')
3
+ var semver = require('semver')
4
+ var fs = require('fs')
5
+ var os = require('os')
6
+
7
+ function hasDockerEnv() {
8
+ try {
9
+ fs.statSync('/.dockerenv');
10
+ return true;
11
+ } catch (_) {
12
+ return false;
13
+ }
14
+ }
15
+
16
+ function hasDockerCGroup() {
17
+ try {
18
+ return fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
19
+ } catch (_) {
20
+ return false;
21
+ }
22
+ }
23
+
24
+ module.exports = function (opts) {
25
+ var params = {
26
+ state: opts.state,
27
+ version: opts.version
28
+ }
29
+
30
+ try {
31
+ params.os = os.type()
32
+ params.uptime = Math.floor(process.uptime())
33
+ params.nodev = process.versions.node
34
+ params.docker = hasDockerEnv() || hasDockerCGroup()
35
+ } catch(e) {
36
+ }
37
+
38
+ vCheck.runCheck(params, (err, pkg) => {
39
+ if (err) return false
40
+ if (!pkg.current_version) return false
41
+ if (opts.version && semver.lt(opts.version, pkg.current_version)) {
42
+ console.log('[PM2] This PM2 is not UP TO DATE')
43
+ console.log('[PM2] Upgrade to version %s', pkg.current_version)
44
+ }
45
+ })
46
+ }
package/lib/Watcher.js ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Copyright 2013-present 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 chokidar = require('../modules/chokidar');
7
+ var util = require('util');
8
+ var log = require('debug')('pm2:watch');
9
+
10
+ module.exports = function ClusterMode(God) {
11
+ /**
12
+ * Watch folder for changes and restart
13
+ * @method watch
14
+ * @param {Object} pm2_env pm2 app environnement
15
+ * @return MemberExpression
16
+ */
17
+ God.watch = {};
18
+
19
+ God.watch._watchers = {};
20
+
21
+ God.watch.enable = function(pm2_env) {
22
+ if (God.watch._watchers[pm2_env.pm_id]) {
23
+ God.watch._watchers[pm2_env.pm_id].close();
24
+ God.watch._watchers[pm2_env.pm_id] = null;
25
+ delete God.watch._watchers[pm2_env.pm_id];
26
+ }
27
+
28
+ log('Initial watch ', pm2_env.watch)
29
+
30
+ var watch = pm2_env.watch
31
+
32
+ if(typeof watch == 'boolean' || Array.isArray(watch) && watch.length === 0)
33
+ watch = pm2_env.pm_cwd;
34
+
35
+ log('Watching %s', watch);
36
+
37
+ var watch_options = {
38
+ ignored : pm2_env.ignore_watch || /[\/\\]\.|node_modules/,
39
+ persistent : true,
40
+ ignoreInitial : true,
41
+ cwd: pm2_env.pm_cwd
42
+ };
43
+
44
+ if (pm2_env.watch_options) {
45
+ watch_options = Object.assign(watch_options, pm2_env.watch_options);
46
+ }
47
+
48
+ log('Watch opts', watch_options);
49
+
50
+ var watcher = chokidar.watch(watch, watch_options);
51
+
52
+ console.log('[Watch] Start watching', pm2_env.name);
53
+
54
+ watcher.on('all', function(event, path) {
55
+ var self = this;
56
+
57
+ if (self.restarting === true) {
58
+ log('Already restarting, skipping');
59
+ return false;
60
+ }
61
+
62
+ self.restarting = true;
63
+
64
+ console.log('Change detected on path %s for app %s - restarting', path, pm2_env.name);
65
+
66
+ setTimeout(function() {
67
+ God.restartProcessName(pm2_env.name, function(err, list) {
68
+ self.restarting = false;
69
+
70
+ if (err) {
71
+ log('Error while restarting', err);
72
+ return false;
73
+ }
74
+
75
+ return log('Process restarted');
76
+ });
77
+ }, (pm2_env.watch_delay || 0));
78
+
79
+ return false;
80
+ });
81
+
82
+ watcher.on('error', function(e) {
83
+ console.error(e.stack || e);
84
+ });
85
+
86
+ God.watch._watchers[pm2_env.pm_id] = watcher;
87
+
88
+ //return God.watch._watchers[pm2_env.name];
89
+ },
90
+ /**
91
+ * Description
92
+ * @method close
93
+ * @param {} id
94
+ * @return
95
+ */
96
+ God.watch.disableAll = function() {
97
+ var watchers = God.watch._watchers;
98
+
99
+ console.log('[Watch] PM2 is being killed. Watch is disabled to avoid conflicts');
100
+ for (var i in watchers) {
101
+ watchers[i].close && watchers[i].close();
102
+ watchers.splice(i, 1);
103
+ }
104
+ },
105
+
106
+ God.watch.disable = function(pm2_env) {
107
+ var watcher = God.watch._watchers[pm2_env.pm_id]
108
+ if (watcher) {
109
+ console.log('[Watch] Stop watching', pm2_env.name);
110
+ watcher.close();
111
+ delete God.watch._watchers[pm2_env.pm_id];
112
+ return true;
113
+ } else {
114
+ return false;
115
+ }
116
+ }
117
+ };
package/lib/Worker.js ADDED
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Copyright 2013-present 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
+ const eachLimit = require('async/eachLimit');
7
+ const debug = require('debug')('pm2:worker');
8
+ const domain = require('domain');
9
+ const Cron = require('croner');
10
+ const pkg = require('../package.json');
11
+
12
+ var cst = require('../constants.js');
13
+ var vCheck = require('./VersionCheck.js')
14
+ var Configuration = require('./Configuration.js');
15
+ var SysMetrics = require('./tools/SysMetrics.js');
16
+
17
+ module.exports = function(God) {
18
+ var timer = null;
19
+ var sysMetricsTimer = null;
20
+
21
+ God.CronJobs = new Map();
22
+ God.Worker = {};
23
+ God.Worker.is_running = false;
24
+ God.system_infos = {};
25
+
26
+ /**
27
+ * RPC: expose the latest host metrics snapshot (see SysMetrics.js).
28
+ */
29
+ God.getSystemData = function(env, cb) {
30
+ return cb(null, God.system_infos || {});
31
+ };
32
+
33
+ God.getCronID = function(pm_id) {
34
+ return `cron-${pm_id}`
35
+ }
36
+
37
+ God.registerCron = function(pm2_env) {
38
+ if (!pm2_env ||
39
+ pm2_env.pm_id === undefined ||
40
+ !pm2_env.cron_restart ||
41
+ pm2_env.cron_restart == '0' ||
42
+ God.CronJobs.has(God.getCronID(pm2_env.pm_id)))
43
+ return;
44
+
45
+ var pm_id = pm2_env.pm_id
46
+ console.log('[PM2][WORKER] Registering a cron job on:', pm_id);
47
+
48
+ var job = Cron(pm2_env.cron_restart, function() {
49
+ God.restartProcessId({id: pm_id}, function(err, data) {
50
+ if (err)
51
+ console.error(err.stack || err);
52
+ return;
53
+ });
54
+ });
55
+
56
+ God.CronJobs.set(God.getCronID(pm_id), job);
57
+ }
58
+
59
+
60
+ /**
61
+ * Deletes the cron job on deletion of process
62
+ */
63
+ God.deleteCron = function(id) {
64
+ if (typeof(id) !== 'undefined' && God.CronJobs.has(God.getCronID(id)) === false)
65
+ return;
66
+ console.log('[PM2] Deregistering a cron job on:', id);
67
+ var job = God.CronJobs.get(God.getCronID(id));
68
+
69
+ if (job)
70
+ job.stop();
71
+
72
+ God.CronJobs.delete(God.getCronID(id));
73
+ };
74
+
75
+ var _getProcessById = function(pm_id) {
76
+ var proc = God.clusters_db[pm_id];
77
+ return proc ? proc : null;
78
+ };
79
+
80
+
81
+ var maxMemoryRestart = function(proc_key, cb) {
82
+ var proc = _getProcessById(proc_key.pm2_env.pm_id);
83
+
84
+ if (!(proc &&
85
+ proc.pm2_env &&
86
+ proc_key.monit))
87
+ return cb();
88
+
89
+ if (proc_key.monit.memory !== undefined &&
90
+ proc.pm2_env.max_memory_restart !== undefined &&
91
+ proc.pm2_env.max_memory_restart < proc_key.monit.memory &&
92
+ proc.pm2_env.axm_options &&
93
+ proc.pm2_env.axm_options.pid === undefined) {
94
+ console.log('[PM2][WORKER] Process %s restarted because it exceeds --max-memory-restart value (current_memory=%s max_memory_limit=%s [octets])', proc.pm2_env.pm_id, proc_key.monit.memory, proc.pm2_env.max_memory_restart);
95
+ God.reloadProcessId({
96
+ id : proc.pm2_env.pm_id
97
+ }, function(err, data) {
98
+ if (err)
99
+ console.error(err.stack || err);
100
+ return cb();
101
+ });
102
+ }
103
+ else {
104
+ return cb();
105
+ }
106
+ };
107
+
108
+ var tasks = function() {
109
+ if (God.Worker.is_running === true) {
110
+ debug('[PM2][WORKER] Worker is already running, skipping this round');
111
+ return false;
112
+ }
113
+ God.Worker.is_running = true;
114
+
115
+ God.getMonitorData(null, function(err, data) {
116
+ if (err || !data || typeof(data) !== 'object') {
117
+ God.Worker.is_running = false;
118
+ return console.error(err);
119
+ }
120
+
121
+ eachLimit(data, 1, function(proc, next) {
122
+ if (!proc || !proc.pm2_env || proc.pm2_env.pm_id === undefined)
123
+ return next();
124
+
125
+ debug('[PM2][WORKER] Processing proc id:', proc.pm2_env.pm_id);
126
+
127
+ // Reset restart delay if application has an uptime of more > 30secs
128
+ if (proc.pm2_env.exp_backoff_restart_delay !== undefined &&
129
+ proc.pm2_env.prev_restart_delay && proc.pm2_env.prev_restart_delay > 0) {
130
+ var app_uptime = Date.now() - proc.pm2_env.pm_uptime
131
+ if (app_uptime > cst.EXP_BACKOFF_RESET_TIMER) {
132
+ var ref_proc = _getProcessById(proc.pm2_env.pm_id);
133
+ ref_proc.pm2_env.prev_restart_delay = 0
134
+ console.log(`[PM2][WORKER] Reset the restart delay, as app ${proc.name} has been up for more than ${cst.EXP_BACKOFF_RESET_TIMER}ms`)
135
+ }
136
+ }
137
+
138
+ // Check if application has reached memory threshold
139
+ maxMemoryRestart(proc, function() {
140
+ return next();
141
+ });
142
+ }, function(err) {
143
+ God.Worker.is_running = false;
144
+ debug('[PM2][WORKER] My job here is done, next job in %d seconds', parseInt(cst.WORKER_INTERVAL / 1000));
145
+ });
146
+ });
147
+ };
148
+
149
+ var wrappedTasks = function() {
150
+ var d = domain.create();
151
+
152
+ d.once('error', function(err) {
153
+ console.error('[PM2][WORKER] Error caught by domain:\n' + (err.stack || err));
154
+ God.Worker.is_running = false;
155
+ });
156
+
157
+ d.run(function() {
158
+ tasks();
159
+ });
160
+ };
161
+
162
+
163
+ // Host metrics collection (replaces the external pm2-sysmonit process).
164
+ // Enabled by default; disable with `pm2 set pm2:sysmonit false` + `pm2 update`.
165
+ var sysMetricsTask = function() {
166
+ try {
167
+ SysMetrics.collect(function(data) {
168
+ God.system_infos = data || {};
169
+ });
170
+ } catch (e) {
171
+ debug('[PM2][WORKER] SysMetrics collection failed: %s', e && e.message);
172
+ }
173
+ };
174
+
175
+ God.Worker.start = function() {
176
+ timer = setInterval(wrappedTasks, cst.WORKER_INTERVAL);
177
+
178
+ var pm2_conf = Configuration.getSync('pm2');
179
+ if (!pm2_conf || pm2_conf.sysmonit != 'false') {
180
+ sysMetricsTask();
181
+ sysMetricsTimer = setInterval(sysMetricsTask, cst.WORKER_INTERVAL);
182
+ }
183
+
184
+ if (!process.env.PM2_DISABLE_VERSION_CHECK) {
185
+ setInterval(() => {
186
+ vCheck({
187
+ state: 'check',
188
+ version: pkg.version,
189
+ });
190
+ }, 1000 * 60 * 60 * 24);
191
+ }
192
+ };
193
+
194
+ God.Worker.stop = function() {
195
+ if (timer !== null)
196
+ clearInterval(timer);
197
+ if (sysMetricsTimer !== null)
198
+ clearInterval(sysMetricsTimer);
199
+ };
200
+ };