@rocket.chat/houston 0.27.0-next.3 → 2.1.8

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 (293) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +108 -15
  3. package/bin/houston +62 -0
  4. package/data/docs/ARCHITECTURE.md +387 -0
  5. package/data/docs/automation.md +107 -0
  6. package/data/docs/e2ee.md +76 -0
  7. package/data/docs/eks.md +258 -0
  8. package/data/docs/gui.md +282 -0
  9. package/data/docs/guide.md +669 -0
  10. package/data/docs/kubernetes.md +138 -0
  11. package/data/docs/troubleshooting.md +193 -0
  12. package/data/docs/upgrading.md +84 -0
  13. package/data/docs/voice.md +253 -0
  14. package/data/iam/engineer-policy.json +11 -0
  15. package/data/iam/engineer-rbac.yaml +42 -0
  16. package/data/iam/operator-policy.json +211 -0
  17. package/data/loadtest/badbot.js +22 -0
  18. package/data/loadtest/common.js +168 -0
  19. package/data/loadtest/custom.js +20 -0
  20. package/data/loadtest/journey.js +58 -0
  21. package/data/loadtest/login.js +18 -0
  22. package/data/loadtest/messages.js +13 -0
  23. package/data/loadtest/mixed.js +39 -0
  24. package/data/loadtest/read.js +12 -0
  25. package/data/loadtest/webhook.js +20 -0
  26. package/data/monitoring/houston-logs.json +98 -0
  27. package/data/monitoring/k6-loadtest.json +610 -0
  28. package/data/monitoring/mongodb-exporter.json +3007 -0
  29. package/data/monitoring/node-exporter-full.json +16114 -0
  30. package/data/monitoring/rocketchat-metrics.json +6471 -0
  31. package/data/presets/airgapped.yaml +16 -0
  32. package/data/presets/default.yaml +9 -0
  33. package/data/seed/avatar-0.png +0 -0
  34. package/data/seed/avatar-1.png +0 -0
  35. package/data/seed/avatar-2.png +0 -0
  36. package/data/seed/avatar-3.png +0 -0
  37. package/data/seed/avatar-4.png +0 -0
  38. package/data/seed/avatar-5.png +0 -0
  39. package/data/seed/avatar-6.png +0 -0
  40. package/data/seed/avatar-7.png +0 -0
  41. package/data/seed/seed-metrics.csv +3 -0
  42. package/data/seed/seed-preview.png +0 -0
  43. package/data/seed/seed-report.pdf +32 -0
  44. package/data/seed/seed-runbook.txt +3 -0
  45. package/data/skill/SKILL.md +399 -0
  46. package/data/versions.yaml +55 -0
  47. package/data/voice/freeswitch/drachtio.xml +52 -0
  48. package/data/voice/freeswitch/public.xml +87 -0
  49. package/data/webui/app.css +2003 -0
  50. package/data/webui/index.html +678 -0
  51. package/data/webui/js/api.js +561 -0
  52. package/data/webui/js/boot.js +44 -0
  53. package/data/webui/js/clusters-tail.js +1377 -0
  54. package/data/webui/js/clusters.js +896 -0
  55. package/data/webui/js/create.js +276 -0
  56. package/data/webui/js/detail.js +507 -0
  57. package/data/webui/js/jobs.js +636 -0
  58. package/data/webui/js/logs.js +634 -0
  59. package/data/webui/js/main.js +14 -0
  60. package/data/webui/js/options.js +408 -0
  61. package/data/webui/js/people.js +438 -0
  62. package/data/webui/js/perf.js +303 -0
  63. package/data/webui/js/render.js +438 -0
  64. package/data/webui/js/shared.js +3 -0
  65. package/data/webui/js/state.js +583 -0
  66. package/data/webui/js/theme.js +123 -0
  67. package/data/webui/js/util.js +584 -0
  68. package/dist/cli/app.js +593 -0
  69. package/dist/cli/capabilities.js +76 -0
  70. package/dist/cli/cell-widths.js +495 -0
  71. package/dist/cli/entry.js +10 -0
  72. package/dist/cli/error-panel.js +492 -0
  73. package/dist/cli/handlers/actor.js +84 -0
  74. package/dist/cli/handlers/https.js +614 -0
  75. package/dist/cli/handlers/prompt.js +299 -0
  76. package/dist/cli/handlers/users.js +226 -0
  77. package/dist/cli/handlers.js +3678 -0
  78. package/dist/cli/help.js +183 -0
  79. package/dist/cli/index.js +15 -0
  80. package/dist/cli/perf.js +810 -0
  81. package/dist/cli/render.js +254 -0
  82. package/dist/cli/serve.js +858 -0
  83. package/dist/cli/spec-data.js +2593 -0
  84. package/dist/cli/spec-types.js +8 -0
  85. package/dist/cli/usage-error.js +520 -0
  86. package/dist/cli/wire.js +70 -0
  87. package/dist/core/audit.js +346 -0
  88. package/dist/core/backup-compat.js +85 -0
  89. package/dist/core/backup.js +1639 -0
  90. package/dist/core/cluster.js +1398 -0
  91. package/dist/core/configimport.js +344 -0
  92. package/dist/core/data.js +267 -0
  93. package/dist/core/database-of.js +82 -0
  94. package/dist/core/diagnose.js +159 -0
  95. package/dist/core/doctor.js +1518 -0
  96. package/dist/core/edge/acme.js +338 -0
  97. package/dist/core/edge/engine.js +500 -0
  98. package/dist/core/edge/networks.js +174 -0
  99. package/dist/core/edge/paths.js +107 -0
  100. package/dist/core/edge/routes.js +251 -0
  101. package/dist/core/edge/routeyml.js +195 -0
  102. package/dist/core/edge/runtime.js +493 -0
  103. package/dist/core/edge/spec.js +305 -0
  104. package/dist/core/edge/types.js +202 -0
  105. package/dist/core/eks-docs.js +135 -0
  106. package/dist/core/eks.js +2240 -0
  107. package/dist/core/envvars.js +562 -0
  108. package/dist/core/eventlog.js +541 -0
  109. package/dist/core/firstrun.js +153 -0
  110. package/dist/core/journal.js +691 -0
  111. package/dist/core/kube/ask.js +231 -0
  112. package/dist/core/kube/capabilities.js +269 -0
  113. package/dist/core/kube/certmanager.js +452 -0
  114. package/dist/core/kube/chart.js +413 -0
  115. package/dist/core/kube/cluster.js +196 -0
  116. package/dist/core/kube/context.js +545 -0
  117. package/dist/core/kube/endpoints.js +448 -0
  118. package/dist/core/kube/exec.js +195 -0
  119. package/dist/core/kube/forward.js +732 -0
  120. package/dist/core/kube/grafana-ingress.js +110 -0
  121. package/dist/core/kube/ingress.js +218 -0
  122. package/dist/core/kube/manifests.js +361 -0
  123. package/dist/core/kube/monitoring.js +768 -0
  124. package/dist/core/kube/names.js +237 -0
  125. package/dist/core/kube/namespace.js +678 -0
  126. package/dist/core/kube/operator.js +941 -0
  127. package/dist/core/kube/probe.js +202 -0
  128. package/dist/core/kube/reachability.js +163 -0
  129. package/dist/core/kube/release.js +439 -0
  130. package/dist/core/kube/replicaset.js +180 -0
  131. package/dist/core/kube/scale.js +398 -0
  132. package/dist/core/kube/status.js +633 -0
  133. package/dist/core/kube/tools.js +238 -0
  134. package/dist/core/kube/transfer.js +173 -0
  135. package/dist/core/kube/workspace.js +423 -0
  136. package/dist/core/lifecycle/admin.js +64 -0
  137. package/dist/core/lifecycle/create-docker.js +1533 -0
  138. package/dist/core/lifecycle/create-k8s.js +939 -0
  139. package/dist/core/lifecycle/destroy.js +339 -0
  140. package/dist/core/lifecycle/inspect.js +635 -0
  141. package/dist/core/lifecycle/naming.js +298 -0
  142. package/dist/core/lifecycle/notes.js +726 -0
  143. package/dist/core/lifecycle/ownership.js +313 -0
  144. package/dist/core/lifecycle/payload.js +401 -0
  145. package/dist/core/lifecycle/ports.js +388 -0
  146. package/dist/core/lifecycle/preconditions.js +367 -0
  147. package/dist/core/lifecycle/pruning.js +551 -0
  148. package/dist/core/lifecycle/ready.js +753 -0
  149. package/dist/core/lifecycle/request.js +525 -0
  150. package/dist/core/lifecycle/seeding.js +281 -0
  151. package/dist/core/lifecycle/sizing.js +392 -0
  152. package/dist/core/lifecycle/state.js +286 -0
  153. package/dist/core/lifecycle/tlsplan.js +704 -0
  154. package/dist/core/lifecycle/types.js +232 -0
  155. package/dist/core/loadtest.js +995 -0
  156. package/dist/core/migrate.js +612 -0
  157. package/dist/core/monitor.js +494 -0
  158. package/dist/core/postready.js +969 -0
  159. package/dist/core/promote.js +804 -0
  160. package/dist/core/rcapi.js +1285 -0
  161. package/dist/core/recovery.js +75 -0
  162. package/dist/core/runner/engine.js +394 -0
  163. package/dist/core/runner/host.js +298 -0
  164. package/dist/core/runner/locks.js +129 -0
  165. package/dist/core/runner/paths.js +173 -0
  166. package/dist/core/runner/ports.js +172 -0
  167. package/dist/core/runner/queries.js +612 -0
  168. package/dist/core/runner/record.js +563 -0
  169. package/dist/core/scaleseed.js +271 -0
  170. package/dist/core/seed-db.js +208 -0
  171. package/dist/core/sessions.js +472 -0
  172. package/dist/core/skill.js +326 -0
  173. package/dist/core/sso-identities.js +172 -0
  174. package/dist/core/sso.js +703 -0
  175. package/dist/core/tls-local.js +311 -0
  176. package/dist/core/tls.js +878 -0
  177. package/dist/core/topology.js +482 -0
  178. package/dist/core/upgrade.js +868 -0
  179. package/dist/core/users.js +739 -0
  180. package/dist/lib/audit.js +100 -0
  181. package/dist/lib/close-matches.js +238 -0
  182. package/dist/lib/compose.js +672 -0
  183. package/dist/lib/config.js +1398 -0
  184. package/dist/lib/context.js +18 -0
  185. package/dist/lib/errors.js +305 -0
  186. package/dist/lib/events.js +208 -0
  187. package/dist/lib/float-text.js +126 -0
  188. package/dist/lib/format.js +1320 -0
  189. package/dist/lib/home.js +325 -0
  190. package/dist/lib/journal.js +122 -0
  191. package/dist/lib/json-text.js +733 -0
  192. package/dist/lib/jsonout.js +382 -0
  193. package/dist/lib/lock.js +516 -0
  194. package/dist/lib/login-name.js +202 -0
  195. package/dist/lib/map-limit.js +29 -0
  196. package/dist/lib/mkdir-parents.js +90 -0
  197. package/dist/lib/mongo-kernel.js +67 -0
  198. package/dist/lib/monitoring.js +492 -0
  199. package/dist/lib/platform-name.js +59 -0
  200. package/dist/lib/presets/common.js +390 -0
  201. package/dist/lib/presets/composite.js +326 -0
  202. package/dist/lib/presets/e2ee.js +143 -0
  203. package/dist/lib/presets/email.js +172 -0
  204. package/dist/lib/presets/guides.js +27 -0
  205. package/dist/lib/presets/index.js +490 -0
  206. package/dist/lib/presets/keycloak.js +369 -0
  207. package/dist/lib/presets/ldap.js +1285 -0
  208. package/dist/lib/presets/livechat.js +220 -0
  209. package/dist/lib/presets/multi-instance.js +124 -0
  210. package/dist/lib/presets/oidc.js +161 -0
  211. package/dist/lib/presets/public.js +496 -0
  212. package/dist/lib/presets/registry.js +64 -0
  213. package/dist/lib/presets/s3-minio.js +300 -0
  214. package/dist/lib/presets/saml.js +149 -0
  215. package/dist/lib/presets/scenario.js +51 -0
  216. package/dist/lib/presets/types.js +86 -0
  217. package/dist/lib/presets/voice-pbx.js +320 -0
  218. package/dist/lib/presets/voice.js +345 -0
  219. package/dist/lib/presets/webhooks.js +182 -0
  220. package/dist/lib/redact.js +106 -0
  221. package/dist/lib/seed-options.js +68 -0
  222. package/dist/lib/seed-profiles.js +59 -0
  223. package/dist/lib/targz.js +1383 -0
  224. package/dist/lib/teammode.js +25 -0
  225. package/dist/lib/tempdir.js +162 -0
  226. package/dist/lib/unicode-tables.js +2335 -0
  227. package/dist/lib/version-spec.js +357 -0
  228. package/dist/lib/versions.js +463 -0
  229. package/dist/lib/yaml-dump.js +1361 -0
  230. package/dist/perf/baseline.js +168 -0
  231. package/dist/perf/constrain.js +296 -0
  232. package/dist/perf/k6.js +235 -0
  233. package/dist/perf/mongoprof.js +171 -0
  234. package/dist/perf/rcmetrics.js +178 -0
  235. package/dist/perf/report.js +386 -0
  236. package/dist/perf/resources.js +224 -0
  237. package/dist/perf/slo.js +111 -0
  238. package/dist/perf/timeline.js +187 -0
  239. package/dist/perf/timings.js +85 -0
  240. package/dist/perf/verdict.js +201 -0
  241. package/dist/seams/aws-cli.js +126 -0
  242. package/dist/seams/docker-cli.js +280 -0
  243. package/dist/seams/exec.js +861 -0
  244. package/dist/seams/fs/lock.js +528 -0
  245. package/dist/seams/kubectl.js +83 -0
  246. package/dist/seams/rc-http.js +921 -0
  247. package/dist/seed/apply.js +190 -0
  248. package/dist/seed/assets.js +76 -0
  249. package/dist/seed/check.js +391 -0
  250. package/dist/seed/client.js +172 -0
  251. package/dist/seed/executor.js +726 -0
  252. package/dist/seed/history.js +281 -0
  253. package/dist/seed/kinds.js +91 -0
  254. package/dist/seed/plan.js +432 -0
  255. package/dist/seed/receipt.js +339 -0
  256. package/dist/seed/repairs.js +75 -0
  257. package/dist/seed/verification.js +363 -0
  258. package/dist/seed/wording.js +248 -0
  259. package/dist/web/app.js +326 -0
  260. package/dist/web/jobs.js +510 -0
  261. package/dist/web/route-deps.js +211 -0
  262. package/dist/web/route-table.js +213 -0
  263. package/dist/web/routes/backup.js +244 -0
  264. package/dist/web/routes/clusters.js +303 -0
  265. package/dist/web/routes/data.js +187 -0
  266. package/dist/web/routes/edge.js +82 -0
  267. package/dist/web/routes/index.js +63 -0
  268. package/dist/web/routes/jobs.js +95 -0
  269. package/dist/web/routes/logs.js +297 -0
  270. package/dist/web/routes/meta.js +191 -0
  271. package/dist/web/routes/people.js +151 -0
  272. package/dist/web/routes/perf.js +95 -0
  273. package/dist/web/routes/repros.js +550 -0
  274. package/dist/web/routes/session.js +361 -0
  275. package/dist/web/routes/spa.js +198 -0
  276. package/dist/web/security.js +475 -0
  277. package/dist/web/signin.js +246 -0
  278. package/package.json +67 -32
  279. package/.eslintrc +0 -94
  280. package/.swcrc +0 -18
  281. package/dist/bin.js +0 -3
  282. package/dist/cli.js +0 -184
  283. package/dist/commands/createBranch.js +0 -194
  284. package/dist/outputCI.js +0 -59
  285. package/src/bin.js +0 -4
  286. package/src/cli.ts +0 -25
  287. package/src/commands/createBranch.ts +0 -28
  288. package/src/outputCI.ts +0 -12
  289. package/src-old/logs.js +0 -323
  290. package/src-old/md.js +0 -191
  291. package/src-old/release-table.js +0 -60
  292. package/src-old/set-version.js +0 -614
  293. package/src-old/utils.js +0 -15
@@ -0,0 +1,633 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TERMINAL_POD_REASONS = exports.LOG_CONTAINER = exports.APP_SELECTOR = exports.LOG_SELECTOR = exports.READY_SELECTOR = void 0;
4
+ exports.serviceReadyAddresses = serviceReadyAddresses;
5
+ exports.servicesWithoutEndpoints = servicesWithoutEndpoints;
6
+ exports.workspaceReady = workspaceReady;
7
+ exports.workspaceReplicasByNamespace = workspaceReplicasByNamespace;
8
+ exports.workspacePodsByNamespace = workspacePodsByNamespace;
9
+ exports.workspacePodsReady = workspacePodsReady;
10
+ exports.logArgv = logArgv;
11
+ exports.logProcess = logProcess;
12
+ exports.containerEnv = containerEnv;
13
+ exports.parseQuantity = parseQuantity;
14
+ exports.podMetrics = podMetrics;
15
+ exports.podRow = podRow;
16
+ exports.podRows = podRows;
17
+ exports.terminalPodFailure = terminalPodFailure;
18
+ exports.terminalFailureOfPods = terminalFailureOfPods;
19
+ exports.workloadExists = workloadExists;
20
+ exports.workloadReplicas = workloadReplicas;
21
+ /**
22
+ * What the workload is doing right now: pods, their phases, and the failures Kubernetes
23
+ * has already decided are terminal.
24
+ *
25
+ * `terminalPodFailure` exists so a mistyped version or an unreachable registry costs a second
26
+ * rather than the full readiness timeout, and reports the cause rather than the timeout.
27
+ */
28
+ const errors_1 = require("../../lib/errors");
29
+ const format_1 = require("../../lib/format");
30
+ const exec_1 = require("../../seams/exec");
31
+ const ask_1 = require("./ask");
32
+ const exec_2 = require("./exec");
33
+ const names_1 = require("./names");
34
+ const namespace_1 = require("./namespace");
35
+ /**
36
+ * The workloads whose readiness `ready` is entitled to speak for: the ones the official
37
+ * chart gives a real readinessProbe. `account`, `authorization` and `presence` are
38
+ * deliberately NOT here -- the chart ships them with no probe at all, so their pod-Ready
39
+ * is set the moment the container starts and attests nothing.
40
+ */
41
+ exports.READY_SELECTOR = 'app.kubernetes.io/name in (rocketchat,rocketchat-ddp-streamer)';
42
+ /**
43
+ * Rocket.Chat's APPLICATION pods -- every replica of the monolith, and on microservices
44
+ * the account, authorization, ddp-streamer and presence deployments too.
45
+ *
46
+ * This was `app.kubernetes.io/name=rocketchat`, which is the MONOLITH deployment alone. On
47
+ * microservices that silently omitted the four services that make the deployment
48
+ * interesting -- ddp-streamer above all, since it carries the WebSocket, so a realtime
49
+ * problem produced logs with nothing about realtime in them.
50
+ *
51
+ * Selected by RELEASE with nats excluded, rather than by listing the four names: a
52
+ * microservice the chart adds later is then included automatically.
53
+ */
54
+ exports.LOG_SELECTOR = names_1.APPLICATION_SELECTOR;
55
+ /**
56
+ * The MONOLITH Rocket.Chat deployment alone, and its container. Anything asking a question
57
+ * about "Rocket.Chat itself" wants this and not the broad log selector: that one matches
58
+ * ddp-streamer and presence too, so `items[0]` under it could answer with a microservice's
59
+ * environment instead of Rocket.Chat's.
60
+ */
61
+ exports.APP_SELECTOR = names_1.MONOLITH_SELECTOR;
62
+ exports.LOG_CONTAINER = 'rocketchat';
63
+ /**
64
+ * Waiting-state reasons a pod will never recover from on its own. `ImagePullBackOff` alone
65
+ * is NOT terminal -- a slow or rate-limited registry looks identical while it is still
66
+ * making progress -- so it is the REASON that discriminates, not the phase.
67
+ */
68
+ exports.TERMINAL_POD_REASONS = [
69
+ 'ErrImagePull',
70
+ 'ImagePullBackOff',
71
+ 'InvalidImageName',
72
+ 'CreateContainerConfigError',
73
+ 'CreateContainerError',
74
+ 'RunContainerError',
75
+ ];
76
+ function mapOf(value) {
77
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
78
+ ? value
79
+ : {};
80
+ }
81
+ function listOf(value) {
82
+ return Array.isArray(value) ? value : [];
83
+ }
84
+ /**
85
+ * Ready endpoint count per Service in a namespace. null if it could not be read.
86
+ *
87
+ * EndpointSlice, not Endpoints. kubectl says it plainly on every call to the old one, and
88
+ * `discovery.k8s.io/v1` has been GA since Kubernetes 1.21, which is this package's
89
+ * declared kubectl floor.
90
+ *
91
+ * A Service with pods behind it but no READY endpoints is the case worth having this for:
92
+ * readiness reads pod status and the port-forward targets the Deployment, so nothing on
93
+ * either path ever traverses the Service. A selector that matches nothing therefore looked
94
+ * exactly like a healthy workspace -- and the Kubernetes default deployment is
95
+ * microservices, where in-cluster Service traffic is what carries the product.
96
+ */
97
+ async function serviceReadyAddresses(namespace, { context }) {
98
+ const seen = await (0, ask_1.askList)('endpointslices', { context, namespace });
99
+ if ((0, ask_1.refused)(seen))
100
+ return null;
101
+ const out = {};
102
+ for (const slice of (0, ask_1.items)(seen)) {
103
+ const svc = String(mapOf(mapOf(slice.metadata).labels)['kubernetes.io/service-name'] ?? '');
104
+ if (svc === '')
105
+ continue;
106
+ let ready = 0;
107
+ for (const endpoint of listOf(slice.endpoints)) {
108
+ if (mapOf(endpoint.conditions).ready === true)
109
+ ready += 1;
110
+ }
111
+ out[svc] = (out[svc] ?? 0) + ready;
112
+ }
113
+ return out;
114
+ }
115
+ /**
116
+ * Rocket.Chat Services in this workspace that no ready pod is behind.
117
+ *
118
+ * REPORTED, NOT GATED, and that is deliberate. Endpoints churn during a rollout, so a
119
+ * transient empty set is normal; making readiness depend on this would turn an ordinary
120
+ * restart into a workspace that never comes ready. And a false negative here would block
121
+ * every boot, which is a far worse failure than the one being detected.
122
+ */
123
+ async function servicesWithoutEndpoints(name, { context }) {
124
+ const namespace = await (0, namespace_1.namespaceFor)(name);
125
+ const counts = await serviceReadyAddresses(namespace, { context });
126
+ if (counts === null)
127
+ return [];
128
+ const svcs = await (0, ask_1.askList)('svc', { context, namespace });
129
+ if ((0, ask_1.refused)(svcs))
130
+ return [];
131
+ const bad = [];
132
+ for (const svc of (0, ask_1.items)(svcs)) {
133
+ const meta = mapOf(svc.metadata);
134
+ const svcName = String(meta.name ?? '');
135
+ const spec = mapOf(svc.spec);
136
+ const selector = mapOf(spec.selector);
137
+ // A Service with no selector is wired by hand (or is a headless alias) and has no pods
138
+ // to be missing. ExternalName has no endpoints by definition.
139
+ if (svcName === '' || Object.keys(selector).length === 0)
140
+ continue;
141
+ if (String(spec.type ?? '') === 'ExternalName')
142
+ continue;
143
+ // THE SELECTOR, NOT THE LABELS, and this was wrong first time round: the chart does
144
+ // not set `app.kubernetes.io/instance` as a LABEL on most of them, so the filter
145
+ // excluded every Service it was meant to judge and the whole check was a silent no-op.
146
+ // Caught by breaking one on a live cluster, which is the only way it could have been
147
+ // caught -- a stub would have answered whatever the test put in it.
148
+ if (selector['app.kubernetes.io/instance'] !== names_1.RELEASE)
149
+ continue;
150
+ if ((counts[svcName] ?? 0) === 0)
151
+ bad.push(svcName);
152
+ }
153
+ return bad.sort();
154
+ }
155
+ /**
156
+ * Whether every probed Rocket.Chat workload reports itself Ready.
157
+ *
158
+ * This used to read `items[0].status.containerStatuses[0].ready`, which over-claimed
159
+ * twice: `items[0]` is ONE pod, so with `--replicas 3` the workspace was called ready on
160
+ * the strength of the first; and only the monolith container was consulted, while on
161
+ * microservices `ddp-streamer` carries the WebSocket and was observed Running-but-not-Ready
162
+ * on a workspace already reported as serving.
163
+ *
164
+ * A Pending pod has no containerStatuses at all, so counting pods and comparing is what
165
+ * keeps "no statuses yet" from passing as "nothing failed".
166
+ */
167
+ async function workspaceReady(name, { context }) {
168
+ const res = await exec_2.kube.run([
169
+ 'kubectl',
170
+ '--context',
171
+ context,
172
+ '-n',
173
+ await (0, namespace_1.namespaceFor)(name),
174
+ 'get',
175
+ 'pod',
176
+ '-l',
177
+ exports.READY_SELECTOR,
178
+ '-o',
179
+ 'json',
180
+ ], { own: (0, names_1.isOurs)(context) });
181
+ if (res.returncode !== 0)
182
+ return false;
183
+ let pods;
184
+ try {
185
+ pods = listOf(mapOf(JSON.parse(res.stdout || '{}')).items);
186
+ }
187
+ catch {
188
+ return false;
189
+ }
190
+ return readyPodRows(pods);
191
+ }
192
+ function readyPodRows(pods) {
193
+ if (pods.length === 0)
194
+ return false;
195
+ for (const pod of pods) {
196
+ const statuses = listOf(mapOf(pod.status).containerStatuses);
197
+ if (statuses.length === 0)
198
+ return false; // Pending/ContainerCreating
199
+ if (!statuses.every((container) => container.ready === true))
200
+ return false;
201
+ }
202
+ return true;
203
+ }
204
+ /** A broad collection must be usable before an omitted namespace can mean absence. */
205
+ function namespaceRows(seen) {
206
+ if ((0, ask_1.refused)(seen) || !Array.isArray(seen.doc?.items))
207
+ return null;
208
+ const rows = (0, ask_1.items)(seen);
209
+ for (const row of rows) {
210
+ const meta = mapOf(mapOf(row).metadata);
211
+ if (typeof meta.namespace !== 'string' ||
212
+ meta.namespace === '' ||
213
+ typeof meta.name !== 'string' ||
214
+ meta.name === '') {
215
+ return null;
216
+ }
217
+ }
218
+ return rows;
219
+ }
220
+ /**
221
+ * One fresh Deployment read for a workspace list, keyed by its actual namespace.
222
+ * A refused broad read is null so a namespace-scoped identity can use the scoped probe.
223
+ */
224
+ async function workspaceReplicasByNamespace(context) {
225
+ const rows = namespaceRows(await (0, ask_1.askList)('deployment', { context, allNamespaces: true }));
226
+ if (rows === null)
227
+ return null;
228
+ const replicas = new Map();
229
+ for (const row of rows) {
230
+ const meta = mapOf(row.metadata);
231
+ if (meta.name !== `${names_1.RELEASE}-rocketchat`)
232
+ continue;
233
+ const count = mapOf(row.spec).replicas;
234
+ replicas.set(String(meta.namespace), typeof count === 'number' ? count : -1);
235
+ }
236
+ return replicas;
237
+ }
238
+ /** One fresh pod read shared by readiness and failure checks in a workspace list. */
239
+ async function workspacePodsByNamespace(context) {
240
+ const rows = namespaceRows(await (0, ask_1.askList)('pod', { context, allNamespaces: true }));
241
+ if (rows === null)
242
+ return null;
243
+ const pods = new Map();
244
+ for (const row of rows) {
245
+ const namespace = String(mapOf(row.metadata).namespace);
246
+ const held = pods.get(namespace) ?? [];
247
+ held.push(row);
248
+ pods.set(namespace, held);
249
+ }
250
+ return pods;
251
+ }
252
+ /** Apply the existing readiness selector to an unfiltered pod snapshot. */
253
+ function workspacePodsReady(pods) {
254
+ return readyPodRows(pods.filter((pod) => {
255
+ const name = mapOf(mapOf(pod.metadata).labels)['app.kubernetes.io/name'];
256
+ return name === 'rocketchat' || name === 'rocketchat-ddp-streamer';
257
+ }));
258
+ }
259
+ async function podCount(name, { context, selector = exports.LOG_SELECTOR }) {
260
+ const res = await exec_2.kube.run([
261
+ 'kubectl',
262
+ '--context',
263
+ context,
264
+ '-n',
265
+ await (0, namespace_1.namespaceFor)(name),
266
+ 'get',
267
+ 'pods',
268
+ '-l',
269
+ selector,
270
+ '-o',
271
+ 'name',
272
+ ], { own: (0, names_1.isOurs)(context) });
273
+ if (res.returncode !== 0)
274
+ return 1;
275
+ return res.stdout.split('\n').filter((line) => line.trim() !== '').length;
276
+ }
277
+ /**
278
+ * Stream Rocket.Chat's logs out of the cluster, shaped like the Compose one.
279
+ *
280
+ * A named function for the same reason the Compose one is: it is the single kubectl call
281
+ * the log path makes, so a test can stand here without a cluster.
282
+ *
283
+ * `--prefix` matters more here than on Compose: with microservices or several replicas the
284
+ * lines come from different pods and are otherwise indistinguishable. `--max-log-requests`
285
+ * is raised because kubectl refuses to follow more than five pods by default and a
286
+ * microservices workspace has more than five.
287
+ */
288
+ async function logArgv(name, { context, tail = 200, follow = true, selector = exports.LOG_SELECTOR, }) {
289
+ // No `-c`: the pods now selected have DIFFERENT container names (rocketchat,
290
+ // ddp-streamer, presence...), so naming one would fail on the others. Each pod here has
291
+ // a single container, so kubectl's default is the right one.
292
+ const argv = [
293
+ 'kubectl',
294
+ '--context',
295
+ context,
296
+ '-n',
297
+ await (0, namespace_1.namespaceFor)(name),
298
+ 'logs',
299
+ '-l',
300
+ selector,
301
+ '--tail',
302
+ String(Math.trunc(tail)),
303
+ '--max-log-requests',
304
+ '20',
305
+ ];
306
+ // `--prefix` ONLY when there is more than one pod to tell apart. It was unconditional
307
+ // and that was wrong: Rocket.Chat pretty-prints its own log lines in columns, and
308
+ // stamping "[pod/rocketchat-rocketchat-<hash>/rocketchat] " onto the front of every one
309
+ // of them destroys exactly the formatting somebody opened the logs to read.
310
+ if ((await podCount(name, { context, selector })) > 1)
311
+ argv.push('--prefix');
312
+ if (follow)
313
+ argv.push('-f');
314
+ return argv;
315
+ }
316
+ /**
317
+ * Stream the log lines out of the cluster, merged, one callback per line.
318
+ *
319
+ * The log process's output is read as text, line by line: every line reaches the readers,
320
+ * the unterminated last one included, split as text mode splits (`textLines`). This split
321
+ * on `\n` alone and kept whatever followed the last one -- `logs` dropped a final line with
322
+ * no newline, and a `\r`-redrawn line came through whole with its carriage returns in it
323
+ * The result retains nothing: `stream` keeps no copy of the output, so a reader that needs
324
+ * the text collects it through `onLine`.
325
+ */
326
+ async function logProcess(name, options) {
327
+ const argv = await logArgv(name, options);
328
+ const env = (0, exec_2.envFor)(options.context);
329
+ const lines = (0, format_1.textLines)((line) => options.onLine?.(line));
330
+ options.onSpawn?.();
331
+ const result = await (0, exec_1.stream)(argv, {
332
+ encoding: 'utf8',
333
+ mergeStderr: true,
334
+ ...(env !== undefined ? { env } : {}),
335
+ ...(options.abortSignal === undefined ? {} : { abortSignal: options.abortSignal }),
336
+ onStdout: (chunk) => lines.push(typeof chunk === 'string' ? chunk : chunk.toString('utf8')),
337
+ });
338
+ lines.end();
339
+ return result;
340
+ }
341
+ /**
342
+ * Rocket.Chat's EFFECTIVE environment, read out of the running container.
343
+ *
344
+ * Compose answers this from the generated compose file. There is no such document here,
345
+ * and the helm values are only what houston asked for -- the chart adds its own, so the
346
+ * values are not the answer to "what is Rocket.Chat actually running with".
347
+ */
348
+ async function containerEnv(name, { context, selector = exports.APP_SELECTOR }) {
349
+ const namespace = await (0, namespace_1.namespaceFor)(name);
350
+ const pod = await exec_2.kube.run([
351
+ 'kubectl',
352
+ '--context',
353
+ context,
354
+ '-n',
355
+ namespace,
356
+ 'get',
357
+ 'pod',
358
+ '-l',
359
+ selector,
360
+ '-o',
361
+ 'jsonpath={.items[0].metadata.name}',
362
+ ], { own: (0, names_1.isOurs)(context) });
363
+ // THE EXIT CODE, not just empty stdout. A refused read -- wrong context, RBAC, a
364
+ // timeout -- also produces no stdout, so a HEALTHY running workspace was told "no
365
+ // Rocket.Chat pod ... is it running?", which sends the reader to start something that is
366
+ // already started.
367
+ //
368
+ // `quotedText(context)` and `quotedText(name)'s`, the established messages: `quotedText` picks
369
+ // double quotes for `o'brien`, and a quoted name before `'s` is `'beta''s`. These
370
+ // hard-coded single quotes, so every refused pod lookup -- RBAC, a wrong context, no
371
+ // kubectl -- read differently.
372
+ if (pod.returncode !== 0) {
373
+ throw new errors_1.DockerError(`could not ask cluster ${(0, format_1.quotedText)(context)} for ${(0, format_1.quotedText)(name)}'s Rocket.Chat pod: ${(0, ask_1.why)(pod)}`);
374
+ }
375
+ const target = pod.stdout.trim();
376
+ if (target === '') {
377
+ throw new errors_1.NotReadyError(`no Rocket.Chat pod in ${namespace} to read the environment from — is ${(0, format_1.quotedText)(name)} ` +
378
+ `running? (\`houston start --name ${name}\`)`);
379
+ }
380
+ const res = await exec_2.kube.run([
381
+ 'kubectl',
382
+ '--context',
383
+ context,
384
+ '-n',
385
+ namespace,
386
+ 'exec',
387
+ target,
388
+ '-c',
389
+ exports.LOG_CONTAINER,
390
+ '--',
391
+ 'env',
392
+ ], { timeout: names_1.APPLY_TIMEOUT, own: (0, names_1.isOurs)(context) });
393
+ if (res.returncode !== 0) {
394
+ throw new errors_1.NotReadyError(`could not read the environment from ${target}: ${(0, ask_1.why)(res)}`);
395
+ }
396
+ const out = {};
397
+ for (const line of res.stdout.split('\n')) {
398
+ const at = line.indexOf('=');
399
+ if (at >= 0)
400
+ out[line.slice(0, at).trim()] = line.slice(at + 1);
401
+ }
402
+ return out;
403
+ }
404
+ /**
405
+ * A Kubernetes CPU or memory quantity as a plain number.
406
+ *
407
+ * CPU comes as millicores ("142m") or cores ("1"); memory as Ki/Mi/Gi. Returned as
408
+ * millicores and BYTES respectively, so the caller does the same arithmetic it does for
409
+ * Compose.
410
+ */
411
+ function parseQuantity(text) {
412
+ const trimmed = text.trim();
413
+ if (trimmed.endsWith('m'))
414
+ return Number(trimmed.slice(0, -1) || 0);
415
+ for (const [suffix, multiplier] of [
416
+ ['Ki', 1024],
417
+ ['Mi', 1024 ** 2],
418
+ ['Gi', 1024 ** 3],
419
+ ['K', 1000],
420
+ ['M', 1000 ** 2],
421
+ ['G', 1000 ** 3],
422
+ ]) {
423
+ if (trimmed.endsWith(suffix)) {
424
+ return Number(trimmed.slice(0, -suffix.length) || 0) * multiplier;
425
+ }
426
+ }
427
+ const value = Number(trimmed);
428
+ return Number.isFinite(value) ? value : 0;
429
+ }
430
+ /**
431
+ * Per-pod CPU and memory, via `kubectl top`.
432
+ *
433
+ * Every Rocket.Chat application pod, which on microservices means the four services as
434
+ * well as the monolith deployment. Scoped to the monolith alone it would report two pods
435
+ * out of six and call it the workspace's resource use.
436
+ *
437
+ * Needs metrics-server, which kind does NOT ship. When it is absent the refusal says so
438
+ * and how to install it, rather than reporting zero -- a resource figure that is quietly
439
+ * wrong is worse than one that is missing. A PreflightError, exit 3 and a 409: the answer is
440
+ * to install it (or, on kind, to let it scrape), and polling changes nothing. It was a
441
+ * NotReadyError, exit 5, which tells a script to poll again -- forever, here.
442
+ */
443
+ async function podMetrics(name, { context, selector = exports.LOG_SELECTOR }) {
444
+ // An EMPTY selector means the whole namespace, and the flag is dropped rather than
445
+ // passed empty -- Compose sums every container in the workspace, and reporting only the
446
+ // Rocket.Chat pods made the two runtimes measure different sets, omitting the database
447
+ // on the one where it is usually the largest consumer.
448
+ const argv = ['kubectl', '--context', context, '-n', await (0, namespace_1.namespaceFor)(name), 'top', 'pods'];
449
+ if (selector !== '')
450
+ argv.push('-l', selector);
451
+ argv.push('--no-headers');
452
+ const res = await exec_2.kube.run(argv, { timeout: names_1.APPLY_TIMEOUT, own: (0, names_1.isOurs)(context) });
453
+ if (res.returncode !== 0) {
454
+ const blob = `${res.stderr}${res.stdout}`.toLowerCase();
455
+ if (blob.includes('metrics') || blob.includes('not available')) {
456
+ // Both commands, because the second is not optional on kind: its kubelet serves a
457
+ // self-signed certificate that metrics-server refuses by default, so the install
458
+ // succeeds and never reports a metric.
459
+ throw new errors_1.PreflightError('this cluster has no metrics-server, so there is nothing to read CPU and memory ' +
460
+ 'from. Install it with:\n' +
461
+ ' kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/' +
462
+ 'latest/download/components.yaml\n' +
463
+ "and on kind, let it accept the kubelet's self-signed certificate:\n" +
464
+ ' kubectl -n kube-system patch deploy metrics-server --type=json -p ' +
465
+ '\'[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":' +
466
+ '"--kubelet-insecure-tls"}]\'');
467
+ }
468
+ throw new errors_1.NotReadyError(`could not read pod metrics: ${(0, ask_1.why)(res)}`);
469
+ }
470
+ const rows = [];
471
+ for (const line of res.stdout.split('\n')) {
472
+ const parts = line.split(/\s+/u).filter(Boolean);
473
+ if (parts.length >= 3) {
474
+ rows.push({
475
+ pod: parts[0],
476
+ cpu_millicores: parseQuantity(parts[1]),
477
+ mem_bytes: parseQuantity(parts[2]),
478
+ });
479
+ }
480
+ }
481
+ return rows;
482
+ }
483
+ /** Render one Kubernetes pod in the container-panel shape. */
484
+ function podRow(item) {
485
+ const meta = mapOf(item.metadata);
486
+ const st = mapOf(item.status);
487
+ // initContainerStatuses too: the MongoDB fix-permission and init containers are exactly
488
+ // where a Kubernetes workspace gets stuck, and a pod whose init container is in
489
+ // CrashLoopBackOff reports phase Pending and an EMPTY containerStatuses -- so reading
490
+ // only the main list showed "0/0 ready" and named nothing.
491
+ const main = listOf(st.containerStatuses);
492
+ const all = [...listOf(st.initContainerStatuses), ...main];
493
+ const ready = main.filter((container) => container.ready === true).length;
494
+ let restarts = 0;
495
+ for (const container of all)
496
+ restarts += Number(container.restartCount ?? 0);
497
+ let reason = '';
498
+ for (const container of all) {
499
+ const state = mapOf(container.state);
500
+ const waiting = mapOf(state.waiting);
501
+ const terminated = mapOf(state.terminated);
502
+ // A terminated init container that SUCCEEDED is not a reason -- that is the normal end
503
+ // of an init container, and reporting "Completed" as the pod's status hid a Rocket.Chat
504
+ // container that was crash-looping behind it.
505
+ if (terminated.reason === 'Completed')
506
+ continue;
507
+ reason = String(waiting.reason ?? terminated.reason ?? '');
508
+ if (reason !== '')
509
+ break;
510
+ }
511
+ const phase = String(st.phase ?? '');
512
+ let status = reason || `${String(ready)}/${String(main.length)} ready`;
513
+ if (restarts > 0)
514
+ status += ` · ${String(restarts)} restart${restarts === 1 ? '' : 's'}`;
515
+ return {
516
+ service: String(meta.name ?? ''),
517
+ state: phase.toLowerCase(),
518
+ status,
519
+ health: main.length > 0 && ready === main.length ? 'healthy' : '',
520
+ // WHICH POD IS ROCKET.CHAT ITSELF, decided by the label APP_SELECTOR already names --
521
+ // not by a substring of the pod name, which is a naming rule the browser would then
522
+ // hold a second copy of.
523
+ app: mapOf(meta.labels)['app.kubernetes.io/name'] === 'rocketchat',
524
+ // Decided HERE, next to the list that defines it, because the browser needs the answer
525
+ // and must not keep a second copy of the policy: `ContainerCreating` and
526
+ // `PodInitializing` are waiting reasons too, and a panel that treated every reason as a
527
+ // failure would report a booting workspace as broken.
528
+ blocked: exports.TERMINAL_POD_REASONS.includes(reason),
529
+ restarts,
530
+ started: String(st.startTime ?? ''),
531
+ };
532
+ }
533
+ /**
534
+ * Every pod in this workspace's namespace, in the shape the panel's containers tab already
535
+ * renders.
536
+ *
537
+ * A waiting REASON outranks the phase in the status column. "Pending" says only that
538
+ * something has not happened; `ImagePullBackOff`, `CrashLoopBackOff` and
539
+ * `CreateContainerConfigError` say what, and that is the answer to "why is this workspace
540
+ * not up".
541
+ */
542
+ async function podRows(name, { context }) {
543
+ const res = await exec_2.kube.run(['kubectl', '--context', context, '-n', await (0, namespace_1.namespaceFor)(name), 'get', 'pods', '-o', 'json'], { own: (0, names_1.isOurs)(context) });
544
+ // An unreachable cluster is the panel's "docker is unavailable": an empty list, never a
545
+ // raise. `detail()` is on the path of every panel open, and a workspace whose cluster is
546
+ // asleep still has to render.
547
+ if (res.returncode !== 0)
548
+ return [];
549
+ let doc;
550
+ try {
551
+ doc = mapOf(JSON.parse(res.stdout || '{}'));
552
+ }
553
+ catch {
554
+ return [];
555
+ }
556
+ const rows = listOf(doc.items).map(podRow);
557
+ // Named order, so the tab does not reshuffle itself between two panel opens.
558
+ rows.sort((left, right) => left.service < right.service ? -1 : left.service > right.service ? 1 : 0);
559
+ return rows;
560
+ }
561
+ /**
562
+ * The first pod condition that cannot succeed, as `[pod, reason, message]`.
563
+ *
564
+ * Without this, a create waits out its whole timeout on something already decided: a
565
+ * mistyped version, an image the registry does not have, an unreachable registry. Ten
566
+ * minutes of "waiting for Rocket.Chat" for an answer Kubernetes had in seconds.
567
+ *
568
+ * Returns null when nothing is terminal, so the caller keeps waiting -- the default has to
569
+ * be patience, or a slow pull becomes a failed create.
570
+ */
571
+ async function terminalPodFailure(name, { context }) {
572
+ const res = await exec_2.kube.run(['kubectl', '--context', context, '-n', await (0, namespace_1.namespaceFor)(name), 'get', 'pods', '-o', 'json'], { own: (0, names_1.isOurs)(context) });
573
+ if (res.returncode !== 0)
574
+ return null;
575
+ let rows;
576
+ try {
577
+ rows = listOf(mapOf(JSON.parse(res.stdout || '{}')).items);
578
+ }
579
+ catch {
580
+ return null;
581
+ }
582
+ return terminalFailureOfPods(rows);
583
+ }
584
+ /** The same terminal-failure rule for a caller that already read these pods. */
585
+ function terminalFailureOfPods(rows) {
586
+ for (const item of rows) {
587
+ const pod = String(mapOf(item.metadata).name ?? '');
588
+ const st = mapOf(item.status);
589
+ for (const status of [...listOf(st.containerStatuses), ...listOf(st.initContainerStatuses)]) {
590
+ const waiting = mapOf(mapOf(status.state).waiting);
591
+ const reason = String(waiting.reason ?? '');
592
+ if (exports.TERMINAL_POD_REASONS.includes(reason)) {
593
+ return [pod, reason, String(waiting.message ?? '').trim()];
594
+ }
595
+ }
596
+ }
597
+ return null;
598
+ }
599
+ /**
600
+ * Whether the Rocket.Chat deployment is present in the workspace's namespace.
601
+ *
602
+ * Distinct from the namespace existing, which survives a plain `down` along with the PVC.
603
+ *
604
+ * RAISES rather than answering false when the cluster could not be asked. This returned
605
+ * `rc == 0 and stdout`, so a wrong context, an RBAC denial or a timeout all read as "the
606
+ * workload is not there" -- and `prunable()` then listed a LIVE workspace under "these
607
+ * down repros will be deleted, containers, data volumes and records". Measured: it
608
+ * returned a workspace that was serving 200 at the time.
609
+ */
610
+ async function workloadExists(name, { context }) {
611
+ return (await workloadReplicas(name, { context })) !== null;
612
+ }
613
+ /**
614
+ * The Rocket.Chat Deployment's DESIRED replica count, or null when there is no Deployment;
615
+ * -1 when it carries no count. Presence and count from ONE read, where the state column
616
+ * asked `workloadExists` and then `desiredReplicas` -- two round trips for one object.
617
+ *
618
+ * RAISES on a refused read, for the reason `workloadExists` gives.
619
+ */
620
+ async function workloadReplicas(name, { context }) {
621
+ const answer = await (0, ask_1.askObject)('deployment', `${names_1.RELEASE}-rocketchat`, {
622
+ namespace: await (0, namespace_1.namespaceFor)(name),
623
+ context,
624
+ });
625
+ if ((0, ask_1.refused)(answer)) {
626
+ throw new errors_1.DockerError(`could not ask cluster ${(0, format_1.quotedText)(context)} whether ${(0, format_1.quotedText)(name)} is running: ` +
627
+ ((0, ask_1.answerWhy)(answer) || 'the API server did not answer'));
628
+ }
629
+ if (!(0, ask_1.present)(answer))
630
+ return null;
631
+ const replicas = mapOf(answer.doc.spec).replicas;
632
+ return typeof replicas === 'number' ? replicas : -1;
633
+ }