@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/API.js ADDED
@@ -0,0 +1,1980 @@
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
+ 'use strict';
7
+
8
+ const commander = require('commander');
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+ const eachLimit = require('async/eachLimit');
12
+ const series = require('async/series');
13
+ const debug = require('debug')('pm2:cli');
14
+ const util = require('util');
15
+ const chalk = require('ansis');
16
+ const fclone = require('../modules/fclone');
17
+
18
+ var DockerMgmt = require('./API/ExtraMgmt/Docker.js')
19
+ var conf = require('../constants.js');
20
+ var Client = require('./Client');
21
+ var Common = require('./Common');
22
+ var KMDaemon = require('../modules/pm2-io-agent/src/InteractorClient');
23
+ var Config = require('./tools/Config');
24
+ var pm2Keys = require('./tools/pm2-config-keys.js');
25
+ var Modularizer = require('./API/Modules/Modularizer.js');
26
+ var path_structure = require('../paths.js');
27
+ var UX = require('./API/UX');
28
+ var pkg = require('../package.json');
29
+ var hf = require('./API/Modules/flagExt.js');
30
+ var Configuration = require('./Configuration.js');
31
+ const sexec = require('./tools/sexec.js')
32
+
33
+ var IMMUTABLE_MSG = chalk.bold.blue('Use --update-env to update environment variables');
34
+
35
+ /**
36
+ * Main Function to be imported
37
+ * can be aliased to PM2
38
+ *
39
+ * To use it when PM2 is installed as a module:
40
+ *
41
+ * var PM2 = require('pm2');
42
+ *
43
+ * var pm2 = PM2(<opts>);
44
+ *
45
+ *
46
+ * @param {Object} opts
47
+ * @param {String} [opts.cwd=<current>] override pm2 cwd for starting scripts
48
+ * @param {String} [opts.pm2_home=[<paths.js>]] pm2 directory for log, pids, socket files
49
+ * @param {Boolean} [opts.independent=false] unique PM2 instance (random pm2_home)
50
+ * @param {Boolean} [opts.daemon_mode=true] should be called in the same process or not
51
+ * @param {String} [opts.public_key=null] pm2 plus bucket public key
52
+ * @param {String} [opts.secret_key=null] pm2 plus bucket secret key
53
+ * @param {String} [opts.machine_name=null] pm2 plus instance name
54
+ */
55
+ class API {
56
+
57
+ constructor (opts) {
58
+ if (!opts) opts = {};
59
+ var that = this;
60
+
61
+ this.daemon_mode = typeof(opts.daemon_mode) == 'undefined' ? true : opts.daemon_mode;
62
+ this.pm2_home = conf.PM2_ROOT_PATH;
63
+ this.public_key = conf.PUBLIC_KEY || opts.public_key || null;
64
+ this.secret_key = conf.SECRET_KEY || opts.secret_key || null;
65
+ this.machine_name = conf.MACHINE_NAME || opts.machine_name || null
66
+
67
+ /**
68
+ * CWD resolution
69
+ */
70
+ this.cwd = process.cwd();
71
+ if (opts.cwd) {
72
+ this.cwd = path.resolve(opts.cwd);
73
+ }
74
+
75
+ /**
76
+ * PM2 HOME resolution
77
+ */
78
+ if (opts.pm2_home && opts.independent == true)
79
+ throw new Error('You cannot set a pm2_home and independent instance in same time');
80
+
81
+ if (opts.pm2_home) {
82
+ // Override default conf file
83
+ this.pm2_home = opts.pm2_home;
84
+ conf = Object.assign(conf, path_structure(this.pm2_home));
85
+ }
86
+ else if (opts.independent == true && conf.IS_WINDOWS === false) {
87
+ // Create an unique pm2 instance
88
+ const crypto = require('crypto');
89
+ var random_file = crypto.randomBytes(8).toString('hex');
90
+ this.pm2_home = path.join('/tmp', random_file);
91
+
92
+ // If we dont explicitly tell to have a daemon
93
+ // It will go as in proc
94
+ if (typeof(opts.daemon_mode) == 'undefined')
95
+ this.daemon_mode = false;
96
+ conf = Object.assign(conf, path_structure(this.pm2_home));
97
+ }
98
+
99
+ this._conf = conf;
100
+
101
+ if (conf.IS_WINDOWS) {
102
+ // Weird fix, may need to be dropped
103
+ // @todo windows connoisseur double check
104
+ if (process.stdout._handle && process.stdout._handle.setBlocking)
105
+ process.stdout._handle.setBlocking(true);
106
+ }
107
+
108
+ this.Client = new Client({
109
+ pm2_home: that.pm2_home,
110
+ conf: this._conf,
111
+ secret_key: this.secret_key,
112
+ public_key: this.public_key,
113
+ daemon_mode: this.daemon_mode,
114
+ machine_name: this.machine_name
115
+ });
116
+
117
+ this.pm2_configuration = Configuration.getSync('pm2') || {}
118
+
119
+ this.gl_interact_infos = null;
120
+ this.gl_is_km_linked = false;
121
+
122
+ try {
123
+ var pid = fs.readFileSync(conf.INTERACTOR_PID_PATH);
124
+ pid = parseInt(pid.toString().trim());
125
+ process.kill(pid, 0);
126
+ that.gl_is_km_linked = true;
127
+ } catch (e) {
128
+ that.gl_is_km_linked = false;
129
+ }
130
+
131
+ // For testing purposes
132
+ if (this.secret_key && process.env.NODE_ENV == 'local_test')
133
+ that.gl_is_km_linked = true;
134
+
135
+ KMDaemon.ping(this._conf, function(err, result) {
136
+ if (!err && result === true) {
137
+ fs.readFile(conf.INTERACTION_CONF, (err, _conf) => {
138
+ if (!err) {
139
+ try {
140
+ that.gl_interact_infos = JSON.parse(_conf.toString())
141
+ } catch(e) {
142
+ var json5 = require('./tools/json5.js')
143
+ try {
144
+ that.gl_interact_infos = json5.parse(_conf.toString())
145
+ } catch(e) {
146
+ console.error(e)
147
+ that.gl_interact_infos = null
148
+ }
149
+ }
150
+ }
151
+ })
152
+ }
153
+ })
154
+
155
+ this.gl_retry = 0;
156
+ }
157
+
158
+ /**
159
+ * Connect to PM2
160
+ * Calling this command is now optional
161
+ *
162
+ * @param {Function} cb callback once pm2 is ready for commands
163
+ */
164
+ connect (noDaemon, cb) {
165
+ var that = this;
166
+ this.start_timer = new Date();
167
+
168
+ if (typeof(cb) == 'undefined') {
169
+ cb = noDaemon;
170
+ noDaemon = false;
171
+ } else if (noDaemon === true) {
172
+ // Backward compatibility with PM2 1.x
173
+ this.Client.daemon_mode = false;
174
+ this.daemon_mode = false;
175
+ }
176
+
177
+ this.Client.start(function(err, meta) {
178
+ if (err)
179
+ return cb(err);
180
+
181
+ if (meta.new_pm2_instance == false && that.daemon_mode === true)
182
+ return cb(err, meta);
183
+
184
+ // If new pm2 instance has been popped
185
+ // Launch all modules
186
+ that.launchAll(that, function(err_mod) {
187
+ return cb(err, meta);
188
+ });
189
+ });
190
+ }
191
+
192
+ /**
193
+ * Usefull when custom PM2 created with independent flag set to true
194
+ * This will cleanup the newly created instance
195
+ * by removing folder, killing PM2 and so on
196
+ *
197
+ * @param {Function} cb callback once cleanup is successfull
198
+ */
199
+ destroy (cb) {
200
+ var that = this;
201
+
202
+ debug('Killing and deleting current deamon');
203
+
204
+ this.killDaemon(function() {
205
+ var cmd = 'rm -rf ' + that.pm2_home;
206
+ var test_path = path.join(that.pm2_home, 'module_conf.json');
207
+ var test_path_2 = path.join(that.pm2_home, 'pm2.pid');
208
+
209
+ if (that.pm2_home.indexOf('.pm2') > -1)
210
+ return cb(new Error('Destroy is not a allowed method on .pm2'));
211
+
212
+ fs.access(test_path, fs.constants.R_OK, function(err) {
213
+ if (err) return cb(err);
214
+ debug('Deleting temporary folder %s', that.pm2_home);
215
+ sexec(cmd, cb);
216
+ });
217
+ });
218
+ }
219
+
220
+ /**
221
+ * Disconnect from PM2 instance
222
+ * This will allow your software to exit by itself
223
+ *
224
+ * @param {Function} [cb] optional callback once connection closed
225
+ */
226
+ disconnect (cb) {
227
+ var that = this;
228
+
229
+ if (!cb) cb = function() {};
230
+
231
+ this.Client.close(function(err, data) {
232
+ debug('The session lasted %ds', (new Date() - that.start_timer) / 1000);
233
+ return cb(err, data);
234
+ });
235
+ };
236
+
237
+ /**
238
+ * Alias on disconnect
239
+ * @param cb
240
+ */
241
+ close (cb) {
242
+ this.disconnect(cb);
243
+ }
244
+
245
+ /**
246
+ * Launch modules
247
+ *
248
+ * @param {Function} cb callback once pm2 has launched modules
249
+ */
250
+ launchModules (cb) {
251
+ this.launchAll(this, cb);
252
+ }
253
+
254
+ /**
255
+ * Enable bus allowing to retrieve various process event
256
+ * like logs, restarts, reloads
257
+ *
258
+ * @param {Function} cb callback called with 1st param err and 2nb param the bus
259
+ */
260
+ launchBus (cb) {
261
+ this.Client.launchBus(cb);
262
+ }
263
+
264
+ /**
265
+ * Exit methods for API
266
+ * @param {Integer} code exit code for terminal
267
+ */
268
+ exitCli (code) {
269
+ var that = this;
270
+
271
+ // Do nothing if PM2 called programmatically (also in speedlist)
272
+ if (conf.PM2_PROGRAMMATIC && process.env.PM2_USAGE != 'CLI') return false;
273
+
274
+ KMDaemon.disconnectRPC(function() {
275
+ that.Client.close(function() {
276
+ code = code || 0;
277
+ // Safe exits process after all streams are drained.
278
+ // file descriptor flag.
279
+ var fds = 0;
280
+ // exits process when stdout (1) and sdterr(2) are both drained.
281
+ function tryToExit() {
282
+ if ((fds & 1) && (fds & 2)) {
283
+ debug('This command took %ds to execute', (new Date() - that.start_timer) / 1000);
284
+ process.exit(code);
285
+ }
286
+ }
287
+
288
+ [process.stdout, process.stderr].forEach(function(std) {
289
+ var fd = std.fd;
290
+ if (!std.bufferSize) {
291
+ // bufferSize equals 0 means current stream is drained.
292
+ fds = fds | fd;
293
+ } else {
294
+ // Appends nothing to the std queue, but will trigger `tryToExit` event on `drain`.
295
+ std.write && std.write('', function() {
296
+ fds = fds | fd;
297
+ tryToExit();
298
+ });
299
+ }
300
+ // Does not write anything more.
301
+ delete std.write;
302
+ });
303
+ tryToExit();
304
+ });
305
+ });
306
+ }
307
+
308
+ ////////////////////////////
309
+ // Application management //
310
+ ////////////////////////////
311
+
312
+ /**
313
+ * Start a file or json with configuration
314
+ * @param {Object||String} cmd script to start or json
315
+ * @param {Function} cb called when application has been started
316
+ */
317
+ start (cmd, opts, cb) {
318
+ if (typeof(opts) == "function") {
319
+ cb = opts;
320
+ opts = {};
321
+ }
322
+ if (!opts) opts = {};
323
+
324
+ var that = this;
325
+ if (Array.isArray(opts.watch) && opts.watch.length === 0)
326
+ opts.watch = (opts.rawArgs ? !!~opts.rawArgs.indexOf('--watch') : !!~process.argv.indexOf('--watch')) || false;
327
+
328
+ if (Common.isConfigFile(cmd) || (typeof(cmd) === 'object')) {
329
+ that._startJson(cmd, opts, 'restartProcessId', (err, procs) => {
330
+ return cb ? cb(err, procs) : this.speedList()
331
+ })
332
+ }
333
+ else {
334
+ that._startScript(cmd, opts, (err, procs) => {
335
+ return cb ? cb(err, procs) : this.speedList(0)
336
+ })
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Reset process counters
342
+ *
343
+ * @method resetMetaProcess
344
+ */
345
+ reset (process_name, cb) {
346
+ var that = this;
347
+
348
+ function processIds(ids, cb) {
349
+ eachLimit(ids, conf.CONCURRENT_ACTIONS, function(id, next) {
350
+ that.Client.executeRemote('resetMetaProcessId', id, function(err, res) {
351
+ if (err) console.error(err);
352
+ Common.printOut(conf.PREFIX_MSG + 'Resetting meta for process id %d', id);
353
+ return next();
354
+ });
355
+ }, function(err) {
356
+ if (err) return cb(Common.retErr(err));
357
+ return cb ? cb(null, {success:true}) : that.speedList();
358
+ });
359
+ }
360
+
361
+ if (process_name == 'all') {
362
+ that.Client.getAllProcessId(function(err, ids) {
363
+ if (err) {
364
+ Common.printError(err);
365
+ return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
366
+ }
367
+ return processIds(ids, cb);
368
+ });
369
+ }
370
+ else if (isNaN(process_name)) {
371
+ that.Client.getProcessIdByName(process_name, function(err, ids) {
372
+ if (err) {
373
+ Common.printError(err);
374
+ return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
375
+ }
376
+ if (ids.length === 0) {
377
+ Common.printError('Unknown process name');
378
+ return cb ? cb(new Error('Unknown process name')) : that.exitCli(conf.ERROR_EXIT);
379
+ }
380
+ return processIds(ids, cb);
381
+ });
382
+ } else {
383
+ processIds([process_name], cb);
384
+ }
385
+ }
386
+
387
+ /**
388
+ * Update daemonized PM2 Daemon
389
+ *
390
+ * @param {Function} cb callback when pm2 has been upgraded
391
+ */
392
+ update (cb) {
393
+ var that = this;
394
+
395
+ Common.printOut('Be sure to have the latest version by doing `npm install pm2@latest -g` before doing this procedure.');
396
+
397
+ // Dump PM2 processes
398
+ that.Client.executeRemote('notifyKillPM2', {}, function() {});
399
+
400
+ that.getVersion(function(err, new_version) {
401
+ // If not linked to PM2 plus, and update PM2 to latest, display motd.update
402
+ if (!that.gl_is_km_linked && !err && (pkg.version != new_version)) {
403
+ var dt = fs.readFileSync(path.join(__dirname, that._conf.PM2_UPDATE));
404
+ console.log(dt.toString());
405
+ }
406
+
407
+ that.dump(function(err) {
408
+ that.killDaemon(function() {
409
+ that.Client.launchDaemon({interactor:false}, function(err, child) {
410
+ that.Client.launchRPC(function() {
411
+ that.resurrect(function() {
412
+ Common.printOut(chalk.blue.bold('>>>>>>>>>> PM2 updated'));
413
+ that.launchAll(that, function() {
414
+ KMDaemon.launchAndInteract(that._conf, {
415
+ pm2_version: pkg.version
416
+ }, function(err, data, interactor_proc) {
417
+ })
418
+ setTimeout(() => {
419
+ return cb ? cb(null, {success:true}) : that.speedList();
420
+ }, 250)
421
+ });
422
+ });
423
+ });
424
+ });
425
+ });
426
+ });
427
+ });
428
+
429
+ return false;
430
+ }
431
+
432
+ /**
433
+ * Reload an application
434
+ *
435
+ * @param {String} process_name Application Name or All
436
+ * @param {Object} opts Options
437
+ * @param {Function} cb Callback
438
+ */
439
+ reload (process_name, opts, cb) {
440
+ var that = this;
441
+
442
+ if (typeof(opts) == "function") {
443
+ cb = opts;
444
+ opts = {};
445
+ }
446
+
447
+ var delay = Common.lockReload();
448
+ if (delay > 0 && opts.force != true) {
449
+ Common.printError(conf.PREFIX_MSG_ERR + 'Reload already in progress, please try again in ' + Math.floor((conf.RELOAD_LOCK_TIMEOUT - delay) / 1000) + ' seconds or use --force');
450
+ return cb ? cb(new Error('Reload in progress')) : that.exitCli(conf.ERROR_EXIT);
451
+ }
452
+
453
+ if (Common.isConfigFile(process_name))
454
+ that._startJson(process_name, opts, 'reloadProcessId', function(err, apps) {
455
+ Common.unlockReload();
456
+ if (err)
457
+ return cb ? cb(err) : that.exitCli(conf.ERROR_EXIT);
458
+ return cb ? cb(null, apps) : that.exitCli(conf.SUCCESS_EXIT);
459
+ });
460
+ else {
461
+ if (opts && opts.env) {
462
+ var err = 'Using --env [env] without passing the ecosystem.config.js does not work'
463
+ Common.err(err);
464
+ Common.unlockReload();
465
+ return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
466
+ }
467
+
468
+ if (opts && !opts.updateEnv)
469
+ Common.printOut(IMMUTABLE_MSG);
470
+
471
+ that._operate('reloadProcessId', process_name, opts, function(err, apps) {
472
+ Common.unlockReload();
473
+
474
+ if (err)
475
+ return cb ? cb(err) : that.exitCli(conf.ERROR_EXIT);
476
+ return cb ? cb(null, apps) : that.exitCli(conf.SUCCESS_EXIT);
477
+ });
478
+ }
479
+ }
480
+
481
+ /**
482
+ * Restart process
483
+ *
484
+ * @param {String} cmd Application Name / Process id / JSON application file / 'all'
485
+ * @param {Object} opts Extra options to be updated
486
+ * @param {Function} cb Callback
487
+ */
488
+ restart (cmd, opts, cb) {
489
+ if (typeof(opts) == "function") {
490
+ cb = opts;
491
+ opts = {};
492
+ }
493
+ var that = this;
494
+
495
+ if (typeof(cmd) === 'number')
496
+ cmd = cmd.toString();
497
+
498
+ if (cmd == "-") {
499
+ // Restart from PIPED JSON
500
+ process.stdin.resume();
501
+ process.stdin.setEncoding('utf8');
502
+ process.stdin.on('data', function (param) {
503
+ process.stdin.pause();
504
+ that.actionFromJson('restartProcessId', param, opts, 'pipe', cb);
505
+ });
506
+ }
507
+ else if (Common.isConfigFile(cmd) || typeof(cmd) === 'object')
508
+ that._startJson(cmd, opts, 'restartProcessId', cb);
509
+ else {
510
+ if (opts && opts.env) {
511
+ var err = 'Using --env [env] without passing the ecosystem.config.js does not work'
512
+ Common.err(err);
513
+ return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
514
+ }
515
+ if (opts && !opts.updateEnv)
516
+ Common.printOut(IMMUTABLE_MSG);
517
+ that._operate('restartProcessId', cmd, opts, cb);
518
+ }
519
+ }
520
+
521
+ /**
522
+ * Delete process
523
+ *
524
+ * @param {String} process_name Application Name / Process id / Application file / 'all'
525
+ * @param {Function} cb Callback
526
+ */
527
+ delete (process_name, jsonVia, cb) {
528
+ var that = this;
529
+
530
+ if (typeof(jsonVia) === "function") {
531
+ cb = jsonVia;
532
+ jsonVia = null;
533
+ }
534
+
535
+ if (typeof(process_name) === "number") {
536
+ process_name = process_name.toString();
537
+ }
538
+
539
+ if (jsonVia == 'pipe')
540
+ return that.actionFromJson('deleteProcessId', process_name, commander, 'pipe', (err, procs) => {
541
+ return cb ? cb(err, procs) : this.speedList()
542
+ });
543
+ if (Common.isConfigFile(process_name))
544
+ return that.actionFromJson('deleteProcessId', process_name, commander, 'file', (err, procs) => {
545
+ return cb ? cb(err, procs) : this.speedList()
546
+ });
547
+ else {
548
+ that._operate('deleteProcessId', process_name, (err, procs) => {
549
+ return cb ? cb(err, procs) : this.speedList()
550
+ });
551
+ }
552
+ }
553
+
554
+ /**
555
+ * Stop process
556
+ *
557
+ * @param {String} process_name Application Name / Process id / Application file / 'all'
558
+ * @param {Function} cb Callback
559
+ */
560
+ stop (process_name, cb) {
561
+ var that = this;
562
+
563
+ if (typeof(process_name) === 'number')
564
+ process_name = process_name.toString();
565
+
566
+ if (process_name == "-") {
567
+ process.stdin.resume();
568
+ process.stdin.setEncoding('utf8');
569
+ process.stdin.on('data', function (param) {
570
+ process.stdin.pause();
571
+ that.actionFromJson('stopProcessId', param, commander, 'pipe', (err, procs) => {
572
+ return cb ? cb(err, procs) : this.speedList()
573
+ })
574
+ });
575
+ }
576
+ else if (Common.isConfigFile(process_name))
577
+ that.actionFromJson('stopProcessId', process_name, commander, 'file', (err, procs) => {
578
+ return cb ? cb(err, procs) : this.speedList()
579
+ });
580
+ else
581
+ that._operate('stopProcessId', process_name, (err, procs) => {
582
+ return cb ? cb(err, procs) : this.speedList()
583
+ });
584
+ }
585
+
586
+ /**
587
+ * Get list of all processes managed
588
+ *
589
+ * @param {Function} cb Callback
590
+ */
591
+ list (opts, cb) {
592
+ var that = this;
593
+
594
+ if (typeof(opts) == 'function') {
595
+ cb = opts;
596
+ opts = null;
597
+ }
598
+
599
+ that.Client.executeRemote('getMonitorData', {}, function(err, list) {
600
+ if (err) {
601
+ Common.printError(err);
602
+ return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
603
+ }
604
+
605
+ if (opts && opts.rawArgs && opts.rawArgs.indexOf('--watch') > -1) {
606
+ var dayjs = require('dayjs');
607
+ function show() {
608
+ process.stdout.write('\x1b[2J');
609
+ process.stdout.write('\x1b[0f');
610
+ console.log('Last refresh: ', dayjs().format());
611
+ that.Client.executeRemote('getMonitorData', {}, function(err, list) {
612
+ UX.list(list, null);
613
+ });
614
+ }
615
+
616
+ show();
617
+ setInterval(show, 900);
618
+ return false;
619
+ }
620
+
621
+ return cb ? cb(null, list) : that.speedList(null);
622
+ });
623
+ }
624
+
625
+ /**
626
+ * Kill Daemon
627
+ *
628
+ * @param {Function} cb Callback
629
+ */
630
+ killDaemon (cb) {
631
+ process.env.PM2_STATUS = 'stopping'
632
+
633
+ var that = this;
634
+
635
+ that.Client.executeRemote('notifyKillPM2', {}, function() {});
636
+
637
+ that._operate('deleteProcessId', 'all', function(err, list) {
638
+ Common.printOut(conf.PREFIX_MSG + '[v] All Applications Stopped');
639
+ process.env.PM2_SILENT = 'false';
640
+
641
+ that.killAgent(function(err, data) {
642
+ if (!err) {
643
+ Common.printOut(conf.PREFIX_MSG + '[v] Agent Stopped');
644
+ }
645
+
646
+ that.Client.killDaemon(function(err, res) {
647
+ if (err) Common.printError(err);
648
+ Common.printOut(conf.PREFIX_MSG + '[v] PM2 Daemon Stopped');
649
+ return cb ? cb(err, res) : that.exitCli(conf.SUCCESS_EXIT);
650
+ });
651
+
652
+ });
653
+ })
654
+ }
655
+
656
+ kill (cb) {
657
+ this.killDaemon(cb);
658
+ }
659
+
660
+ /////////////////////
661
+ // Private methods //
662
+ /////////////////////
663
+
664
+ /**
665
+ * Method to START / RESTART a script
666
+ *
667
+ * @private
668
+ * @param {string} script script name (will be resolved according to location)
669
+ */
670
+ _startScript (script, opts, cb) {
671
+ if (typeof opts == "function") {
672
+ cb = opts;
673
+ opts = {};
674
+ }
675
+ var that = this;
676
+
677
+ /**
678
+ * Commander.js tricks
679
+ */
680
+ var app_conf = Config.filterOptions(opts);
681
+ var appConf = {};
682
+
683
+ if (typeof app_conf.name == 'function')
684
+ delete app_conf.name;
685
+
686
+ delete app_conf.args;
687
+
688
+ // Retrieve arguments via -- <args>
689
+ var argsIndex;
690
+
691
+ if (opts.rawArgs && (argsIndex = opts.rawArgs.indexOf('--')) >= 0)
692
+ app_conf.args = opts.rawArgs.slice(argsIndex + 1);
693
+ else if (opts.scriptArgs)
694
+ app_conf.args = opts.scriptArgs;
695
+
696
+ app_conf.script = script;
697
+ if(!app_conf.namespace)
698
+ app_conf.namespace = 'default';
699
+
700
+ if ((appConf = Common.verifyConfs(app_conf)) instanceof Error) {
701
+ Common.err(appConf)
702
+ return cb ? cb(Common.retErr(appConf)) : that.exitCli(conf.ERROR_EXIT);
703
+ }
704
+
705
+ app_conf = appConf[0];
706
+
707
+ if (opts.watchDelay) {
708
+ if (typeof opts.watchDelay === "string" && opts.watchDelay.indexOf("ms") !== -1)
709
+ app_conf.watch_delay = parseInt(opts.watchDelay);
710
+ else {
711
+ app_conf.watch_delay = parseFloat(opts.watchDelay) * 1000;
712
+ }
713
+ }
714
+
715
+ var mas = [];
716
+ if(typeof opts.ext != 'undefined')
717
+ hf.make_available_extension(opts, mas); // for -e flag
718
+ mas.length > 0 ? app_conf.ignore_watch = mas : 0;
719
+
720
+ /**
721
+ * If -w option, write configuration to configuration.json file
722
+ */
723
+ if (app_conf.write) {
724
+ var dst_path = path.join(process.env.PWD || process.cwd(), app_conf.name + '-pm2.json');
725
+ Common.printOut(conf.PREFIX_MSG + 'Writing configuration to', chalk.blue(dst_path));
726
+ // pretty JSON
727
+ try {
728
+ fs.writeFileSync(dst_path, JSON.stringify(app_conf, null, 2));
729
+ } catch (e) {
730
+ console.error(e.stack || e);
731
+ }
732
+ }
733
+
734
+ series([
735
+ restartExistingProcessName,
736
+ restartExistingNameSpace,
737
+ restartExistingProcessId,
738
+ restartExistingProcessPathOrStartNew
739
+ ], function(err, data) {
740
+ if (err instanceof Error)
741
+ return cb ? cb(err) : that.exitCli(conf.ERROR_EXIT);
742
+
743
+ var ret = {};
744
+
745
+ data.forEach(function(_dt) {
746
+ if (_dt !== undefined)
747
+ ret = _dt;
748
+ });
749
+
750
+ return cb ? cb(null, ret) : that.speedList();
751
+ });
752
+
753
+ /**
754
+ * If start <app_name> start/restart application
755
+ */
756
+ function restartExistingProcessName(cb) {
757
+ if (!isNaN(script) ||
758
+ (typeof script === 'string' && script.indexOf('/') != -1) ||
759
+ (typeof script === 'string' && path.extname(script) !== ''))
760
+ return cb(null);
761
+
762
+ that.Client.getProcessIdByName(script, function(err, ids) {
763
+ if (err && cb) return cb(err);
764
+ if (ids.length > 0) {
765
+ that._operate('restartProcessId', script, opts, function(err, list) {
766
+ if (err) return cb(err);
767
+ Common.printOut(conf.PREFIX_MSG + 'Process successfully started');
768
+ return cb(true, list);
769
+ });
770
+ }
771
+ else return cb(null);
772
+ });
773
+ }
774
+
775
+ /**
776
+ * If start <namespace> start/restart namespace
777
+ */
778
+ function restartExistingNameSpace(cb) {
779
+ if (!isNaN(script) ||
780
+ (typeof script === 'string' && script.indexOf('/') != -1) ||
781
+ (typeof script === 'string' && path.extname(script) !== ''))
782
+ return cb(null);
783
+
784
+ if (script !== 'all') {
785
+ that.Client.getProcessIdsByNamespace(script, function (err, ids) {
786
+ if (err && cb) return cb(err);
787
+ if (ids.length > 0) {
788
+ that._operate('restartProcessId', script, opts, function (err, list) {
789
+ if (err) return cb(err);
790
+ Common.printOut(conf.PREFIX_MSG + 'Process successfully started');
791
+ return cb(true, list);
792
+ });
793
+ }
794
+ else return cb(null);
795
+ });
796
+ }
797
+ else {
798
+ that._operate('restartProcessId', 'all', function(err, list) {
799
+ if (err) return cb(err);
800
+ Common.printOut(conf.PREFIX_MSG + 'Process successfully started');
801
+ return cb(true, list);
802
+ });
803
+ }
804
+ }
805
+
806
+ function restartExistingProcessId(cb) {
807
+ if (isNaN(script)) return cb(null);
808
+
809
+ that._operate('restartProcessId', script, opts, function(err, list) {
810
+ if (err) return cb(err);
811
+ Common.printOut(conf.PREFIX_MSG + 'Process successfully started');
812
+ return cb(true, list);
813
+ });
814
+ }
815
+
816
+ /**
817
+ * Restart a process with the same full path
818
+ * Or start it
819
+ */
820
+ function restartExistingProcessPathOrStartNew(cb) {
821
+ that.Client.executeRemote('getMonitorData', {}, function(err, procs) {
822
+ if (err) return cb ? cb(new Error(err)) : that.exitCli(conf.ERROR_EXIT);
823
+
824
+ var full_path = path.resolve(that.cwd, script);
825
+ var managed_script = null;
826
+
827
+ procs.forEach(function(proc) {
828
+ if (proc.pm2_env.pm_exec_path == full_path &&
829
+ proc.pm2_env.name == app_conf.name)
830
+ managed_script = proc;
831
+ });
832
+
833
+ if (managed_script &&
834
+ (managed_script.pm2_env.status == conf.STOPPED_STATUS ||
835
+ managed_script.pm2_env.status == conf.STOPPING_STATUS ||
836
+ managed_script.pm2_env.status == conf.ERRORED_STATUS)) {
837
+ // Restart process if stopped
838
+ var app_name = managed_script.pm2_env.name;
839
+
840
+ that._operate('restartProcessId', app_name, opts, function(err, list) {
841
+ if (err) return cb ? cb(new Error(err)) : that.exitCli(conf.ERROR_EXIT);
842
+ Common.printOut(conf.PREFIX_MSG + 'Process successfully started');
843
+ return cb(true, list);
844
+ });
845
+ return false;
846
+ }
847
+ else if (managed_script && !opts.force) {
848
+ Common.err('Script already launched, add -f option to force re-execution');
849
+ return cb(new Error('Script already launched'));
850
+ }
851
+
852
+ var resolved_paths = null;
853
+
854
+ try {
855
+ resolved_paths = Common.resolveAppAttributes({
856
+ cwd : that.cwd,
857
+ pm2_home : that.pm2_home
858
+ }, app_conf);
859
+ } catch(e) {
860
+ Common.err(e.message);
861
+ return cb(Common.retErr(e));
862
+ }
863
+
864
+ Common.printOut(conf.PREFIX_MSG + 'Starting %s in %s (%d instance' + (resolved_paths.instances > 1 ? 's' : '') + ')',
865
+ resolved_paths.pm_exec_path, resolved_paths.exec_mode, resolved_paths.instances);
866
+
867
+ if (!resolved_paths.env) resolved_paths.env = {};
868
+
869
+ // Set PM2 HOME in case of child process using PM2 API
870
+ resolved_paths.env['PM2_HOME'] = that.pm2_home;
871
+
872
+ var additional_env = Modularizer.getAdditionalConf(resolved_paths.name);
873
+ Object.assign(resolved_paths.env, additional_env);
874
+
875
+ // Is KM linked?
876
+ resolved_paths.km_link = that.gl_is_km_linked;
877
+
878
+ that.Client.executeRemote('prepare', resolved_paths, function(err, data) {
879
+ if (err) {
880
+ Common.printError(conf.PREFIX_MSG_ERR + 'Error while launching application', err.stack || err);
881
+ return cb(Common.retErr(err));
882
+ }
883
+
884
+ Common.printOut(conf.PREFIX_MSG + 'Done.');
885
+ return cb(true, data);
886
+ });
887
+ return false;
888
+ });
889
+ }
890
+ }
891
+
892
+ /**
893
+ * Method to start/restart/reload processes from a JSON file
894
+ * It will start app not started
895
+ * Can receive only option to skip applications
896
+ *
897
+ * @private
898
+ */
899
+ _startJson (file, opts, action, pipe, cb) {
900
+ var config = {};
901
+ var appConf = {};
902
+ var staticConf = [];
903
+ var deployConf = {};
904
+ var apps_info = [];
905
+ var that = this;
906
+
907
+ /**
908
+ * Get File configuration
909
+ */
910
+ if (typeof(cb) === 'undefined' && typeof(pipe) === 'function') {
911
+ cb = pipe;
912
+ }
913
+ if (typeof(file) === 'object') {
914
+ config = file;
915
+ } else if (pipe === 'pipe') {
916
+ config = Common.parseConfig(file, 'pipe');
917
+ } else {
918
+ var data = null;
919
+
920
+ var isAbsolute = path.isAbsolute(file)
921
+ var file_path = isAbsolute ? file : path.join(that.cwd, file);
922
+
923
+ debug('Resolved filepath %s', file_path);
924
+
925
+ try {
926
+ data = fs.readFileSync(file_path);
927
+ } catch(e) {
928
+ Common.printError(conf.PREFIX_MSG_ERR + 'File ' + file +' not found');
929
+ return cb ? cb(Common.retErr(e)) : that.exitCli(conf.ERROR_EXIT);
930
+ }
931
+
932
+ try {
933
+ config = Common.parseConfig(data, file);
934
+ } catch(e) {
935
+ Common.printError(conf.PREFIX_MSG_ERR + 'File ' + file + ' malformated');
936
+ console.error(e);
937
+ return cb ? cb(Common.retErr(e)) : that.exitCli(conf.ERROR_EXIT);
938
+ }
939
+ }
940
+
941
+ /**
942
+ * Alias some optional fields
943
+ */
944
+ if (config.deploy)
945
+ deployConf = config.deploy;
946
+ if (config.static)
947
+ staticConf = config.static;
948
+ if (config.apps)
949
+ appConf = config.apps;
950
+ else if (config.pm2)
951
+ appConf = config.pm2;
952
+ else
953
+ appConf = config;
954
+ if (!Array.isArray(appConf))
955
+ appConf = [appConf];
956
+
957
+ if ((appConf = Common.verifyConfs(appConf)) instanceof Error)
958
+ return cb ? cb(appConf) : that.exitCli(conf.ERROR_EXIT);
959
+
960
+ process.env.PM2_JSON_PROCESSING = true;
961
+
962
+ // Get App list
963
+ var apps_name = [];
964
+ var proc_list = {};
965
+
966
+ // Add statics to apps
967
+ staticConf.forEach(function(serve) {
968
+ appConf.push({
969
+ name: serve.name ? serve.name : `static-page-server-${serve.port}`,
970
+ script: path.resolve(__dirname, 'API', 'Serve.js'),
971
+ env: {
972
+ PM2_SERVE_PORT: serve.port,
973
+ PM2_SERVE_HOST: serve.host,
974
+ PM2_SERVE_PATH: serve.path,
975
+ PM2_SERVE_SPA: serve.spa,
976
+ PM2_SERVE_FTP: serve.ftp,
977
+ PM2_SERVE_DIRECTORY: serve.directory,
978
+ PM2_SERVE_BASIC_AUTH: serve.basic_auth !== undefined,
979
+ PM2_SERVE_BASIC_AUTH_USERNAME: serve.basic_auth ? serve.basic_auth.username : null,
980
+ PM2_SERVE_BASIC_AUTH_PASSWORD: serve.basic_auth ? serve.basic_auth.password : null,
981
+ PM2_SERVE_MONITOR: serve.monitor
982
+ }
983
+ });
984
+ });
985
+
986
+ // Here we pick only the field we want from the CLI when starting a JSON
987
+ appConf.forEach(function(app) {
988
+ if (!app.env) { app.env = {}; }
989
+ app.env.io = app.io;
990
+ // --only <app>
991
+ if (opts.only) {
992
+ var apps = opts.only.split(/,| /)
993
+ if (apps.indexOf(app.name) == -1)
994
+ return false
995
+ }
996
+ // Namespace
997
+ if (!app.namespace) {
998
+ if (opts.namespace)
999
+ app.namespace = opts.namespace;
1000
+ else
1001
+ app.namespace = 'default';
1002
+ }
1003
+ // --watch
1004
+ if (!app.watch && opts.watch && opts.watch === true)
1005
+ app.watch = true;
1006
+ // --ignore-watch
1007
+ if (!app.ignore_watch && opts.ignore_watch)
1008
+ app.ignore_watch = opts.ignore_watch;
1009
+ if (opts.install_url)
1010
+ app.install_url = opts.install_url;
1011
+ // --instances <nb>
1012
+ if (opts.instances && typeof(opts.instances) === 'number')
1013
+ app.instances = opts.instances;
1014
+ // --uid <user>
1015
+ if (opts.uid)
1016
+ app.uid = opts.uid;
1017
+ // --gid <user>
1018
+ if (opts.gid)
1019
+ app.gid = opts.gid;
1020
+ // --filter-env (#6176)
1021
+ if (app.filter_env === undefined && opts.filterEnv !== undefined)
1022
+ app.filter_env = opts.filterEnv;
1023
+ // Specific
1024
+ if (app.append_env_to_name && opts.env)
1025
+ app.name += ('-' + opts.env);
1026
+ if (opts.name_prefix && app.name.indexOf(opts.name_prefix) == -1)
1027
+ app.name = `${opts.name_prefix}:${app.name}`
1028
+
1029
+ app.username = Common.getCurrentUsername();
1030
+ apps_name.push(app.name);
1031
+ });
1032
+
1033
+ that.Client.executeRemote('getMonitorData', {}, function(err, raw_proc_list) {
1034
+ if (err) {
1035
+ Common.printError(err);
1036
+ return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
1037
+ }
1038
+
1039
+ /**
1040
+ * Uniquify in memory process list
1041
+ */
1042
+ // filter_env each process runs with, for the shell env updateEnv
1043
+ // re-reads when the file sets none: no lookup per app (#6176)
1044
+ var stored_filters = {};
1045
+
1046
+ raw_proc_list.forEach(function(proc) {
1047
+ proc_list[proc.name] = proc;
1048
+ stored_filters[proc.pm_id] = proc.pm2_env.filter_env;
1049
+ });
1050
+
1051
+ /**
1052
+ * Auto detect application already started
1053
+ * and act on them depending on action
1054
+ */
1055
+ eachLimit(Object.keys(proc_list), conf.CONCURRENT_ACTIONS, function(proc_name, next) {
1056
+ // Skip app name (--only option)
1057
+ if (apps_name.indexOf(proc_name) == -1)
1058
+ return next();
1059
+
1060
+ if (!(action == 'reloadProcessId' ||
1061
+ action == 'softReloadProcessId' ||
1062
+ action == 'restartProcessId'))
1063
+ throw new Error('Wrong action called');
1064
+
1065
+ var apps = appConf.filter(function(app) {
1066
+ return app.name == proc_name;
1067
+ });
1068
+
1069
+ var envs = apps.map(function(app){
1070
+ // Binds env_diff to env and returns it.
1071
+ return Common.mergeEnvironmentVariables(app, opts.env, deployConf);
1072
+ });
1073
+
1074
+ // Assigns own enumerable properties of all
1075
+ // Notice: if people use the same name in different apps,
1076
+ // duplicated envs will be overrode by the last one
1077
+ var env = envs.reduce(function(e1, e2){
1078
+ return Object.assign(e1, e2);
1079
+ });
1080
+
1081
+ // When we are processing JSON, allow to keep the new env by default
1082
+ env.updateEnv = true;
1083
+
1084
+ // Pass `env` option
1085
+ that._operate(action, proc_name, env, stored_filters, function(err, ret) {
1086
+ if (err) Common.printError(err);
1087
+
1088
+ // For return
1089
+ apps_info = apps_info.concat(ret);
1090
+
1091
+ that.Client.notifyGod(action, proc_name);
1092
+ // And Remove from array to spy
1093
+ apps_name.splice(apps_name.indexOf(proc_name), 1);
1094
+ return next();
1095
+ });
1096
+
1097
+ }, function(err) {
1098
+ if (err) return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
1099
+ if (apps_name.length > 0 && action != 'start')
1100
+ Common.printOut(conf.PREFIX_MSG_WARNING + 'Applications %s not running, starting...', apps_name.join(', '));
1101
+ // Start missing apps
1102
+ return startApps(apps_name, function(err, apps) {
1103
+ apps_info = apps_info.concat(apps);
1104
+ return cb ? cb(err, apps_info) : that.speedList(err ? 1 : 0);
1105
+ });
1106
+ });
1107
+ return false;
1108
+ });
1109
+
1110
+ function startApps(app_name_to_start, cb) {
1111
+ var apps_to_start = [];
1112
+ var apps_started = [];
1113
+ var apps_errored = [];
1114
+
1115
+ appConf.forEach(function(app, i) {
1116
+ if (app_name_to_start.indexOf(app.name) != -1) {
1117
+ apps_to_start.push(appConf[i]);
1118
+ }
1119
+ });
1120
+
1121
+ eachLimit(apps_to_start, conf.CONCURRENT_ACTIONS, function(app, next) {
1122
+ if (opts.cwd)
1123
+ app.cwd = opts.cwd;
1124
+ if (opts.force_name)
1125
+ app.name = opts.force_name;
1126
+ if (opts.started_as_module)
1127
+ app.pmx_module = true;
1128
+
1129
+ var resolved_paths = null;
1130
+
1131
+ // hardcode script name to use `serve` feature inside a process file
1132
+ if (app.script === 'serve') {
1133
+ app.script = path.resolve(__dirname, 'API', 'Serve.js')
1134
+ }
1135
+
1136
+ try {
1137
+ resolved_paths = Common.resolveAppAttributes({
1138
+ cwd : that.cwd,
1139
+ pm2_home : that.pm2_home
1140
+ }, app);
1141
+ } catch (e) {
1142
+ apps_errored.push(e)
1143
+ Common.err(`Error: ${e.message}`)
1144
+ return next();
1145
+ }
1146
+
1147
+ if (!resolved_paths.env) resolved_paths.env = {};
1148
+
1149
+ // Set PM2 HOME in case of child process using PM2 API
1150
+ resolved_paths.env['PM2_HOME'] = that.pm2_home;
1151
+
1152
+ var additional_env = Modularizer.getAdditionalConf(resolved_paths.name);
1153
+ Object.assign(resolved_paths.env, additional_env);
1154
+
1155
+ resolved_paths.env = Common.mergeEnvironmentVariables(resolved_paths, opts.env, deployConf);
1156
+
1157
+ delete resolved_paths.env.current_conf;
1158
+
1159
+ // Is KM linked?
1160
+ resolved_paths.km_link = that.gl_is_km_linked;
1161
+
1162
+ if (resolved_paths.wait_ready) {
1163
+ Common.warn(`App ${resolved_paths.name} has option 'wait_ready' set, waiting for app to be ready...`)
1164
+ }
1165
+ that.Client.executeRemote('prepare', resolved_paths, function(err, data) {
1166
+ if (err) {
1167
+ Common.printError(conf.PREFIX_MSG_ERR + 'Process failed to launch %s', err.message ? err.message : err);
1168
+ return next();
1169
+ }
1170
+ if (data.length === 0) {
1171
+ Common.printError(conf.PREFIX_MSG_ERR + 'Process config loading failed', data);
1172
+ return next();
1173
+ }
1174
+
1175
+ Common.printOut(conf.PREFIX_MSG + 'App [%s] launched (%d instances)', data[0].pm2_env.name, data.length);
1176
+ apps_started = apps_started.concat(data);
1177
+ next();
1178
+ });
1179
+
1180
+ }, function(err) {
1181
+ var final_error = err || apps_errored.length > 0 ? apps_errored : null
1182
+ return cb ? cb(final_error, apps_started) : that.speedList();
1183
+ });
1184
+ return false;
1185
+ }
1186
+ }
1187
+
1188
+ /**
1189
+ * Apply a RPC method on the json file
1190
+ * @private
1191
+ * @method actionFromJson
1192
+ * @param {string} action RPC Method
1193
+ * @param {object} options
1194
+ * @param {string|object} file file
1195
+ * @param {string} jsonVia action type (=only 'pipe' ?)
1196
+ * @param {Function}
1197
+ */
1198
+ actionFromJson (action, file, opts, jsonVia, cb) {
1199
+ var appConf = {};
1200
+ var ret_processes = [];
1201
+ var that = this;
1202
+
1203
+ //accept programmatic calls
1204
+ if (typeof file == 'object') {
1205
+ cb = typeof jsonVia == 'function' ? jsonVia : cb;
1206
+ appConf = file;
1207
+ }
1208
+ else if (jsonVia == 'file') {
1209
+ var data = null;
1210
+
1211
+ try {
1212
+ data = fs.readFileSync(file);
1213
+ } catch(e) {
1214
+ Common.printError(conf.PREFIX_MSG_ERR + 'File ' + file +' not found');
1215
+ return cb ? cb(Common.retErr(e)) : that.exitCli(conf.ERROR_EXIT);
1216
+ }
1217
+
1218
+ try {
1219
+ appConf = Common.parseConfig(data, file);
1220
+ } catch(e) {
1221
+ Common.printError(conf.PREFIX_MSG_ERR + 'File ' + file + ' malformated');
1222
+ console.error(e);
1223
+ return cb ? cb(Common.retErr(e)) : that.exitCli(conf.ERROR_EXIT);
1224
+ }
1225
+ } else if (jsonVia == 'pipe') {
1226
+ appConf = Common.parseConfig(file, 'pipe');
1227
+ } else {
1228
+ Common.printError('Bad call to actionFromJson, jsonVia should be one of file, pipe');
1229
+ return that.exitCli(conf.ERROR_EXIT);
1230
+ }
1231
+
1232
+ // Backward compatibility
1233
+ if (appConf.apps)
1234
+ appConf = appConf.apps;
1235
+
1236
+ if (!Array.isArray(appConf))
1237
+ appConf = [appConf];
1238
+
1239
+ if ((appConf = Common.verifyConfs(appConf)) instanceof Error)
1240
+ return cb ? cb(appConf) : that.exitCli(conf.ERROR_EXIT);
1241
+
1242
+ eachLimit(appConf, conf.CONCURRENT_ACTIONS, function(proc, next1) {
1243
+ var name = '';
1244
+ var new_env;
1245
+
1246
+ if (!proc.name)
1247
+ name = path.basename(proc.script);
1248
+ else
1249
+ name = proc.name;
1250
+
1251
+ if (opts.only && opts.only != name)
1252
+ return process.nextTick(next1);
1253
+
1254
+ if (opts && opts.env)
1255
+ new_env = Common.mergeEnvironmentVariables(proc, opts.env);
1256
+ else
1257
+ new_env = Common.mergeEnvironmentVariables(proc);
1258
+
1259
+ that.Client.getProcessIdByName(name, function(err, ids) {
1260
+ if (err) {
1261
+ Common.printError(err);
1262
+ return next1();
1263
+ }
1264
+ if (!ids) return next1();
1265
+
1266
+ eachLimit(ids, conf.CONCURRENT_ACTIONS, function(id, next2) {
1267
+ var opts = {};
1268
+
1269
+ //stopProcessId could accept options to?
1270
+ if (action == 'restartProcessId') {
1271
+ opts = {id : id, env : new_env};
1272
+ } else {
1273
+ opts = id;
1274
+ }
1275
+
1276
+ that.Client.executeRemote(action, opts, function(err, res) {
1277
+ ret_processes.push(res);
1278
+ if (err) {
1279
+ Common.printError(err);
1280
+ return next2();
1281
+ }
1282
+
1283
+ if (action == 'restartProcessId') {
1284
+ that.Client.notifyGod('restart', id);
1285
+ } else if (action == 'deleteProcessId') {
1286
+ that.Client.notifyGod('delete', id);
1287
+ } else if (action == 'stopProcessId') {
1288
+ that.Client.notifyGod('stop', id);
1289
+ }
1290
+
1291
+ Common.printOut(conf.PREFIX_MSG + '[%s](%d) \u2713', name, id);
1292
+ return next2();
1293
+ });
1294
+ }, function(err) {
1295
+ return next1(null, ret_processes);
1296
+ });
1297
+ });
1298
+ }, function(err) {
1299
+ if (cb) return cb(null, ret_processes);
1300
+ else return that.speedList();
1301
+ });
1302
+ }
1303
+
1304
+
1305
+ /**
1306
+ * Main function to operate with PM2 daemon
1307
+ *
1308
+ * @param {String} action_name Name of action (restartProcessId, deleteProcessId, stopProcessId)
1309
+ * @param {String} process_name can be 'all', a id integer or process name
1310
+ * @param {Object} envs object with CLI options / environment
1311
+ * @param {Object} [stored_filters] pm_id -> filter_env, when the caller has the process list
1312
+ */
1313
+ _operate (action_name, process_name, envs, stored_filters, cb) {
1314
+ var that = this;
1315
+ var update_env = false;
1316
+ var ret = [];
1317
+
1318
+ // stored_filters (pm_id -> filter_env) is optional
1319
+ if (typeof(stored_filters) == 'function') {
1320
+ cb = stored_filters;
1321
+ stored_filters = null;
1322
+ }
1323
+
1324
+ // Make sure all options exist
1325
+ if (!envs)
1326
+ envs = {};
1327
+
1328
+ if (typeof(envs) == 'function'){
1329
+ cb = envs;
1330
+ envs = {};
1331
+ }
1332
+
1333
+ // Set via env.update (JSON processing)
1334
+ if (envs.updateEnv === true)
1335
+ update_env = true;
1336
+
1337
+ var concurrent_actions = envs.parallel || conf.CONCURRENT_ACTIONS;
1338
+
1339
+ if (!process.env.PM2_JSON_PROCESSING || envs.commands) {
1340
+ envs = that._handleAttributeUpdate(envs);
1341
+ }
1342
+
1343
+ /**
1344
+ * Set current updated configuration if not passed
1345
+ */
1346
+ if (!envs.current_conf) {
1347
+ var _conf = fclone(envs);
1348
+ envs = {
1349
+ current_conf : _conf
1350
+ }
1351
+
1352
+ // Is KM linked?
1353
+ envs.current_conf.km_link = that.gl_is_km_linked;
1354
+ }
1355
+
1356
+ /**
1357
+ * --update-env re-reads the shell env: filter it like the initial start
1358
+ * did, with the new filter_env if the conf sets one, else the one each
1359
+ * process was started with (#6176)
1360
+ */
1361
+ var filter_env = envs.current_conf.filter_env;
1362
+
1363
+ function processIds(ids, cb) {
1364
+ if (update_env !== true || filter_env !== undefined)
1365
+ return operateIds(ids, {}, cb);
1366
+
1367
+ if (stored_filters)
1368
+ return operateIds(ids, stored_filters, cb);
1369
+
1370
+ that.Client.executeRemote('getMonitorData', {}, function(err, list) {
1371
+ if (err) {
1372
+ Common.printError(err);
1373
+ return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
1374
+ }
1375
+ var filters = {};
1376
+ list.forEach(function(proc) {
1377
+ filters[proc.pm_id] = proc.pm2_env.filter_env;
1378
+ });
1379
+ return operateIds(ids, filters, cb);
1380
+ });
1381
+ }
1382
+
1383
+ /**
1384
+ * Operate action on specific process id
1385
+ */
1386
+ function operateIds(ids, filters, cb) {
1387
+ Common.printOut(conf.PREFIX_MSG + 'Applying action %s on app [%s](ids: %s)', action_name, process_name, ids);
1388
+
1389
+ if (ids.length <= 2)
1390
+ concurrent_actions = 1;
1391
+
1392
+ if (action_name == 'deleteProcessId')
1393
+ concurrent_actions = 10;
1394
+
1395
+ eachLimit(ids, concurrent_actions, function(id, next) {
1396
+ var opts;
1397
+
1398
+ // These functions need extra param to be passed
1399
+ if (action_name == 'restartProcessId' ||
1400
+ action_name == 'reloadProcessId' ||
1401
+ action_name == 'softReloadProcessId') {
1402
+ var new_env = {};
1403
+
1404
+ if (update_env === true) {
1405
+ // Same rule as the initial start in Common.prepareAppConf: the
1406
+ // shell may not re-supply PM2 options on --update-env, only real
1407
+ // environment variables. The app's own config is layered on top.
1408
+ new_env = Common.safeExtend({}, pm2Keys.filterShellEnv(process.env,
1409
+ filter_env !== undefined ? filter_env : filters[id]));
1410
+
1411
+ Object.keys(envs).forEach(function(k) {
1412
+ new_env[k] = envs[k];
1413
+ });
1414
+ }
1415
+ else {
1416
+ new_env = envs;
1417
+ }
1418
+
1419
+ opts = {
1420
+ id : id,
1421
+ env : new_env
1422
+ };
1423
+ }
1424
+ else {
1425
+ opts = id;
1426
+ }
1427
+
1428
+ that.Client.executeRemote(action_name, opts, function(err, res) {
1429
+ if (err) {
1430
+ // Surface the daemon's actual error (e.g. `Reload already in
1431
+ // progress`) instead of masking everything as `not found`
1432
+ var error_msg = (err && err.message) ? err.message : `Process ${id} not found`;
1433
+ Common.printError(conf.PREFIX_MSG_ERR + '%s', error_msg);
1434
+ return next(error_msg);
1435
+ }
1436
+
1437
+ if (action_name == 'restartProcessId') {
1438
+ that.Client.notifyGod('restart', id);
1439
+ } else if (action_name == 'deleteProcessId') {
1440
+ that.Client.notifyGod('delete', id);
1441
+ } else if (action_name == 'stopProcessId') {
1442
+ that.Client.notifyGod('stop', id);
1443
+ } else if (action_name == 'reloadProcessId') {
1444
+ that.Client.notifyGod('reload', id);
1445
+ } else if (action_name == 'softReloadProcessId') {
1446
+ that.Client.notifyGod('graceful reload', id);
1447
+ }
1448
+
1449
+ if (!Array.isArray(res))
1450
+ res = [res];
1451
+
1452
+ // Filter return
1453
+ res.forEach(function(proc) {
1454
+ Common.printOut(conf.PREFIX_MSG + '[%s](%d) \u2713', proc.pm2_env ? proc.pm2_env.name : process_name, id);
1455
+
1456
+ if (action_name == 'stopProcessId' && proc.pm2_env && proc.pm2_env.cron_restart) {
1457
+ Common.warn(`App ${chalk.bold(proc.pm2_env.name)} stopped but CRON RESTART is still UP ${proc.pm2_env.cron_restart}`)
1458
+ }
1459
+
1460
+ if (!proc.pm2_env) return false;
1461
+
1462
+ ret.push({
1463
+ name : proc.pm2_env.name,
1464
+ namespace: proc.pm2_env.namespace,
1465
+ pm_id : proc.pm2_env.pm_id,
1466
+ status : proc.pm2_env.status,
1467
+ restart_time : proc.pm2_env.restart_time,
1468
+ pm2_env : {
1469
+ name : proc.pm2_env.name,
1470
+ namespace: proc.pm2_env.namespace,
1471
+ pm_id : proc.pm2_env.pm_id,
1472
+ status : proc.pm2_env.status,
1473
+ restart_time : proc.pm2_env.restart_time,
1474
+ env : proc.pm2_env.env
1475
+ }
1476
+ });
1477
+ });
1478
+
1479
+ return next();
1480
+ });
1481
+ }, function(err) {
1482
+ if (err) return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
1483
+ return cb ? cb(null, ret) : that.speedList();
1484
+ });
1485
+ }
1486
+
1487
+ if (process_name == 'all') {
1488
+ // When using shortcuts like 'all', do not delete modules
1489
+ var fn
1490
+
1491
+ if (process.env.PM2_STATUS == 'stopping')
1492
+ that.Client.getAllProcessId(function(err, ids) {
1493
+ reoperate(err, ids)
1494
+ });
1495
+ else
1496
+ that.Client.getAllProcessIdWithoutModules(function(err, ids) {
1497
+ reoperate(err, ids)
1498
+ });
1499
+
1500
+ function reoperate(err, ids) {
1501
+ if (err) {
1502
+ Common.printError(err);
1503
+ return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
1504
+ }
1505
+ if (!ids || ids.length === 0) {
1506
+ Common.printError(conf.PREFIX_MSG_WARNING + 'No process found');
1507
+ return cb ? cb(new Error('process name not found')) : that.exitCli(conf.ERROR_EXIT);
1508
+ }
1509
+ return processIds(ids, cb);
1510
+ }
1511
+ }
1512
+ // operate using regex
1513
+ else if (isNaN(process_name) && process_name[0] === '/' && process_name[process_name.length - 1] === '/') {
1514
+ var regex = new RegExp(process_name.replace(/\//g, ''));
1515
+
1516
+ that.Client.executeRemote('getMonitorData', {}, function(err, list) {
1517
+ if (err) {
1518
+ Common.printError('Error retrieving process list: ' + err);
1519
+ return cb(err);
1520
+ }
1521
+ var found_proc = [];
1522
+ list.forEach(function(proc) {
1523
+ if (regex.test(proc.pm2_env.name)) {
1524
+ found_proc.push(proc.pm_id);
1525
+ }
1526
+ });
1527
+
1528
+ if (found_proc.length === 0) {
1529
+ Common.printError(conf.PREFIX_MSG_WARNING + 'No process found');
1530
+ return cb ? cb(new Error('process name not found')) : that.exitCli(conf.ERROR_EXIT);
1531
+ }
1532
+
1533
+ return processIds(found_proc, cb);
1534
+ });
1535
+ }
1536
+ else if (isNaN(process_name)) {
1537
+ /**
1538
+ * We can not stop or delete a module but we can restart it
1539
+ * to refresh configuration variable
1540
+ */
1541
+ var allow_module_restart = action_name == 'restartProcessId' ? true : false;
1542
+
1543
+ that.Client.getProcessIdByName(process_name, allow_module_restart, function (err, ids) {
1544
+ if (err) {
1545
+ Common.printError(err);
1546
+ return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
1547
+ }
1548
+ if (ids && ids.length > 0) {
1549
+ /**
1550
+ * Determine if the process to restart is a module
1551
+ * if yes load configuration variables and merge with the current environment
1552
+ */
1553
+ var additional_env = Modularizer.getAdditionalConf(process_name);
1554
+ Object.assign(envs, additional_env);
1555
+ return processIds(ids, cb);
1556
+ }
1557
+
1558
+ that.Client.getProcessIdsByNamespace(process_name, allow_module_restart, function (err, ns_process_ids) {
1559
+ if (err) {
1560
+ Common.printError(err);
1561
+ return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
1562
+ }
1563
+ if (!ns_process_ids || ns_process_ids.length === 0) {
1564
+ Common.printError(conf.PREFIX_MSG_ERR + 'Process or Namespace %s not found', process_name);
1565
+ return cb ? cb(new Error('process or namespace not found')) : that.exitCli(conf.ERROR_EXIT);
1566
+ }
1567
+
1568
+ /**
1569
+ * Determine if the process to restart is a module
1570
+ * if yes load configuration variables and merge with the current environment
1571
+ */
1572
+ var ns_additional_env = Modularizer.getAdditionalConf(process_name);
1573
+ Object.assign(envs, ns_additional_env);
1574
+ return processIds(ns_process_ids, cb);
1575
+ });
1576
+ });
1577
+ } else {
1578
+ if (that.pm2_configuration.docker == "true" ||
1579
+ that.pm2_configuration.docker == true) {
1580
+ // Docker/Systemd process interaction detection
1581
+ that.Client.executeRemote('getMonitorData', {}, (err, proc_list) => {
1582
+ var higher_id = 0
1583
+ proc_list.forEach(p => { p.pm_id > higher_id ? higher_id = p.pm_id : null })
1584
+
1585
+ // Is Docker/Systemd
1586
+ if (process_name > higher_id)
1587
+ return DockerMgmt.processCommand(that, higher_id, process_name, action_name, (err) => {
1588
+ if (err) {
1589
+ Common.printError(conf.PREFIX_MSG_ERR + (err.message ? err.message : err));
1590
+ return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
1591
+ }
1592
+
1593
+ return cb ? cb(null, ret) : that.speedList();
1594
+ })
1595
+
1596
+ // Check if application name as number is an app name
1597
+ that.Client.getProcessIdByName(process_name, function(err, ids) {
1598
+ if (ids.length > 0)
1599
+ return processIds(ids, cb);
1600
+
1601
+ // Check if application name as number is an namespace
1602
+ that.Client.getProcessIdsByNamespace(process_name, function(err, ns_process_ids) {
1603
+ if (ns_process_ids.length > 0)
1604
+ return processIds(ns_process_ids, cb);
1605
+ // Else operate on pm id
1606
+ return processIds([process_name], cb);
1607
+ });
1608
+ });
1609
+ })
1610
+ }
1611
+ else {
1612
+ // Check if application name as number is an app name
1613
+ that.Client.getProcessIdByName(process_name, function(err, ids) {
1614
+ if (ids.length > 0)
1615
+ return processIds(ids, cb);
1616
+
1617
+ // Check if application name as number is an namespace
1618
+ that.Client.getProcessIdsByNamespace(process_name, function(err, ns_process_ids) {
1619
+ if (ns_process_ids.length > 0)
1620
+ return processIds(ns_process_ids, cb);
1621
+ // Else operate on pm id
1622
+ return processIds([process_name], cb);
1623
+ });
1624
+ });
1625
+ }
1626
+ }
1627
+ }
1628
+
1629
+ /**
1630
+ * Converts CamelCase Commander.js arguments
1631
+ * to Underscore
1632
+ * (nodeArgs -> node_args)
1633
+ */
1634
+ _handleAttributeUpdate (opts) {
1635
+ var conf = Config.filterOptions(opts);
1636
+ var that = this;
1637
+
1638
+ if (typeof(conf.name) != 'string')
1639
+ delete conf.name;
1640
+
1641
+ var argsIndex = 0;
1642
+ if (opts.rawArgs && (argsIndex = opts.rawArgs.indexOf('--')) >= 0) {
1643
+ conf.args = opts.rawArgs.slice(argsIndex + 1);
1644
+ }
1645
+
1646
+ var appConf = Common.verifyConfs(conf)[0];
1647
+
1648
+ if (appConf instanceof Error) {
1649
+ Common.printError('Error while transforming CamelCase args to underscore');
1650
+ return appConf;
1651
+ }
1652
+
1653
+ if (argsIndex == -1)
1654
+ delete appConf.args;
1655
+ if (appConf.name == 'undefined')
1656
+ delete appConf.name;
1657
+
1658
+ delete appConf.exec_mode;
1659
+
1660
+ if (Array.isArray(appConf.watch) && appConf.watch.length === 0) {
1661
+ if (!~opts.rawArgs.indexOf('--watch'))
1662
+ delete appConf.watch
1663
+ }
1664
+
1665
+ // Options set via environment variables
1666
+ if (process.env.PM2_DEEP_MONITORING)
1667
+ appConf.deep_monitoring = true;
1668
+
1669
+ // Force deletion of defaults values set by commander
1670
+ // to avoid overriding specified configuration by user
1671
+ if (appConf.treekill === true)
1672
+ delete appConf.treekill;
1673
+ if (appConf.pmx === true)
1674
+ delete appConf.pmx;
1675
+ if (appConf.vizion === true)
1676
+ delete appConf.vizion;
1677
+ if (appConf.automation === true)
1678
+ delete appConf.automation;
1679
+ if (appConf.autostart === true)
1680
+ delete appConf.autostart;
1681
+ if (appConf.autorestart === true)
1682
+ delete appConf.autorestart;
1683
+
1684
+ return appConf;
1685
+ }
1686
+
1687
+ getProcessIdByName (name, cb) {
1688
+ var that = this;
1689
+
1690
+ this.Client.getProcessIdByName(name, function(err, id) {
1691
+ if (err) {
1692
+ Common.printError(err);
1693
+ return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
1694
+ }
1695
+ console.log(id);
1696
+ return cb ? cb(null, id) : that.exitCli(conf.SUCCESS_EXIT);
1697
+ });
1698
+ }
1699
+
1700
+ /**
1701
+ * Description
1702
+ * @method jlist
1703
+ * @param {} debug
1704
+ * @return
1705
+ */
1706
+ jlist (debug) {
1707
+ var that = this;
1708
+
1709
+ that.Client.executeRemote('getMonitorData', {}, function(err, list) {
1710
+ if (err) {
1711
+ Common.printError(err);
1712
+ return that.exitCli(conf.ERROR_EXIT);
1713
+ }
1714
+
1715
+ if (debug) {
1716
+ process.stdout.write(util.inspect(list, false, null, false));
1717
+ }
1718
+ else {
1719
+ process.stdout.write(JSON.stringify(list));
1720
+ }
1721
+
1722
+ that.exitCli(conf.SUCCESS_EXIT);
1723
+
1724
+ });
1725
+ }
1726
+
1727
+ /**
1728
+ * Display system information
1729
+ * @method slist
1730
+ * @return
1731
+ */
1732
+ slist (tree) {
1733
+ this.Client.executeRemote('getSystemData', {}, (err, sys_infos) => {
1734
+ if (err) {
1735
+ Common.err(err)
1736
+ return this.exitCli(conf.ERROR_EXIT)
1737
+ }
1738
+
1739
+ if (tree === true) {
1740
+ var treeify = require('./tools/treeify.js')
1741
+ console.log(treeify.asTree(sys_infos, true))
1742
+ }
1743
+ else
1744
+ process.stdout.write(util.inspect(sys_infos, false, null, false))
1745
+ this.exitCli(conf.SUCCESS_EXIT)
1746
+ })
1747
+ }
1748
+
1749
+ /**
1750
+ * Description
1751
+ * @method speedList
1752
+ * @return
1753
+ */
1754
+ speedList (code, apps_acted) {
1755
+ var that = this;
1756
+ var systemdata = null
1757
+ var acted = []
1758
+
1759
+ if ((code != 0 && code != null)) {
1760
+ return that.exitCli(code ? code : conf.SUCCESS_EXIT);
1761
+ }
1762
+
1763
+ if (apps_acted && apps_acted.length > 0) {
1764
+ apps_acted.forEach(proc => {
1765
+ acted.push(proc.pm2_env ? proc.pm2_env.pm_id : proc.pm_id)
1766
+ })
1767
+ }
1768
+
1769
+ // Do nothing if PM2 called programmatically and not called from CLI (also in exitCli)
1770
+ if ((conf.PM2_PROGRAMMATIC && process.env.PM2_USAGE != 'CLI'))
1771
+ return false;
1772
+
1773
+ // Best-effort host metrics snapshot (daemon-side SysMetrics collector);
1774
+ // absence just means the `host metrics` line is skipped.
1775
+ return that.Client.executeRemote('getSystemData', {}, (serrr, sdata) => {
1776
+ systemdata = sdata || null
1777
+ that.Client.executeRemote('getMonitorData', {}, (err, proc_list) => {
1778
+ doList(err, proc_list)
1779
+ })
1780
+ })
1781
+
1782
+ function doList(err, list) {
1783
+ if (err) {
1784
+ if (that.gl_retry == 0) {
1785
+ that.gl_retry += 1;
1786
+ return setTimeout(that.speedList.bind(that), 1400);
1787
+ }
1788
+ console.error('Error retrieving process list: %s.\nA process seems to be on infinite loop, retry in 5 seconds',err);
1789
+ return that.exitCli(conf.ERROR_EXIT);
1790
+ }
1791
+ if (process.stdout.isTTY === false) {
1792
+ UX.list_min(list);
1793
+ }
1794
+ else if (commander.miniList && !commander.silent)
1795
+ UX.list_min(list);
1796
+ else if (!commander.silent) {
1797
+ if (that.gl_interact_infos) {
1798
+ var dashboard_url = `https://app.pm2.io/#/r/${that.gl_interact_infos.public_key}`
1799
+
1800
+ if (that.gl_interact_infos.info_node != 'https://root.keymetrics.io') {
1801
+ dashboard_url = `${that.gl_interact_infos.info_node}/#/r/${that.gl_interact_infos.public_key}`
1802
+ }
1803
+
1804
+ Common.printOut('%s PM2+ activated | Instance Name: %s | Dash: %s',
1805
+ chalk.green.bold('⇆'),
1806
+ chalk.bold(that.gl_interact_infos.machine_name),
1807
+ chalk.bold(dashboard_url))
1808
+ }
1809
+ UX.list(list, commander, systemdata);
1810
+ //Common.printOut(chalk.white.italic(' Use `pm2 show <id|name>` to get more details about an app'));
1811
+ }
1812
+
1813
+ if (that.Client.daemon_mode == false) {
1814
+ Common.printOut('[--no-daemon] Continue to stream logs');
1815
+ Common.printOut('[--no-daemon] Exit on target PM2 exit pid=' + fs.readFileSync(conf.PM2_PID_FILE_PATH).toString());
1816
+ global._auto_exit = true;
1817
+ return that.streamLogs('all', 0, false, 'HH:mm:ss', false);
1818
+ }
1819
+ // if (process.stdout.isTTY) if looking for start logs
1820
+ else if (!process.env.TRAVIS && process.env.NODE_ENV != 'test' && acted.length > 0 && (commander.attach === true)) {
1821
+ Common.info(`Log streaming apps id: ${chalk.cyan(acted.join(' '))}, exit with Ctrl-C or will exit in 10secs`)
1822
+
1823
+ // setTimeout(() => {
1824
+ // Common.info(`Log streaming exited automatically, run 'pm2 logs' to continue watching logs`)
1825
+ // return that.exitCli(code ? code : conf.SUCCESS_EXIT);
1826
+ // }, 10000)
1827
+
1828
+ return acted.forEach((proc_name) => {
1829
+ that.streamLogs(proc_name, 0, false, null, false);
1830
+ })
1831
+ }
1832
+ else {
1833
+ return that.exitCli(code ? code : conf.SUCCESS_EXIT);
1834
+ }
1835
+ }
1836
+ }
1837
+
1838
+ /**
1839
+ * Scale up/down a process
1840
+ * @method scale
1841
+ */
1842
+ scale (app_name, number, cb) {
1843
+ var that = this;
1844
+
1845
+ function addProcs(proc, value, cb) {
1846
+ (function ex(proc, number) {
1847
+ if (number-- === 0) return cb();
1848
+ Common.printOut(conf.PREFIX_MSG + 'Scaling up application');
1849
+ that.Client.executeRemote('duplicateProcessId', proc.pm2_env.pm_id, ex.bind(this, proc, number));
1850
+ })(proc, number);
1851
+ }
1852
+
1853
+ function rmProcs(procs, value, cb) {
1854
+ var i = 0;
1855
+
1856
+ (function ex(procs, number) {
1857
+ if (number++ === 0) return cb();
1858
+ that._operate('deleteProcessId', procs[i++].pm2_env.pm_id, ex.bind(this, procs, number));
1859
+ })(procs, number);
1860
+ }
1861
+
1862
+ function end() {
1863
+ return cb ? cb(null, {success:true}) : that.speedList();
1864
+ }
1865
+
1866
+ this.Client.getProcessByName(app_name, function(err, procs) {
1867
+ if (err) {
1868
+ Common.printError(err);
1869
+ return cb ? cb(Common.retErr(err)) : that.exitCli(conf.ERROR_EXIT);
1870
+ }
1871
+
1872
+ if (!procs || procs.length === 0) {
1873
+ Common.printError(conf.PREFIX_MSG_ERR + 'Application %s not found', app_name);
1874
+ return cb ? cb(new Error('App not found')) : that.exitCli(conf.ERROR_EXIT);
1875
+ }
1876
+
1877
+ var proc_number = procs.length;
1878
+
1879
+ if (typeof(number) === 'string' && number.indexOf('+') >= 0) {
1880
+ number = parseInt(number, 10);
1881
+ return addProcs(procs[0], number, end);
1882
+ }
1883
+ else if (typeof(number) === 'string' && number.indexOf('-') >= 0) {
1884
+ number = parseInt(number, 10);
1885
+ return rmProcs(procs[0], number, end);
1886
+ }
1887
+ else {
1888
+ number = parseInt(number, 10);
1889
+ number = number - proc_number;
1890
+
1891
+ if (number < 0)
1892
+ return rmProcs(procs, number, end);
1893
+ else if (number > 0)
1894
+ return addProcs(procs[0], number, end);
1895
+ else {
1896
+ Common.printError(conf.PREFIX_MSG_ERR + 'Nothing to do');
1897
+ return cb ? cb(new Error('Same process number')) : that.exitCli(conf.ERROR_EXIT);
1898
+ }
1899
+ }
1900
+ });
1901
+ }
1902
+
1903
+ /**
1904
+ * Description
1905
+ * @method describeProcess
1906
+ * @param {} pm2_id
1907
+ * @return
1908
+ */
1909
+ describe (pm2_id, cb) {
1910
+ var that = this;
1911
+
1912
+ var found_proc = [];
1913
+
1914
+ that.Client.executeRemote('getMonitorData', {}, function(err, list) {
1915
+ if (err) {
1916
+ Common.printError('Error retrieving process list: ' + err);
1917
+ that.exitCli(conf.ERROR_EXIT);
1918
+ }
1919
+
1920
+ list.forEach(function(proc) {
1921
+ if ((!isNaN(pm2_id) && proc.pm_id == pm2_id) ||
1922
+ (typeof(pm2_id) === 'string' && proc.name == pm2_id)) {
1923
+ found_proc.push(proc);
1924
+ }
1925
+ });
1926
+
1927
+ if (found_proc.length === 0) {
1928
+ Common.printError(conf.PREFIX_MSG_WARNING + '%s doesn\'t exist', pm2_id);
1929
+ return cb ? cb(null, []) : that.exitCli(conf.ERROR_EXIT);
1930
+ }
1931
+
1932
+ if (!cb) {
1933
+ found_proc.forEach(function(proc) {
1934
+ UX.describe(proc);
1935
+ });
1936
+ }
1937
+
1938
+ return cb ? cb(null, found_proc) : that.exitCli(conf.SUCCESS_EXIT);
1939
+ });
1940
+ }
1941
+
1942
+ /**
1943
+ * API method to perform a deep update of PM2
1944
+ * @method deepUpdate
1945
+ */
1946
+ deepUpdate (cb) {
1947
+ var that = this;
1948
+
1949
+ Common.printOut(conf.PREFIX_MSG + 'Updating PM2...');
1950
+
1951
+ var child = sexec("npm i -g pm2@latest; pm2 update");
1952
+
1953
+ child.stdout.on('end', function() {
1954
+ Common.printOut(conf.PREFIX_MSG + 'PM2 successfully updated');
1955
+ cb ? cb(null, {success:true}) : that.exitCli(conf.SUCCESS_EXIT);
1956
+ });
1957
+ }
1958
+ };
1959
+
1960
+
1961
+ //////////////////////////
1962
+ // Load all API methods //
1963
+ //////////////////////////
1964
+
1965
+ require('./API/Extra.js')(API);
1966
+ require('./API/Deploy.js')(API);
1967
+ require('./API/Modules/index.js')(API);
1968
+
1969
+ require('./API/pm2-plus/link.js')(API);
1970
+ require('./API/pm2-plus/process-selector.js')(API);
1971
+ require('./API/pm2-plus/helpers.js')(API);
1972
+
1973
+ require('./API/Configuration.js')(API);
1974
+ require('./API/Version.js')(API);
1975
+ require('./API/Startup.js')(API);
1976
+ require('./API/LogManagement.js')(API);
1977
+ require('./API/Containerizer.js')(API);
1978
+
1979
+
1980
+ module.exports = API;