@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,375 @@
1
+ /**
2
+ * Copyright 2013-present the PM2 project authors. All rights reserved.
3
+ * Use of this source code is governed by a license that
4
+ * can be found in the LICENSE file.
5
+ */
6
+
7
+ /**
8
+ * SysMetrics — minimal, dependency-free host metrics collector.
9
+ *
10
+ * Replaces the `systeminformation` / `pm2-sysmonit` pair for the metrics
11
+ * `pm2 ls` displays. Linux & macOS only (other platforms get the os-module
12
+ * subset). Design constraints:
13
+ *
14
+ * - No shell: `os`/`fs` for everything possible, `execFile` (never `exec`,
15
+ * never `/bin/sh`) with a hard timeout for the few macOS-only items.
16
+ * This structurally removes the entire `systeminformation` command
17
+ * injection (CWE-78) class.
18
+ * - Interface names come from `os.networkInterfaces()` and are validated
19
+ * against a strict whitelist before being passed as an argv (never a
20
+ * shell string).
21
+ * - Every collector is isolated: a failure yields a missing key, never a
22
+ * throw — the daemon must not crash on a parse error.
23
+ *
24
+ * Testability: `create()` returns an isolated collector instance with its
25
+ * own delta state, exposing both `collect()` and each sub-collector
26
+ * (`cpuUsage`, `ram`, `net`, `diskIO`, `fsUsage`). Tests exercise the real
27
+ * `os`/`fs`/`execFile` calls — no mocking — and assert shape + sane ranges.
28
+ * `module.exports` is a ready singleton (used by the daemon Worker);
29
+ * `module.exports.create` builds a fresh one for tests.
30
+ *
31
+ * `collect()` returns a Promise resolving to an object shaped like a pmx
32
+ * `axm_monitor` map (`{ '<Name>': { value, unit } }`) and also invokes an
33
+ * optional callback, so the existing `pm2 ls` renderer consumes it
34
+ * unchanged.
35
+ */
36
+
37
+ const os = require('os')
38
+ const fs = require('fs')
39
+ const { execFile } = require('child_process')
40
+
41
+ const PLATFORM = process.platform
42
+ // openharmony runs a Linux kernel with a readable procfs (/proc/meminfo,
43
+ // /proc/net/dev, /sys/block/*/stat), so it routes through the linux collectors.
44
+ const IS_LINUX = PLATFORM === 'linux' || PLATFORM === 'openharmony'
45
+ const IS_DARWIN = PLATFORM === 'darwin'
46
+
47
+ // Only ever passed as an argv element, never interpolated into a shell.
48
+ const IFACE_RE = /^[A-Za-z0-9._-]+$/
49
+
50
+ const EXEC_OPTS = { timeout: 2000, maxBuffer: 1024 * 1024, windowsHide: true }
51
+
52
+ function execFileP (bin, args) {
53
+ return new Promise((resolve) => {
54
+ try {
55
+ execFile(bin, args, EXEC_OPTS, (err, stdout) => resolve(err ? null : stdout.toString()))
56
+ } catch (e) {
57
+ resolve(null)
58
+ }
59
+ })
60
+ }
61
+
62
+ function metric (value, unit) {
63
+ return { value: value, type: 'metric', unit: unit, historic: true }
64
+ }
65
+
66
+ /**
67
+ * Build an isolated collector with its own previous-sample state.
68
+ * @returns {{collect:Function, cpuUsage:Function, ram:Function, net:Function, diskIO:Function, fsUsage:Function, state:Function}}
69
+ */
70
+ function create () {
71
+ // Previous sample, for rate/percent deltas between collect() calls.
72
+ var prev = { ts: 0, cpu: null, net: {}, disk: null }
73
+
74
+ /**
75
+ * Aggregate CPU busy % between two os.cpus() snapshots.
76
+ */
77
+ function cpuUsage () {
78
+ var cpus = os.cpus() || []
79
+ var idle = 0
80
+ var total = 0
81
+ cpus.forEach(function (c) {
82
+ var t = c.times
83
+ idle += t.idle
84
+ total += t.user + t.nice + t.sys + t.idle + t.irq
85
+ })
86
+
87
+ var pct = 0
88
+ if (prev.cpu) {
89
+ var dIdle = idle - prev.cpu.idle
90
+ var dTotal = total - prev.cpu.total
91
+ pct = dTotal > 0 ? (1 - dIdle / dTotal) * 100 : 0
92
+ }
93
+ prev.cpu = { idle: idle, total: total }
94
+ return Math.max(0, Math.min(100, pct))
95
+ }
96
+
97
+ /**
98
+ * RAM. Returns { total, available, active } in bytes + usagePct.
99
+ */
100
+ async function ram () {
101
+ var total = os.totalmem()
102
+ var free = os.freemem()
103
+ var active = total - free
104
+ var available = free
105
+
106
+ if (IS_LINUX) {
107
+ try {
108
+ var mi = fs.readFileSync('/proc/meminfo', 'utf8')
109
+ var get = function (k) {
110
+ var m = mi.match(new RegExp('^' + k + ':\\s+(\\d+)', 'm'))
111
+ return m ? parseInt(m[1], 10) * 1024 : null
112
+ }
113
+ var memAvail = get('MemAvailable')
114
+ if (memAvail != null) {
115
+ available = memAvail
116
+ active = total - memAvail
117
+ }
118
+ } catch (e) { /* fall back to os values */ }
119
+ } else if (IS_DARWIN) {
120
+ var ps = await execFileP('sysctl', ['-n', 'vm.pagesize'])
121
+ var pageSize = parseInt((ps || '').trim(), 10) || 4096
122
+ var vm = await execFileP('vm_stat', [])
123
+ if (vm) {
124
+ var ma = vm.match(/Pages active:\s+(\d+)/)
125
+ var mi2 = vm.match(/Pages inactive:\s+(\d+)/)
126
+ if (ma) active = parseInt(ma[1], 10) * pageSize
127
+ var inactive = mi2 ? parseInt(mi2[1], 10) * pageSize : 0
128
+ available = (total - active) + inactive
129
+ }
130
+ }
131
+
132
+ var usagePct = total > 0 ? (active / total) * 100 : 0
133
+ return { total: total, available: available, active: active, usagePct: usagePct }
134
+ }
135
+
136
+ /**
137
+ * Per-interface cumulative counters: { rx, tx, rxErr, txErr, rxDrop, txDrop }.
138
+ */
139
+ function readLinuxNet (name) {
140
+ var base = '/sys/class/net/' + name + '/statistics/'
141
+ try {
142
+ var rd = function (f) { return parseInt(fs.readFileSync(base + f, 'utf8').trim(), 10) || 0 }
143
+ return {
144
+ rx: rd('rx_bytes'), tx: rd('tx_bytes'),
145
+ rxErr: rd('rx_errors'), txErr: rd('tx_errors'),
146
+ rxDrop: rd('rx_dropped'), txDrop: rd('tx_dropped')
147
+ }
148
+ } catch (e) {
149
+ return null
150
+ }
151
+ }
152
+
153
+ async function readDarwinNet (name) {
154
+ // netstat -bdnI <iface> : <iface> is argv, validated by IFACE_RE.
155
+ var out = await execFileP('netstat', ['-bdnI', name])
156
+ if (!out) return null
157
+ var lines = out.split('\n')
158
+ if (lines.length < 2 || lines[1].trim() === '') return null
159
+ var s = lines[1].replace(/ +/g, ' ').trim().split(' ')
160
+ var o = s.length > 11 ? 1 : 0
161
+ var n = function (i) { return parseInt(s[o + i], 10) || 0 }
162
+ // Column layout mirrors systeminformation's proven netstat parser.
163
+ return {
164
+ rx: n(5), tx: n(8),
165
+ rxErr: n(4), txErr: n(7),
166
+ rxDrop: n(10), txDrop: n(10)
167
+ }
168
+ }
169
+
170
+ async function net () {
171
+ var names = Object.keys(os.networkInterfaces()).filter(function (n) { return IFACE_RE.test(n) })
172
+ var out = {}
173
+ for (var i = 0; i < names.length; i++) {
174
+ var name = names[i]
175
+ var c = IS_LINUX ? readLinuxNet(name) : (IS_DARWIN ? await readDarwinNet(name) : null)
176
+ if (c) out[name] = c
177
+ }
178
+ return out
179
+ }
180
+
181
+ /**
182
+ * Total disk throughput cumulative counters: { read, write } in bytes.
183
+ */
184
+ function readLinuxDisk () {
185
+ try {
186
+ var read = 0
187
+ var write = 0
188
+ var devs = fs.readdirSync('/sys/block')
189
+ devs.forEach(function (d) {
190
+ if (/^(loop|ram|dm-|fd)/.test(d)) return
191
+ try {
192
+ var st = fs.readFileSync('/sys/block/' + d + '/stat', 'utf8').trim().replace(/ +/g, ' ').split(' ')
193
+ // Linux block stat: [2]=read sectors, [6]=write sectors, 512B each.
194
+ read += (parseInt(st[2], 10) || 0) * 512
195
+ write += (parseInt(st[6], 10) || 0) * 512
196
+ } catch (e) { /* skip device */ }
197
+ })
198
+ return { read: read, write: write }
199
+ } catch (e) {
200
+ return null
201
+ }
202
+ }
203
+
204
+ async function readDarwinDisk () {
205
+ var out = await execFileP('ioreg', ['-c', 'IOBlockStorageDriver', '-k', 'Statistics', '-r', '-w0'])
206
+ if (!out) return null
207
+ var read = 0
208
+ var write = 0
209
+ var re = /"Bytes \((Read|Write)\)"=(\d+)/g
210
+ var m
211
+ while ((m = re.exec(out)) !== null) {
212
+ if (m[1] === 'Read') read += parseInt(m[2], 10)
213
+ else write += parseInt(m[2], 10)
214
+ }
215
+ return { read: read, write: write }
216
+ }
217
+
218
+ function diskIO () {
219
+ if (IS_LINUX) return Promise.resolve(readLinuxDisk())
220
+ if (IS_DARWIN) return readDarwinDisk()
221
+ return Promise.resolve(null)
222
+ }
223
+
224
+ /**
225
+ * Per-filesystem usage. Returns [{ mount, usePct, sizeGb }].
226
+ */
227
+ /**
228
+ * Mount points mounted read-only (disk images, sealed system volumes,
229
+ * squashfs/snap...). Their usage is fixed and never actionable, so the
230
+ * renderer would only ever show a false "disk nearly full" alarm.
231
+ */
232
+ async function readOnlyMounts () {
233
+ var out = await execFileP('mount', [])
234
+ var ro = {}
235
+ if (!out) return ro
236
+ out.split('\n').forEach(function (line) {
237
+ // linux: /dev/x on /mnt type ext4 (ro,relatime)
238
+ // darwin: /dev/x on /mnt (apfs, local, read-only, journaled)
239
+ var m = /^\S+ on (.+?) (?:type \S+ )?\((.*)\)\s*$/.exec(line)
240
+ if (!m) return
241
+ var opts = m[2].split(',').map(function (o) { return o.trim() })
242
+ if (opts.indexOf('ro') !== -1 || opts.indexOf('read-only') !== -1) ro[m[1]] = true
243
+ })
244
+ return ro
245
+ }
246
+
247
+ async function fsUsage () {
248
+ if (!IS_LINUX && !IS_DARWIN) return []
249
+ var out = await execFileP('df', ['-kP'])
250
+ if (!out) return []
251
+ var ro = await readOnlyMounts().catch(function () { return {} })
252
+ var lines = out.split('\n')
253
+ var res = []
254
+ for (var i = 1; i < lines.length; i++) {
255
+ var p = lines[i].replace(/ +/g, ' ').trim().split(' ')
256
+ if (p.length < 6) continue
257
+ var mount = p.slice(5).join(' ')
258
+ // Real devices only, plus the root fs which may be a virtual device
259
+ // (overlay in containers) and is always the one that matters
260
+ if (p[0].indexOf('/dev/') !== 0 && mount !== '/') continue
261
+ var sizeKb = parseInt(p[1], 10) || 0
262
+ var usedKb = parseInt(p[2], 10) || 0
263
+ var availKb = parseInt(p[3], 10) || 0
264
+ if (ro[mount]) continue
265
+ var denom = usedKb + availKb
266
+ if (denom <= 0) continue
267
+ res.push({
268
+ mount: mount,
269
+ usePct: parseFloat(((usedKb / denom) * 100).toFixed(2)),
270
+ sizeGb: parseFloat((sizeKb / 1024 / 1024).toFixed(2))
271
+ })
272
+ }
273
+ return res
274
+ }
275
+
276
+ /**
277
+ * Turn collected samples into the axm_monitor-shaped map, applying
278
+ * deltas against the previous sample. Pure given inputs + `prev`.
279
+ */
280
+ function buildSnapshot (cpu, mem, netCur, disk, fss, now) {
281
+ var dt = prev.ts > 0 ? (now - prev.ts) / 1000 : 0
282
+ var m = {}
283
+
284
+ if (cpu !== null && cpu !== undefined) m['CPU Usage'] = metric(parseFloat(cpu.toFixed(1)), '%')
285
+ // Always present so the (historically unguarded) renderer never throws;
286
+ // -1 == unknown.
287
+ m['CPU Temperature'] = metric(-1, '°C')
288
+
289
+ if (mem) {
290
+ m['RAM Usage'] = metric(parseFloat(mem.usagePct.toFixed(1)), '%')
291
+ m['RAM Total'] = metric(mem.total, 'b')
292
+ m['RAM Available'] = metric(mem.available, 'b')
293
+ m['RAM Active'] = metric(mem.active, 'b')
294
+ }
295
+
296
+ // Network: cumulative counters -> per-second / per-minute rates.
297
+ Object.keys(netCur || {}).forEach(function (name) {
298
+ var c = netCur[name]
299
+ var p = prev.net[name]
300
+ var rxMb = 0, txMb = 0, rxErr = 0, txErr = 0, rxDrop = 0, txDrop = 0
301
+ if (p && dt > 0) {
302
+ rxMb = Math.max(0, (c.rx - p.rx)) / dt / 1024 / 1024
303
+ txMb = Math.max(0, (c.tx - p.tx)) / dt / 1024 / 1024
304
+ rxErr = Math.max(0, (c.rxErr - p.rxErr)) / dt * 60
305
+ txErr = Math.max(0, (c.txErr - p.txErr)) / dt * 60
306
+ rxDrop = Math.max(0, (c.rxDrop - p.rxDrop)) / dt * 60
307
+ txDrop = Math.max(0, (c.txDrop - p.txDrop)) / dt * 60
308
+ }
309
+ m['net:rx_5:' + name] = metric(parseFloat(rxMb.toFixed(3)), 'mb/s')
310
+ m['net:tx_5:' + name] = metric(parseFloat(txMb.toFixed(3)), 'mb/s')
311
+ m['net:rx_errors_60:' + name] = metric(Math.round(rxErr), '/min')
312
+ m['net:tx_errors_60:' + name] = metric(Math.round(txErr), '/min')
313
+ m['net:rx_dropped_60:' + name] = metric(Math.round(rxDrop), '/min')
314
+ m['net:tx_dropped_60:' + name] = metric(Math.round(txDrop), '/min')
315
+ })
316
+ prev.net = netCur || {}
317
+
318
+ // Disk I/O: cumulative bytes -> mb/s.
319
+ var dRead = 0, dWrite = 0
320
+ if (disk && prev.disk && dt > 0) {
321
+ dRead = Math.max(0, (disk.read - prev.disk.read)) / dt / 1024 / 1024
322
+ dWrite = Math.max(0, (disk.write - prev.disk.write)) / dt / 1024 / 1024
323
+ }
324
+ m['Disk Reads'] = metric(parseFloat(dRead.toFixed(3)), 'mb/s')
325
+ m['Disk Writes'] = metric(parseFloat(dWrite.toFixed(3)), 'mb/s')
326
+ if (disk) prev.disk = disk
327
+
328
+ ;(fss || []).forEach(function (f) {
329
+ m['fs:use:' + f.mount] = metric(f.usePct, '%')
330
+ m['fs:size:' + f.mount] = metric(f.sizeGb, 'gb')
331
+ })
332
+
333
+ prev.ts = now
334
+ return m
335
+ }
336
+
337
+ /**
338
+ * Collect one snapshot.
339
+ * @param {Function} [cb] optional cb(axm_monitor) — also returned via Promise.
340
+ * @returns {Promise<Object>}
341
+ */
342
+ function collect (cb) {
343
+ return Promise.all([
344
+ Promise.resolve().then(cpuUsage).catch(function () { return null }),
345
+ ram().catch(function () { return null }),
346
+ net().catch(function () { return {} }),
347
+ diskIO().catch(function () { return null }),
348
+ fsUsage().catch(function () { return [] })
349
+ ]).then(function (r) {
350
+ var m = buildSnapshot(r[0], r[1], r[2], r[3], r[4], Date.now())
351
+ if (cb) cb(m)
352
+ return m
353
+ }).catch(function () {
354
+ if (cb) cb({})
355
+ return {}
356
+ })
357
+ }
358
+
359
+ return {
360
+ collect: collect,
361
+ cpuUsage: cpuUsage,
362
+ ram: ram,
363
+ net: net,
364
+ diskIO: diskIO,
365
+ fsUsage: fsUsage,
366
+ // Inspect/reset delta state (tests only).
367
+ state: function () { return prev }
368
+ }
369
+ }
370
+
371
+ // Default singleton used by the daemon Worker; `.create()` for isolated tests.
372
+ var singleton = create()
373
+ singleton.create = create
374
+
375
+ module.exports = singleton
@@ -0,0 +1,101 @@
1
+ var fs = require('fs');
2
+ var path = require('path');
3
+ /*
4
+ options: {
5
+ utimes: false, // Boolean | Object, keep utimes if true
6
+ mode: false, // Boolean | Number, keep file mode if true
7
+ cover: true, // Boolean, cover if file exists
8
+ filter: true, // Boolean | Function, file filter
9
+ }
10
+ */
11
+ function copydirSync(from, to, options) {
12
+ if (typeof options === 'function') {
13
+ options = {
14
+ filter: options
15
+ };
16
+ }
17
+ if(typeof options === 'undefined') options = {};
18
+ if(typeof options.cover === 'undefined') {
19
+ options.cover = true;
20
+ }
21
+ options.filter = typeof options.filter === 'function' ? options.filter : function(state, filepath, filename) {
22
+ return options.filter;
23
+ };
24
+ var stats = fs.lstatSync(from);
25
+ var statsname = stats.isDirectory() ? 'directory' :
26
+ stats.isFile() ? 'file' :
27
+ stats.isSymbolicLink() ? 'symbolicLink' :
28
+ '';
29
+ var valid = options.filter(statsname, from, path.dirname(from), path.basename(from));
30
+
31
+ if (statsname === 'directory' || statsname === 'symbolicLink') {
32
+ // Directory or SymbolicLink
33
+ if(valid) {
34
+ try {
35
+ fs.statSync(to);
36
+ } catch(err) {
37
+ if(err.code === 'ENOENT') {
38
+ fs.mkdirSync(to, { recursive: true });
39
+ options.debug && console.log('>> ' + to);
40
+ } else {
41
+ throw err;
42
+ }
43
+ }
44
+ rewriteSync(to, options, stats);
45
+ if (statsname != 'symbolicLink')
46
+ listDirectorySync(from, to, options);
47
+ }
48
+ } else if(stats.isFile()) {
49
+ // File
50
+ if(valid) {
51
+ if(options.cover) {
52
+ writeFileSync(from, to, options, stats);
53
+ } else {
54
+ try {
55
+ fs.statSync(to);
56
+ } catch(err) {
57
+ if(err.code === 'ENOENT') {
58
+ writeFileSync(from, to, options, stats);
59
+ } else {
60
+ throw err;
61
+ }
62
+ }
63
+ }
64
+ }
65
+ } else {
66
+ throw new Error('stats invalid: '+ from);
67
+ }
68
+ };
69
+
70
+ function listDirectorySync(from, to, options) {
71
+ var files = fs.readdirSync(from);
72
+ copyFromArraySync(files, from, to, options);
73
+ }
74
+
75
+ function copyFromArraySync(files, from, to, options) {
76
+ if(files.length === 0) return true;
77
+ var f = files.shift();
78
+ copydirSync(path.join(from, f), path.join(to, f), options);
79
+ copyFromArraySync(files, from, to, options);
80
+ }
81
+
82
+ function writeFileSync(from, to, options, stats) {
83
+ fs.writeFileSync(to, fs.readFileSync(from, 'binary'), 'binary');
84
+ options.debug && console.log('>> ' + to);
85
+ rewriteSync(to, options, stats);
86
+ }
87
+
88
+ function rewriteSync(f, options, stats, callback) {
89
+ if(options.cover) {
90
+ var mode = options.mode === true ? stats.mode : options.mode;
91
+ var utimes = options.utimes === true ? {
92
+ atime: stats.atime,
93
+ mtime: stats.mtime
94
+ } : options.utimes;
95
+ mode && fs.chmodSync(f, mode);
96
+ utimes && fs.utimesSync(f, utimes.atime, utimes.mtime);
97
+ }
98
+ return true;
99
+ }
100
+
101
+ module.exports = copydirSync;
@@ -0,0 +1,19 @@
1
+
2
+ const fs = require('fs');
3
+ const Path = require('path');
4
+
5
+ const deleteFolderRecursive = function(path) {
6
+ if (fs.existsSync(path)) {
7
+ fs.readdirSync(path).forEach((file, index) => {
8
+ const curPath = Path.join(path, file);
9
+ if (fs.lstatSync(curPath).isDirectory()) { // recurse
10
+ deleteFolderRecursive(curPath);
11
+ } else { // delete file
12
+ fs.unlinkSync(curPath);
13
+ }
14
+ });
15
+ fs.rmdirSync(path);
16
+ }
17
+ };
18
+
19
+ module.exports = deleteFolderRecursive
@@ -0,0 +1,74 @@
1
+ 'use strict';
2
+
3
+ var path = require('path')
4
+ , fs = require('fs');
5
+
6
+ /**
7
+ * Attempt to somewhat safely parse the JSON.
8
+ *
9
+ * @param {String} data JSON blob that needs to be parsed.
10
+ * @returns {Object|false} Parsed JSON or false.
11
+ * @api private
12
+ */
13
+ function parse(data) {
14
+ data = data.toString('utf-8');
15
+
16
+ //
17
+ // Remove a possible UTF-8 BOM (byte order marker) as this can lead to parse
18
+ // values when passed in to the JSON.parse.
19
+ //
20
+ if (data.charCodeAt(0) === 0xFEFF) data = data.slice(1);
21
+
22
+ try { return JSON.parse(data); }
23
+ catch (e) { return false; }
24
+ }
25
+
26
+ /**
27
+ * Find package.json files.
28
+ *
29
+ * @param {String|Object} root The root directory we should start searching in.
30
+ * @returns {Object} Iterator interface.
31
+ * @api public
32
+ */
33
+ module.exports = function find(root) {
34
+ root = root || process.cwd();
35
+ if (typeof root !== "string") {
36
+ if (typeof root === "object" && typeof root.filename === 'string') {
37
+ root = root.filename;
38
+ } else {
39
+ throw new Error("Must pass a filename string or a module object to finder");
40
+ }
41
+ }
42
+ return {
43
+ /**
44
+ * Return the parsed package.json that we find in a parent folder.
45
+ *
46
+ * @returns {Object} Value, filename and indication if the iteration is done.
47
+ * @api public
48
+ */
49
+ next: function next() {
50
+ if (root.match(/^(\w:\\|\/)$/)) return {
51
+ value: undefined,
52
+ filename: undefined,
53
+ done: true
54
+ };
55
+
56
+ var file = path.join(root, 'package.json')
57
+ , data;
58
+
59
+ root = path.resolve(root, '..');
60
+
61
+ if (fs.existsSync(file) && (data = parse(fs.readFileSync(file)))) {
62
+ data.__path = file;
63
+
64
+ return {
65
+ value: data,
66
+ filename: file,
67
+ done: false
68
+ };
69
+ }
70
+
71
+ return next();
72
+ }
73
+ };
74
+ };
@@ -0,0 +1,72 @@
1
+ // --------------------------------------------------------------------------------------------------------------------
2
+ //
3
+ // fmt.js - Command line output formatting.
4
+ //
5
+ // Copyright (c) 2012 Andrew Chilton - http://chilts.org/
6
+ // Written by Andrew Chilton <andychilton@gmail.com>
7
+ //
8
+ // License: http://opensource.org/licenses/MIT
9
+ //
10
+ // --------------------------------------------------------------------------------------------------------------------
11
+
12
+ var util = require('util');
13
+
14
+ // --------------------------------------------------------------------------------------------------------------------
15
+
16
+ var sep = '===============================================================================';
17
+ var line = '-------------------------------------------------------------------------------';
18
+ var field = ' ';
19
+
20
+ // --------------------------------------------------------------------------------------------------------------------
21
+
22
+ // separator
23
+ module.exports.separator = function() {
24
+ console.log(sep);
25
+ };
26
+
27
+ // alias the above
28
+ module.exports.sep = module.exports.separator;
29
+
30
+ // line
31
+ module.exports.line = function() {
32
+ console.log(line);
33
+ };
34
+
35
+ // title
36
+ module.exports.title = function(title) {
37
+ var out = '--- ' + title + ' ';
38
+ out += line.substr(out.length);
39
+ console.log(out);
40
+ };
41
+
42
+ // field
43
+ module.exports.field = function(key, value) {
44
+ console.log('' + key + field.substr(key.length) + ' : ' + value);
45
+ };
46
+
47
+ // subfield
48
+ module.exports.subfield = function(key, value) {
49
+ console.log('- ' + key + field.substr(key.length + 2) + ' : ' + value);
50
+ };
51
+
52
+ // list item
53
+ module.exports.li = function(msg) {
54
+ console.log('* ' + msg);
55
+ };
56
+
57
+ // dump
58
+ module.exports.dump = function(data, name) {
59
+ if ( name ) {
60
+ console.log(name + ' :', util.inspect(data, false, null, true));
61
+ }
62
+ else {
63
+ console.log(util.inspect(data, false, null, true));
64
+ }
65
+ };
66
+
67
+ // msg
68
+ module.exports.msg = function(msg) {
69
+ console.log(msg);
70
+ };
71
+
72
+ // --------------------------------------------------------------------------------------------------------------------