@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/God.js ADDED
@@ -0,0 +1,653 @@
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
+ * ______ _______ ______
9
+ * | __ \ | |__ |
10
+ * | __/ | __|
11
+ * |___| |__|_|__|______|
12
+ *
13
+ * Main Daemon side file
14
+ *
15
+ ******************************/
16
+
17
+ var cluster = require('cluster');
18
+ var numCPUs = require('os').cpus() ? require('os').cpus().length : 1;
19
+ var path = require('path');
20
+ var EventEmitter2 = require('eventemitter2').EventEmitter2;
21
+ var fs = require('fs');
22
+ var vizion = require('../modules/vizion');
23
+ var debug = require('debug')('pm2:god');
24
+ var Utility = require('./Utility');
25
+ var cst = require('../constants.js');
26
+ var timesLimit = require('async/timesLimit');
27
+ var Configuration = require('./Configuration.js');
28
+
29
+ /**
30
+ * Override cluster module configuration
31
+ */
32
+
33
+ // silent: workers get piped stdout/stderr (read in ClusterMode.js) instead
34
+ // of inheriting the daemon's fds, which point to pm2.log
35
+ cluster.setupMaster({
36
+ windowsHide: true,
37
+ silent: true,
38
+ exec : path.resolve(path.dirname(module.filename),
39
+ cst.IS_BUN == true ? 'ProcessContainerBun.js' : 'ProcessContainer.js')
40
+ });
41
+
42
+ /**
43
+ * Expose God
44
+ */
45
+ var God = module.exports = {
46
+ next_id : 0,
47
+ clusters_db : {},
48
+ configuration: {},
49
+ started_at : Date.now(),
50
+ system_infos_proc: null,
51
+ system_infos: null,
52
+ bus : new EventEmitter2({
53
+ wildcard: true,
54
+ delimiter: ':',
55
+ maxListeners: 1000
56
+ })
57
+ };
58
+
59
+ Utility.overrideConsole(God.bus);
60
+
61
+ /**
62
+ * Populate God namespace
63
+ */
64
+ require('./Event.js')(God);
65
+ require('./God/Methods.js')(God);
66
+ require('./God/ForkMode.js')(God);
67
+ require('./God/ClusterMode.js')(God);
68
+ require('./God/Reload')(God);
69
+ require('./God/ActionMethods')(God);
70
+ require('./Watcher')(God);
71
+
72
+ God.init = function() {
73
+ require('./Worker.js')(this)
74
+ God.system_infos_proc = null
75
+
76
+ this.configuration = Configuration.getSync('pm2')
77
+
78
+ setTimeout(function() {
79
+ God.Worker.start()
80
+ }, 500)
81
+ }
82
+
83
+ God.writeExitSeparator = function(pm2_env, code, signal) {
84
+ try {
85
+ var exit_sep = `[PM2][${new Date().toISOString()}] app exited`
86
+ if (code)
87
+ exit_sep += `itself with exit code: ${code}`
88
+ if (signal)
89
+ exit_sep += `by an external signal: ${signal}`
90
+ exit_sep += '\n'
91
+
92
+ if (pm2_env.pm_out_log_path)
93
+ fs.appendFileSync(pm2_env.pm_out_log_path, exit_sep)
94
+ if (pm2_env.pm_err_log_path)
95
+ fs.appendFileSync(pm2_env.pm_err_log_path, exit_sep)
96
+ if (pm2_env.pm_log_path)
97
+ fs.appendFileSync(pm2_env.pm_log_path, exit_sep)
98
+ } catch(e) {
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Init new process
104
+ */
105
+ God.prepare = function prepare (env, cb) {
106
+ // generate a new unique id for each processes
107
+ env.env.unique_id = Utility.generateUUID()
108
+
109
+ // if the app is standalone, no multiple instance
110
+ if (typeof env.instances === 'undefined') {
111
+ env.vizion_running = false;
112
+ if (env.env && env.env.vizion_running) env.env.vizion_running = false;
113
+
114
+ if (env.status == cst.STOPPED_STATUS) {
115
+ env.pm_id = God.getNewId()
116
+ var clu = {
117
+ pm2_env : env,
118
+ process: {
119
+ }
120
+ }
121
+ God.clusters_db[env.pm_id] = clu
122
+ God.registerCron(env)
123
+ return cb(null, [ God.clusters_db[env.pm_id] ])
124
+ }
125
+
126
+ return God.executeApp(env, function (err, clu) {
127
+ if (err) return cb(err);
128
+ God.notify('start', clu, true);
129
+ return cb(null, [ Utility.clone(clu) ]);
130
+ });
131
+ }
132
+
133
+ // find how many replicate the user want
134
+ env.instances = parseInt(env.instances);
135
+ if (env.instances === 0) {
136
+ env.instances = numCPUs;
137
+ } else if (env.instances < 0) {
138
+ env.instances += numCPUs;
139
+ }
140
+ if (env.instances <= 0) {
141
+ env.instances = 1;
142
+ }
143
+
144
+ timesLimit(env.instances, 1, function (n, next) {
145
+ env.vizion_running = false;
146
+ if (env.env && env.env.vizion_running) {
147
+ env.env.vizion_running = false;
148
+ }
149
+
150
+ God.injectVariables(env, function inject (err, _env) {
151
+ if (err) return next(err);
152
+ return God.executeApp(Utility.clone(_env), function (err, clu) {
153
+ if (err) return next(err);
154
+ God.notify('start', clu, true);
155
+ // here call next wihtout an array because
156
+ // async.times aggregate the result into an array
157
+ return next(null, Utility.clone(clu));
158
+ });
159
+ });
160
+ }, cb);
161
+ };
162
+
163
+ /**
164
+ * Launch the specified script (present in env)
165
+ * @api private
166
+ * @method executeApp
167
+ * @param {Mixed} env
168
+ * @param {Function} cb
169
+ * @return Literal
170
+ */
171
+ God.executeApp = function executeApp(env, cb) {
172
+ var env_copy = Utility.clone(env);
173
+
174
+ // Kill-time bookkeeping: a stale list (dump from 7.0.0-7.0.4) must neither
175
+ // reach the app's process.env nor be reused by a later kill
176
+ delete env_copy._tree_pids;
177
+
178
+ // Flatten env vars into pm2_env without letting a shell variable named like a
179
+ // PM2 option (name, namespace, cron_restart, instances...) override the config
180
+ Utility.extendEnv(env_copy, env_copy.env);
181
+
182
+ env_copy['status'] = env.autostart ? cst.LAUNCHING_STATUS : cst.STOPPED_STATUS;
183
+ env_copy['pm_uptime'] = Date.now();
184
+ env_copy['axm_actions'] = [];
185
+ env_copy['axm_monitor'] = {};
186
+ env_copy['axm_options'] = {};
187
+ env_copy['axm_dynamic'] = {};
188
+ env_copy['vizion_running'] =
189
+ env_copy['vizion_running'] !== undefined ? env_copy['vizion_running'] : false;
190
+
191
+ if (!env_copy.created_at)
192
+ env_copy['created_at'] = Date.now();
193
+
194
+ /**
195
+ * Enter here when it's the first time that the process is created
196
+ * 1 - Assign a new id
197
+ * 2 - Reset restart time and unstable_restarts
198
+ * 3 - Assign a log file name depending on the id
199
+ * 4 - If watch option is set, look for changes
200
+ */
201
+ if (env_copy['pm_id'] === undefined) {
202
+ env_copy['pm_id'] = God.getNewId();
203
+ env_copy['restart_time'] = 0;
204
+ env_copy['unstable_restarts'] = 0;
205
+
206
+ // add -pm_id to pid file
207
+ env_copy.pm_pid_path = env_copy.pm_pid_path.replace(/-[0-9]+\.pid$|\.pid$/g, '-' + env_copy['pm_id'] + '.pid');
208
+
209
+ // If merge option, dont separate the logs
210
+ if (!env_copy['merge_logs']) {
211
+ ['', '_out', '_err'].forEach(function(k){
212
+ var key = 'pm' + k + '_log_path';
213
+ env_copy[key] && (env_copy[key] = env_copy[key].replace(/-[0-9]+\.log$|\.log$/g, '-' + env_copy['pm_id'] + '.log'));
214
+ });
215
+ }
216
+
217
+ // Initiate watch file
218
+ if (env_copy['watch']) {
219
+ God.watch.enable(env_copy);
220
+ }
221
+ }
222
+
223
+ God.registerCron(env_copy)
224
+
225
+ if (env_copy['autostart'] === false) {
226
+ var clu = {pm2_env: env_copy, process: {pid: 0}};
227
+ God.clusters_db[env_copy.pm_id] = clu;
228
+ return cb(null, clu);
229
+ }
230
+
231
+ var cb_called = false
232
+
233
+ /** Callback when application is launched */
234
+ var readyCb = function ready(proc) {
235
+ // Idempotent: exit-before-online, ready timeout and the regular online
236
+ // path can race — only the first conclusion may answer the caller
237
+ if (cb_called) return false;
238
+ cb_called = true
239
+
240
+ proc.pm2_env.version = Utility.findPackageVersion(proc.pm2_env.pm_exec_path || proc.pm2_env.cwd);
241
+ // If vizion enabled run versioning retrieval system
242
+ if (cst.ENABLE_GIT_PARSING === true &&
243
+ proc.pm2_env.vizion !== false && proc.pm2_env.vizion !== "false") {
244
+ God.finalizeProcedure(proc);
245
+ }
246
+ else
247
+ God.notify('online', proc);
248
+
249
+ if (proc.pm2_env.status !== cst.ERRORED_STATUS)
250
+ proc.pm2_env.status = cst.ONLINE_STATUS
251
+
252
+ console.log(`App [${proc.pm2_env.name}:${proc.pm2_env.pm_id}] online`);
253
+ if (cb) cb(null, proc);
254
+ }
255
+
256
+ if (env_copy.exec_mode === 'cluster_mode') {
257
+ /**
258
+ * Cluster mode logic (for NodeJS apps)
259
+ */
260
+ God.nodeApp(env_copy, function nodeApp(err, clu) {
261
+ if (cb && err) return cb(err);
262
+ if (err) return false;
263
+
264
+ var old_env = God.clusters_db[clu.pm2_env.pm_id];
265
+
266
+ if (old_env) {
267
+ old_env = null;
268
+ God.clusters_db[clu.pm2_env.pm_id] = null;
269
+ }
270
+
271
+ God.clusters_db[clu.pm2_env.pm_id] = clu;
272
+
273
+
274
+ if (cst.IS_BUN) {
275
+ // When starting an app that does not listen on a port
276
+ // Bun do not call 'online' event
277
+ // This is a temporary workaround
278
+ var a = setTimeout(() => {
279
+ if (clu.pm2_env)
280
+ God.clusters_db[clu.pm2_env.pm_id].state = 'online'
281
+ return readyCb(clu)
282
+ }, 500)
283
+ }
284
+
285
+ clu.once('error', function(err) {
286
+ if (cst.IS_BUN)
287
+ clearTimeout(a)
288
+
289
+ console.error(err.stack || err);
290
+ try {
291
+ clu.destroy && clu.destroy();
292
+ }
293
+ catch (e) {
294
+ console.error(e.stack || e);
295
+ God.handleExit(clu, cst.ERROR_EXIT);
296
+ }
297
+ });
298
+
299
+ clu.once('disconnect', function() {
300
+ if (cst.IS_BUN)
301
+ clearTimeout(a)
302
+
303
+ console.log('App name:%s id:%s disconnected', clu.pm2_env.name, clu.pm2_env.pm_id);
304
+ });
305
+
306
+ clu.once('exit', function cluExit(code, signal) {
307
+ if (cst.IS_BUN)
308
+ clearTimeout(a)
309
+
310
+ // Worker died before emitting 'online' (bad execArgv, OOM at boot…):
311
+ // conclude executeApp's callback so callers (start/restart RPC) are
312
+ // not left hanging forever
313
+ if (cb_called == false)
314
+ readyCb(clu);
315
+ //God.writeExitSeparator(clu.pm2_env, code, signal)
316
+
317
+ God.handleExit(clu, code || 0, signal || 'SIGINT');
318
+ });
319
+
320
+ return clu.once('online', function () {
321
+ if (cst.IS_BUN) {
322
+ clearTimeout(a);
323
+ }
324
+
325
+ if (!clu.pm2_env.wait_ready)
326
+ return readyCb(clu);
327
+
328
+ // Timeout if the ready message has not been sent before listen_timeout
329
+ var ready_timeout = setTimeout(function() {
330
+ God.bus.removeListener('process:msg', listener)
331
+ return readyCb(clu)
332
+ }, clu.pm2_env.listen_timeout || cst.GRACEFUL_LISTEN_TIMEOUT);
333
+
334
+ var listener = function (packet) {
335
+ if (packet.raw === 'ready' &&
336
+ packet.process.name === clu.pm2_env.name &&
337
+ packet.process.pm_id === clu.pm2_env.pm_id) {
338
+ clearTimeout(ready_timeout);
339
+ God.bus.removeListener('process:msg', listener)
340
+ return readyCb(clu)
341
+ }
342
+ }
343
+
344
+ God.bus.on('process:msg', listener);
345
+ });
346
+ });
347
+ }
348
+ else {
349
+ /**
350
+ * Fork mode logic
351
+ */
352
+ God.forkMode(env_copy, function forkMode(err, clu) {
353
+ if (cb && err) return cb(err);
354
+ if (err) return false;
355
+
356
+ var old_env = God.clusters_db[clu.pm2_env.pm_id];
357
+ if (old_env) old_env = null;
358
+
359
+ God.clusters_db[env_copy.pm_id] = clu;
360
+
361
+ clu.once('error', function cluError(err) {
362
+ console.error(err.stack || err);
363
+ try {
364
+ clu.kill && clu.kill();
365
+ }
366
+ catch (e) {
367
+ console.error(e.stack || e);
368
+ God.handleExit(clu, cst.ERROR_EXIT);
369
+ }
370
+ });
371
+
372
+ clu.once('exit', function cluClose(code, signal) {
373
+ //God.writeExitSeparator(clu.pm2_env, code, signal)
374
+
375
+ if (clu.connected === true)
376
+ clu.disconnect && clu.disconnect();
377
+ clu._reloadLogs = null;
378
+
379
+ // Process died before the wait_ready conclusion: answer the caller
380
+ // now instead of waiting for the ready timeout
381
+ if (cb_called == false)
382
+ readyCb(clu);
383
+ return God.handleExit(clu, code || 0, signal);
384
+ });
385
+
386
+ if (!clu.pm2_env.wait_ready)
387
+ return readyCb(clu);
388
+
389
+ // Timeout if the ready message has not been sent before listen_timeout
390
+ var ready_timeout = setTimeout(function() {
391
+ God.bus.removeListener('process:msg', listener)
392
+ return readyCb(clu)
393
+ }, clu.pm2_env.listen_timeout || cst.GRACEFUL_LISTEN_TIMEOUT);
394
+
395
+ var listener = function (packet) {
396
+ if (packet.raw === 'ready' &&
397
+ packet.process.name === clu.pm2_env.name &&
398
+ packet.process.pm_id === clu.pm2_env.pm_id) {
399
+ clearTimeout(ready_timeout);
400
+ God.bus.removeListener('process:msg', listener)
401
+ return readyCb(clu)
402
+ }
403
+ }
404
+ God.bus.on('process:msg', listener);
405
+ });
406
+ }
407
+ return false;
408
+ };
409
+
410
+ /**
411
+ * Handle logic when a process exit (Node or Fork)
412
+ * @method handleExit
413
+ * @param {} clu
414
+ * @param {} exit_code
415
+ * @return
416
+ */
417
+ God.handleExit = function handleExit(clu, exit_code, kill_signal) {
418
+ console.log(`App [${clu.pm2_env.name}:${clu.pm2_env.pm_id}] exited with code [${exit_code}] via signal [${kill_signal || 'SIGINT'}]`)
419
+
420
+ var proc = this.clusters_db[clu.pm2_env.pm_id];
421
+
422
+ if (!proc) {
423
+ console.error('Process undefined ? with process id ', clu.pm2_env.pm_id);
424
+ return false;
425
+ }
426
+
427
+ // A late exit event can belong to a previous generation of this pm_id whose
428
+ // slot has already been taken over by a replacement (seen on Windows with
429
+ // shutdown_with_message, #6142): it must not affect the current occupant
430
+ if (proc !== clu) {
431
+ console.log(`App [${clu.pm2_env.name}:${clu.pm2_env.pm_id}] stale exit event ignored (pid ${clu.process.pid})`);
432
+ return false;
433
+ }
434
+
435
+ var stopExitCodes = proc.pm2_env.stop_exit_codes !== undefined && proc.pm2_env.stop_exit_codes !== null ? proc.pm2_env.stop_exit_codes : [];
436
+ if (!Array.isArray(stopExitCodes)) {
437
+ stopExitCodes = [stopExitCodes];
438
+ }
439
+
440
+ var stopping = (proc.pm2_env.status == cst.STOPPING_STATUS
441
+ || proc.pm2_env.status == cst.STOPPED_STATUS
442
+ || proc.pm2_env.status == cst.ERRORED_STATUS)
443
+ || (proc.pm2_env.autorestart === false || proc.pm2_env.autorestart === "false")
444
+ || (stopExitCodes.map((strOrNum) => typeof strOrNum === 'string' ? parseInt(strOrNum, 10) : strOrNum)
445
+ .includes(exit_code));
446
+
447
+ var overlimit = false;
448
+
449
+ if (stopping) proc.process.pid = 0;
450
+
451
+ // Reset probes and actions
452
+ if (proc.pm2_env.axm_actions) proc.pm2_env.axm_actions = [];
453
+ if (proc.pm2_env.axm_monitor) proc.pm2_env.axm_monitor = {};
454
+
455
+ if (proc.pm2_env.status != cst.ERRORED_STATUS &&
456
+ proc.pm2_env.status != cst.STOPPING_STATUS)
457
+ proc.pm2_env.status = cst.STOPPED_STATUS;
458
+
459
+ if (proc.pm2_env.pm_id.toString().indexOf('_old_') !== 0) {
460
+ try {
461
+ fs.unlinkSync(proc.pm2_env.pm_pid_path);
462
+ } catch (e) {
463
+ debug('Error when unlinking pid file', e);
464
+ }
465
+ }
466
+
467
+ /**
468
+ * Avoid infinite reloop if an error is present
469
+ */
470
+ // If the process has been created less than 15seconds ago
471
+
472
+ // And if the process has an uptime less than a second
473
+ var min_uptime = typeof(proc.pm2_env.min_uptime) !== 'undefined' ? proc.pm2_env.min_uptime : 1000;
474
+ var max_restarts = typeof(proc.pm2_env.max_restarts) !== 'undefined' ? proc.pm2_env.max_restarts : 16;
475
+
476
+ if ((Date.now() - proc.pm2_env.created_at) < (min_uptime * max_restarts)) {
477
+ if ((Date.now() - proc.pm2_env.pm_uptime) < min_uptime) {
478
+ // Increment unstable restart
479
+ proc.pm2_env.unstable_restarts += 1;
480
+ }
481
+ }
482
+
483
+
484
+ if (proc.pm2_env.unstable_restarts >= max_restarts) {
485
+ // Too many unstable restart in less than 15 seconds
486
+ // Set the process as 'ERRORED'
487
+ // And stop restarting it
488
+ proc.pm2_env.status = cst.ERRORED_STATUS;
489
+ proc.process.pid = 0;
490
+
491
+ console.log('Script %s had too many unstable restarts (%d). Stopped. %j',
492
+ proc.pm2_env.pm_exec_path,
493
+ proc.pm2_env.unstable_restarts,
494
+ proc.pm2_env.status);
495
+
496
+ God.notify('restart overlimit', proc);
497
+
498
+ proc.pm2_env.unstable_restarts = 0;
499
+ proc.pm2_env.created_at = null;
500
+ overlimit = true;
501
+ }
502
+
503
+ if (typeof(exit_code) !== 'undefined') proc.pm2_env.exit_code = exit_code;
504
+
505
+ God.notify('exit', proc);
506
+
507
+ if (God.pm2_being_killed) {
508
+ //console.log('[HandleExit] PM2 is being killed, stopping restart procedure...');
509
+ return false;
510
+ }
511
+
512
+ var restart_delay = 0;
513
+
514
+ if (proc.pm2_env.restart_delay !== undefined &&
515
+ !isNaN(parseInt(proc.pm2_env.restart_delay))) {
516
+ proc.pm2_env.status = cst.WAITING_RESTART;
517
+ restart_delay = parseInt(proc.pm2_env.restart_delay);
518
+ }
519
+
520
+ if (proc.pm2_env.exp_backoff_restart_delay !== undefined &&
521
+ !isNaN(parseInt(proc.pm2_env.exp_backoff_restart_delay))) {
522
+ proc.pm2_env.status = cst.WAITING_RESTART;
523
+ if (!proc.pm2_env.prev_restart_delay) {
524
+ proc.pm2_env.prev_restart_delay = proc.pm2_env.exp_backoff_restart_delay
525
+ restart_delay = proc.pm2_env.exp_backoff_restart_delay
526
+ }
527
+ else {
528
+ proc.pm2_env.prev_restart_delay = Math.floor(Math.min(15000, proc.pm2_env.prev_restart_delay * 1.5))
529
+ restart_delay = proc.pm2_env.prev_restart_delay
530
+ }
531
+ console.log(`App [${clu.pm2_env.name}:${clu.pm2_env.pm_id}] will restart in ${restart_delay}ms`)
532
+ }
533
+
534
+ if (!stopping && !overlimit) {
535
+ //make this property unenumerable
536
+ Object.defineProperty(proc.pm2_env, 'restart_task', {configurable: true, writable: true});
537
+ proc.pm2_env.restart_task = setTimeout(function() {
538
+ proc.pm2_env.restart_time += 1;
539
+ God.executeApp(proc.pm2_env);
540
+ }, restart_delay);
541
+ }
542
+
543
+ return false;
544
+ };
545
+
546
+ /**
547
+ * @method finalizeProcedure
548
+ * @param proc {Object}
549
+ * @return
550
+ */
551
+ God.finalizeProcedure = function finalizeProcedure(proc) {
552
+ var last_path = '';
553
+ var current_path = proc.pm2_env.cwd || path.dirname(proc.pm2_env.pm_exec_path);
554
+ var proc_id = proc.pm2_env.pm_id;
555
+
556
+ proc.pm2_env.version = Utility.findPackageVersion(proc.pm2_env.pm_exec_path || proc.pm2_env.cwd);
557
+
558
+ if (proc.pm2_env.vizion_running === true) {
559
+ debug('Vizion is already running for proc id: %d, skipping this round', proc_id);
560
+ return God.notify('online', proc);
561
+ }
562
+ proc.pm2_env.vizion_running = true;
563
+
564
+ vizion.analyze({folder : current_path}, function recur_path(err, meta){
565
+ var proc = God.clusters_db[proc_id];
566
+
567
+ if (err)
568
+ debug(err.stack || err);
569
+
570
+ if (!proc ||
571
+ !proc.pm2_env ||
572
+ proc.pm2_env.status == cst.STOPPED_STATUS ||
573
+ proc.pm2_env.status == cst.STOPPING_STATUS ||
574
+ proc.pm2_env.status == cst.ERRORED_STATUS) {
575
+ return console.error('Cancelling versioning data parsing');
576
+ }
577
+
578
+ proc.pm2_env.vizion_running = false;
579
+
580
+ if (!err) {
581
+ proc.pm2_env.versioning = meta;
582
+ proc.pm2_env.versioning.repo_path = current_path;
583
+ God.notify('online', proc);
584
+ }
585
+ else if (err && current_path === last_path) {
586
+ proc.pm2_env.versioning = null;
587
+ God.notify('online', proc);
588
+ }
589
+ else {
590
+ last_path = current_path;
591
+ current_path = path.dirname(current_path);
592
+ proc.pm2_env.vizion_running = true;
593
+ vizion.analyze({folder : current_path}, recur_path);
594
+ }
595
+ return false;
596
+ });
597
+ };
598
+
599
+ /**
600
+ * Inject variables into processes
601
+ * @param {Object} env environnement to be passed to the process
602
+ * @param {Function} cb invoked with <err, env>
603
+ */
604
+ God.injectVariables = function injectVariables (env, cb) {
605
+ // allow to override the key of NODE_APP_INSTANCE if wanted
606
+ var instanceKey = process.env.PM2_PROCESS_INSTANCE_VAR || env.instance_var;
607
+
608
+ // we need to find the last NODE_APP_INSTANCE used
609
+ var instances = Object.keys(God.clusters_db)
610
+ .map(function (procId) {
611
+ return God.clusters_db[procId];
612
+ }).filter(function (proc) {
613
+ return proc.pm2_env.name === env.name &&
614
+ typeof proc.pm2_env[instanceKey] !== 'undefined';
615
+ }).map(function (proc) {
616
+ return proc.pm2_env[instanceKey];
617
+ }).sort(function (a, b) {
618
+ return b - a;
619
+ });
620
+ // default to last one + 1
621
+ var instanceNumber = typeof instances[0] === 'undefined' ? 0 : instances[0] + 1;
622
+ // but try to find a one available
623
+ for (var i = 0; i < instances.length; i++) {
624
+ if (instances.indexOf(i) === -1) {
625
+ instanceNumber = i;
626
+ break;
627
+ }
628
+ }
629
+ env[instanceKey] = instanceNumber;
630
+
631
+ // if using increment_var, we need to increment it
632
+ if (env.increment_var) {
633
+ var lastIncrement = Object.keys(God.clusters_db)
634
+ .map(function (procId) {
635
+ return God.clusters_db[procId];
636
+ }).filter(function (proc) {
637
+ return proc.pm2_env.name === env.name &&
638
+ typeof proc.pm2_env[env.increment_var] !== 'undefined';
639
+ }).map(function (proc) {
640
+ return Number(proc.pm2_env[env.increment_var]);
641
+ }).sort(function (a, b) {
642
+ return b - a;
643
+ })[0];
644
+ // inject a incremental variable
645
+ var defaut = Number(env.env[env.increment_var]) || 0;
646
+ env[env.increment_var] = typeof lastIncrement === 'undefined' ? defaut : lastIncrement + 1;
647
+ env.env[env.increment_var] = env[env.increment_var];
648
+ }
649
+
650
+ return cb(null, env);
651
+ };
652
+
653
+ God.init()