@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
@@ -0,0 +1,513 @@
1
+ 'use strict'
2
+
3
+ const log = require('debug')('interactor:client')
4
+ const fs = require('fs')
5
+ const path = require('path')
6
+ const rpc = require('../../pm2-axon-rpc')
7
+ const axon = require('../../pm2-axon')
8
+ const chalk = require('ansis')
9
+ const os = require('os')
10
+ const constants = require('../constants')
11
+ const childProcess = require('child_process')
12
+
13
+ const printError = function (msg) {
14
+ if (process.env.PM2_SILENT || process.env.PM2_PROGRAMMATIC) return false
15
+ if (msg instanceof Error) return console.error(msg.message)
16
+ return console.error.apply(console, arguments)
17
+ }
18
+ const printOut = function (msg) {
19
+ if (process.env.PM2_SILENT || process.env.PM2_PROGRAMMATIC) return false
20
+ return console.log.apply(console, arguments)
21
+ }
22
+
23
+ module.exports = class InteractorDaemonizer {
24
+ /**
25
+ * Ping the Interactor to see if its online
26
+ * @param {Object} opts global constants
27
+ * @param {String} opts.INTERACTOR_RPC_PORT path used to connect to the interactor
28
+ * @param {Function} cb invoked with <err, result>
29
+ */
30
+ static ping (opts, cb) {
31
+ if (typeof cb !== 'function') {
32
+ throw new Error('Missing parameters')
33
+ } else if (typeof opts !== 'object' || !opts || !opts.INTERACTOR_RPC_PORT) {
34
+ return cb(new Error('Missing parameters'))
35
+ }
36
+ const req = axon.socket('req')
37
+ const client = new rpc.Client(req)
38
+
39
+ log('[PING INTERACTOR] Trying to connect to Interactor daemon')
40
+
41
+ client.sock.once('reconnect attempt', _ => {
42
+ client.sock.close()
43
+ log('Interactor Daemon not launched')
44
+ return cb(null, false)
45
+ })
46
+
47
+ client.sock.once('connect', _ => {
48
+ client.sock.once('close', _ => {
49
+ return cb(null, true)
50
+ })
51
+ client.sock.close()
52
+ log('Interactor Daemon alive')
53
+ })
54
+
55
+ client.sock.once('error', (e) => {
56
+ if (e.code === 'EACCES') {
57
+ fs.stat(opts.INTERACTOR_RPC_PORT, (e, stats) => {
58
+ if (stats.uid === 0) {
59
+ console.error('Permission denied, activate current user')
60
+ return process.exit(1)
61
+ }
62
+ })
63
+ } else {
64
+ console.error('unexpected error')
65
+ console.error(e)
66
+ }
67
+ })
68
+
69
+ req.connect(opts.INTERACTOR_RPC_PORT)
70
+ }
71
+
72
+ /**
73
+ * Try to kill the interactor daemon via RPC
74
+ * @param {Object} conf global constants
75
+ * @param {String} conf.INTERACTOR_RPC_PORT path used to connect to the interactor
76
+ * @param {Function} cb invoked with <err>
77
+ */
78
+ static killInteractorDaemon (conf, cb) {
79
+ process.env.PM2_INTERACTOR_PROCESSING = 'true'
80
+
81
+ log('Killing interactor #1 ping')
82
+ this.ping(conf, (err, online) => {
83
+ log(`Interactor is ${!online || err ? 'offline' : 'online'}`)
84
+
85
+ if (!online || err) {
86
+ return cb ? err ? cb(err) : cb(new Error('Interactor not launched')) : printError('Interactor not launched')
87
+ }
88
+
89
+ this.launchRPC(conf, (err, data) => {
90
+ if (err) {
91
+ setTimeout(_ => {
92
+ this.disconnectRPC(cb)
93
+ }, 100)
94
+ return false
95
+ }
96
+ this.rpc.kill((err) => {
97
+ if (err) printError(err)
98
+ setTimeout(_ => {
99
+ this.disconnectRPC(cb)
100
+ }, 100)
101
+ })
102
+ return false
103
+ })
104
+ return false
105
+ })
106
+ }
107
+
108
+ /**
109
+ * Start a RPC client that connect to the InteractorDaemon
110
+ * @param {Object} conf global constants
111
+ * @param {Function} cb invoked with <err>
112
+ */
113
+ static launchRPC (conf, cb) {
114
+ const req = axon.socket('req')
115
+ this.rpc = {}
116
+ this.client = new rpc.Client(req)
117
+
118
+ log('Generating Interactor methods of RPC client')
119
+
120
+ // attach known methods to RPC client
121
+ const generateMethods = (cb) => {
122
+ this.client.methods((err, methods) => {
123
+ if (err) return cb(err)
124
+ Object.keys(methods).forEach((key) => {
125
+ let method = methods[key]
126
+ log('+ Adding %s method to interactor RPC client', method.name);
127
+ ((name) => {
128
+ let self = this
129
+ this.rpc[name] = function () {
130
+ let args = Array.prototype.slice.call(arguments)
131
+ args.unshift(name)
132
+ self.client.call.apply(self.client, args)
133
+ }
134
+ })(method.name)
135
+ })
136
+ return cb()
137
+ })
138
+ }
139
+
140
+ this.client.sock.once('reconnect attempt', (err) => {
141
+ this.client.sock.removeAllListeners()
142
+ return cb(err, { success: false, msg: 'reconnect attempt' })
143
+ })
144
+
145
+ this.client.sock.once('error', (err) => {
146
+ log('-- Error in error catch all on Interactor --', err)
147
+ return cb(err, { success: false, msg: 'reconnect attempt' })
148
+ })
149
+
150
+ this.client.sock.once('connect', () => {
151
+ this.client.sock.removeAllListeners()
152
+ generateMethods(_ => {
153
+ log('Methods of RPC client for Interaction ready.')
154
+ return cb(null, { success: true })
155
+ })
156
+ })
157
+
158
+ this.client_sock = req.connect(conf.INTERACTOR_RPC_PORT)
159
+ }
160
+
161
+ /**
162
+ * Start or Restart the Interaction Daemon depending if its online or not
163
+ * @private
164
+ * @param {Object} conf global constants
165
+ * @param {Object} infos data used to start the interactor [can be recovered from FS]
166
+ * @param {String} infos.secret_key the secret key used to cipher data
167
+ * @param {String} infos.public_key the public key used identify the user
168
+ * @param {String} infos.machine_name [optional] override name of the machine
169
+ * @param {Function} cb invoked with <err, msg, process>
170
+ */
171
+ static daemonize (cst, conf, cb) {
172
+ const InteractorJS = path.resolve(path.dirname(module.filename), 'InteractorDaemon.js')
173
+ const PM2Path = require.main.filename
174
+
175
+ // Redirect PM2 internal err and out
176
+ // to STDERR STDOUT when running with Travis
177
+ const testEnv = process.env.TRAVIS || (process.env.NODE_ENV && process.env.NODE_ENV.match(/test/))
178
+ const out = testEnv ? 1 : fs.openSync(constants.INTERACTOR_LOG_FILE_PATH, 'a')
179
+ const err = testEnv ? 2 : fs.openSync(constants.INTERACTOR_LOG_FILE_PATH, 'a')
180
+
181
+ let binary = process.execPath
182
+
183
+ if (cst.IS_BUN === true)
184
+ binary = process.execPath
185
+ else if (binary.indexOf('node') === -1)
186
+ binary = 'node'
187
+ if (process.env.NODEJS_EXECUTABLE)
188
+ binary = process.env.NODEJS_EXECUTABLE
189
+
190
+ const child = childProcess.spawn(binary, [InteractorJS], {
191
+ silent: false,
192
+ detached: true,
193
+ windowsHide: true,
194
+ cwd: process.cwd(),
195
+ env: Object.assign({
196
+ PM2_HOME: cst.PM2_HOME,
197
+ PM2_MACHINE_NAME: conf.machine_name,
198
+ PM2_SECRET_KEY: conf.secret_key,
199
+ PM2_PUBLIC_KEY: conf.public_key,
200
+ PM2_REVERSE_INTERACT: conf.reverse_interact,
201
+ PM2_BINARY_PATH: PM2Path,
202
+ KEYMETRICS_NODE: conf.info_node,
203
+ PM2_VERSION: conf.pm2_version,
204
+ DEBUG: process.env.DEBUG || 'interactor:*,-interactor:axon,-interactor:websocket,-interactor:pm2:client,-interactor:push'
205
+ }, process.env),
206
+ stdio: [null, out, err, 'ipc'], // Redirect stdout, stderr, and enable IPC
207
+ //stdio: ['ipc', out, err]
208
+ })
209
+
210
+ try {
211
+ let prevPid = fs.readFileSync(constants.INTERACTOR_PID_PATH)
212
+ prevPid = parseInt(prevPid)
213
+ process.kill(prevPid)
214
+ } catch (e) {
215
+ }
216
+
217
+ let pid = ''
218
+
219
+ if (child.pid)
220
+ pid = child.pid.toString()
221
+
222
+ fs.writeFileSync(cst.INTERACTOR_PID_PATH, pid)
223
+
224
+ child.on('close', (status) => {
225
+ if (status === constants.ERROR_EXIT) {
226
+ return cb(new Error('Agent has shutdown for unknown reason'))
227
+ }
228
+
229
+ return cb()
230
+ })
231
+
232
+ child.once('error', (err) => {
233
+ log('Error when launching Interactor, please check the agent logs')
234
+ return cb(err)
235
+ })
236
+
237
+ if (cst.IS_BUN === true) {
238
+ return cb(null, {}, child)
239
+ }
240
+
241
+ child.unref()
242
+
243
+ const timeout = setTimeout(_ => {
244
+ printOut(`${chalk.yellow('[PM2.IO][WARNING]')} Not managed to connect to PM2 Plus, retrying in background.`)
245
+ child.removeAllListeners()
246
+ if (child.disconnect)
247
+ child.disconnect()
248
+ return cb(null, {}, child)
249
+ }, 7000)
250
+
251
+ child.once('message', (msg) => {
252
+ clearTimeout(timeout)
253
+ log('Interactor daemon launched :', msg)
254
+
255
+ if (msg.log) {
256
+ return cb(null, msg, child)
257
+ }
258
+
259
+ child.removeAllListeners('error')
260
+ if (cst.IS_BUN === true)
261
+ child.removeAllListeners('close')
262
+ child.disconnect()
263
+
264
+ // Handle and show to user the different error message that can happen
265
+ if (msg.km_data && msg.km_data.error === true) {
266
+ if (!process.env.PM2_SILENT) {
267
+ console.log(chalk.red('[PM2.IO][ERROR]'), msg.km_data.msg)
268
+ console.log(chalk.cyan('[PM2.IO]') + ' Contact support contact@keymetrics.io and send us the error message')
269
+ }
270
+ return cb(msg)
271
+ } else if (msg.km_data && msg.km_data.disabled === true) {
272
+ if (!process.env.PM2_SILENT) {
273
+ console.log(chalk.cyan('[PM2.IO]') + ' Server DISABLED BY ADMINISTRATION contact support contact@keymetrics.io with reference to your public and secret keys)')
274
+ }
275
+ return cb(msg)
276
+ } else if (msg.km_data && msg.km_data.error === true) {
277
+ if (!process.env.PM2_SILENT) {
278
+ console.log('%s %s (Public: %s) (Secret: %s) (Machine name: %s)', chalk.red('[PM2.IO][ERROR]'),
279
+ msg.km_data.msg, msg.public_key, msg.secret_key, msg.machine_name)
280
+ }
281
+ return cb(msg)
282
+ } else if (msg.km_data && msg.km_data.active === false && msg.km_data.pending === true) {
283
+ if (!process.env.PM2_SILENT) {
284
+ console.log('%s You must upgrade your bucket in order to monitor more servers.', chalk.red('[PM2.IO]'))
285
+ }
286
+ return cb(msg)
287
+ }
288
+
289
+ return cb(null, msg, child)
290
+ })
291
+ }
292
+
293
+ /**
294
+ * Start or Restart the Interaction Daemon depending if its online or not
295
+ * @private
296
+ * @param {Object} conf global constants
297
+ * @param {Object} infos data used to start the interactor [can be recovered from FS]
298
+ * @param {String} infos.secret_key the secret key used to cipher data
299
+ * @param {String} infos.public_key the public key used identify the user
300
+ * @param {String} infos.machine_name [optional] override name of the machine
301
+ * @param {Function} cb invoked with <err, msg, process>
302
+ */
303
+ static launchOrAttach (conf, infos, cb) {
304
+ this.ping(conf, (err, online) => {
305
+ if (!err && online) {
306
+ log('Interactor online, restarting it...')
307
+ this.launchRPC(conf, _ => {
308
+ this.rpc.kill((ignoredErr) => {
309
+ this.daemonize(conf, infos, cb)
310
+ })
311
+ })
312
+ } else {
313
+ log('Interactor offline, launching it...')
314
+ this.daemonize(conf, infos, cb)
315
+ }
316
+ })
317
+ }
318
+
319
+ /**
320
+ * Restart the Interactor Daemon
321
+ * @param {Object} conf global constants
322
+ * @param {Function} cb invoked with <err, msg>
323
+ */
324
+ static update (conf, cb) {
325
+ this.ping(conf, (err, online) => {
326
+ if (err || !online) {
327
+ return cb ? cb(new Error('Interactor not launched')) : printError('Interactor not launched')
328
+ }
329
+ this.launchRPC(conf, _ => {
330
+ this.rpc.kill((err) => {
331
+ if (err) {
332
+ return cb ? cb(err) : printError(err)
333
+ }
334
+ printOut('Interactor successfully killed')
335
+ setTimeout(_ => {
336
+ this.launchAndInteract(conf, {}, _ => {
337
+ return cb(null, { msg: 'Daemon launched' })
338
+ })
339
+ }, 500)
340
+ })
341
+ })
342
+ })
343
+ }
344
+
345
+ /**
346
+ * Retrieve Interactor configuration from env, params and filesystem.
347
+ * @param {Object} cst global constants
348
+ * @param {Object} infos data used to start the interactor [optional]
349
+ * @param {String} infos.secret_key the secret key used to cipher data [optional]
350
+ * @param {String} infos.public_key the public key used identify the user [optional]
351
+ * @param {String} infos.machine_name override name of the machine [optional]
352
+ * @param {Function} cb invoked with <err, configuration>
353
+ */
354
+ static getOrSetConf (cst, infos, cb) {
355
+ infos = infos || {}
356
+ let configuration = {
357
+ version_management: {
358
+ active: true
359
+ }
360
+ }
361
+ let confFS = {}
362
+
363
+ // Try loading configuration file on FS
364
+ try {
365
+ let fileContent = fs.readFileSync(cst.INTERACTION_CONF).toString()
366
+ // Handle old configuration with json5
367
+ fileContent = fileContent.replace(/\s(\w+):/g, '"$1":')
368
+ // parse
369
+ confFS = JSON.parse(fileContent)
370
+
371
+ if (confFS.version_management) {
372
+ configuration.version_management.active = confFS.version_management.active
373
+ }
374
+ } catch (e) {
375
+ log('Interaction file does not exists')
376
+ }
377
+
378
+ // load the configration (first have priority)
379
+ // -> from env variable
380
+ // -> from params (eg. CLI)
381
+ // -> from configuration on FS
382
+ configuration.public_key = process.env.PM2_PUBLIC_KEY || process.env.KEYMETRICS_PUBLIC || infos.public_key || confFS.public_key
383
+ configuration.secret_key = process.env.PM2_SECRET_KEY || process.env.KEYMETRICS_SECRET || infos.secret_key || confFS.secret_key
384
+ configuration.machine_name = process.env.PM2_MACHINE_NAME || process.env.INSTANCE_NAME || infos.machine_name || confFS.machine_name || `${os.hostname()}-${require('crypto').randomBytes(2).toString('hex')}`
385
+ configuration.pm2_version = process.env.PM2_VERSION || infos.pm2_version || confFS.pm2_version
386
+ configuration.reverse_interact = confFS.reverse_interact || true
387
+ // is setup empty ? use the one provided in env OR root OTHERWISE get the one on FS conf OR fallback on root
388
+ configuration.info_node = process.env.KEYMETRICS_NODE || infos.info_node || confFS.info_node || cst.KEYMETRICS_ROOT_URL
389
+
390
+
391
+ if (!configuration.secret_key) {
392
+ log('Secret key is not defined in configuration', configuration)
393
+ return cb(new Error('secret key is not defined'))
394
+ }
395
+ if (!configuration.public_key) {
396
+ log('Public key is not defined in configuration', configuration)
397
+ return cb(new Error('public key is not defined'))
398
+ }
399
+
400
+ // write configuration on FS
401
+ try {
402
+ fs.writeFileSync(cst.INTERACTION_CONF, JSON.stringify(configuration, null, 4))
403
+ } catch (e) {
404
+ console.error('Error when writting configuration file %s', cst.INTERACTION_CONF)
405
+ return cb(e)
406
+ }
407
+ if (configuration.info_node.indexOf('http') === -1) { // handle old file
408
+ configuration.info_node = `https://${configuration.info_node}`
409
+ }
410
+ return cb(null, configuration)
411
+ }
412
+
413
+ /**
414
+ * Disconnect the RPC client from Interactor Daemon
415
+ * @param {Function} cb invoked with <err, msg>
416
+ */
417
+ static disconnectRPC (cb) {
418
+ log('Disconnect RPC')
419
+ if (!this.client_sock || !this.client_sock.close) {
420
+ log('RPC not launched')
421
+ return cb(null, {
422
+ success: false,
423
+ msg: 'RPC connection to Interactor Daemon is not launched'
424
+ })
425
+ }
426
+
427
+ if (this.client_sock.closing === true) {
428
+ log('RPC already closed')
429
+ return cb(null, {
430
+ success: false,
431
+ msg: 'RPC closed'
432
+ })
433
+ }
434
+
435
+ try {
436
+ let timer
437
+
438
+ log('Closing RPC INTERACTOR')
439
+
440
+ this.client_sock.once('close', _ => {
441
+ log('RPC INTERACTOR cleanly closed')
442
+ clearTimeout(timer)
443
+ return cb ? cb(null, { success: true }) : false
444
+ })
445
+
446
+ timer = setTimeout(_ => {
447
+ if (this.client_sock.destroy) {
448
+ this.client_sock.destroy()
449
+ }
450
+ return cb ? cb(null, { success: true }) : false
451
+ }, 200)
452
+
453
+ this.client_sock.close()
454
+ } catch (err) {
455
+ log('Error while closing RPC INTERACTOR : %s', err.message || err)
456
+ return cb ? cb(err) : false
457
+ }
458
+ }
459
+
460
+ /**
461
+ * Start the Interactor Daemon
462
+ * @param {Object} cst global constants
463
+ * @param {Object} infos data used to start the interactor [can be recovered from FS]
464
+ * @param {String} infos.secret_key the secret key used to cipher data
465
+ * @param {String} infos.public_key the public key used identify the user
466
+ * @param {String} infos.machine_name [optional] override name of the machine
467
+ * @param {Function} cb invoked with <err, msg, process>
468
+ */
469
+ static launchAndInteract (cst, opts, cb) {
470
+ // For Watchdog
471
+ if (process.env.PM2_AGENT_ONLINE) {
472
+ return cb()
473
+ }
474
+
475
+ process.env.PM2_INTERACTOR_PROCESSING = 'true'
476
+
477
+ this.getOrSetConf(Object.assign(cst, constants), opts, (err, conf) => {
478
+ if (err || !conf) return cb(err || new Error('Cant retrieve configuration'))
479
+
480
+ if (!process.env.PM2_SILENT) {
481
+ console.log(chalk.cyan('[PM2 I/O]') + ' Using: Public key: %s | Private key: %s | Machine name: %s', conf.public_key, conf.secret_key, conf.machine_name)
482
+ }
483
+ return this.launchOrAttach(cst, conf, cb)
484
+ })
485
+ }
486
+
487
+ /**
488
+ * Retrieve configuration used by the Interaction Daemon
489
+ * @param {Object} cst global constants
490
+ * @param {Function} cb invoked with <err, data>
491
+ */
492
+ static getInteractInfo (cst, cb) {
493
+ log('Getting interaction info')
494
+ if (process.env.PM2_NO_INTERACTION) return cb(new Error('PM2_NO_INTERACTION set'))
495
+
496
+ this.ping(cst, (err, online) => {
497
+ if (err || !online) return cb(new Error('Interactor is offline'))
498
+
499
+ this.launchRPC(cst, _ => {
500
+ this.rpc.getInfos((err, infos) => {
501
+ if (err) return cb(err)
502
+
503
+ // Avoid general CLI to interfere with Keymetrics CLI commands
504
+ if (process.env.PM2_INTERACTOR_PROCESSING) return cb(null, infos)
505
+
506
+ this.disconnectRPC(() => {
507
+ return cb(null, infos)
508
+ })
509
+ })
510
+ })
511
+ })
512
+ }
513
+ }