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

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 (294) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +109 -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 +642 -0
  10. package/data/docs/kubernetes.md +138 -0
  11. package/data/docs/loadtest.md +264 -0
  12. package/data/docs/troubleshooting.md +203 -0
  13. package/data/docs/upgrading.md +84 -0
  14. package/data/docs/voice.md +253 -0
  15. package/data/iam/engineer-policy.json +11 -0
  16. package/data/iam/engineer-rbac.yaml +42 -0
  17. package/data/iam/operator-policy.json +211 -0
  18. package/data/loadtest/badbot.js +22 -0
  19. package/data/loadtest/common.js +170 -0
  20. package/data/loadtest/custom.js +20 -0
  21. package/data/loadtest/journey.js +58 -0
  22. package/data/loadtest/login.js +18 -0
  23. package/data/loadtest/messages.js +13 -0
  24. package/data/loadtest/mixed.js +57 -0
  25. package/data/loadtest/read.js +12 -0
  26. package/data/loadtest/webhook.js +20 -0
  27. package/data/monitoring/houston-logs.json +98 -0
  28. package/data/monitoring/k6-loadtest.json +610 -0
  29. package/data/monitoring/mongodb-exporter.json +3007 -0
  30. package/data/monitoring/node-exporter-full.json +16114 -0
  31. package/data/monitoring/rocketchat-metrics.json +6471 -0
  32. package/data/presets/airgapped.yaml +16 -0
  33. package/data/presets/default.yaml +9 -0
  34. package/data/seed/avatar-0.png +0 -0
  35. package/data/seed/avatar-1.png +0 -0
  36. package/data/seed/avatar-2.png +0 -0
  37. package/data/seed/avatar-3.png +0 -0
  38. package/data/seed/avatar-4.png +0 -0
  39. package/data/seed/avatar-5.png +0 -0
  40. package/data/seed/avatar-6.png +0 -0
  41. package/data/seed/avatar-7.png +0 -0
  42. package/data/seed/seed-metrics.csv +3 -0
  43. package/data/seed/seed-preview.png +0 -0
  44. package/data/seed/seed-report.pdf +32 -0
  45. package/data/seed/seed-runbook.txt +3 -0
  46. package/data/skill/SKILL.md +399 -0
  47. package/data/versions.yaml +55 -0
  48. package/data/voice/freeswitch/drachtio.xml +52 -0
  49. package/data/voice/freeswitch/public.xml +87 -0
  50. package/data/webui/app.css +2003 -0
  51. package/data/webui/index.html +678 -0
  52. package/data/webui/js/api.js +561 -0
  53. package/data/webui/js/boot.js +44 -0
  54. package/data/webui/js/clusters-tail.js +1377 -0
  55. package/data/webui/js/clusters.js +896 -0
  56. package/data/webui/js/create.js +276 -0
  57. package/data/webui/js/detail.js +507 -0
  58. package/data/webui/js/jobs.js +636 -0
  59. package/data/webui/js/logs.js +634 -0
  60. package/data/webui/js/main.js +14 -0
  61. package/data/webui/js/options.js +408 -0
  62. package/data/webui/js/people.js +438 -0
  63. package/data/webui/js/perf.js +303 -0
  64. package/data/webui/js/render.js +438 -0
  65. package/data/webui/js/shared.js +3 -0
  66. package/data/webui/js/state.js +583 -0
  67. package/data/webui/js/theme.js +123 -0
  68. package/data/webui/js/util.js +584 -0
  69. package/dist/cli/app.js +593 -0
  70. package/dist/cli/capabilities.js +76 -0
  71. package/dist/cli/cell-widths.js +495 -0
  72. package/dist/cli/entry.js +10 -0
  73. package/dist/cli/error-panel.js +492 -0
  74. package/dist/cli/handlers/actor.js +84 -0
  75. package/dist/cli/handlers/https.js +614 -0
  76. package/dist/cli/handlers/prompt.js +299 -0
  77. package/dist/cli/handlers/users.js +226 -0
  78. package/dist/cli/handlers.js +3694 -0
  79. package/dist/cli/help.js +183 -0
  80. package/dist/cli/index.js +15 -0
  81. package/dist/cli/perf.js +814 -0
  82. package/dist/cli/render.js +254 -0
  83. package/dist/cli/serve.js +858 -0
  84. package/dist/cli/spec-data.js +2599 -0
  85. package/dist/cli/spec-types.js +8 -0
  86. package/dist/cli/usage-error.js +520 -0
  87. package/dist/cli/wire.js +70 -0
  88. package/dist/core/audit.js +346 -0
  89. package/dist/core/backup-compat.js +85 -0
  90. package/dist/core/backup.js +1639 -0
  91. package/dist/core/cluster.js +1398 -0
  92. package/dist/core/configimport.js +345 -0
  93. package/dist/core/data.js +267 -0
  94. package/dist/core/database-of.js +82 -0
  95. package/dist/core/diagnose.js +159 -0
  96. package/dist/core/doctor.js +1518 -0
  97. package/dist/core/edge/acme.js +338 -0
  98. package/dist/core/edge/engine.js +500 -0
  99. package/dist/core/edge/networks.js +174 -0
  100. package/dist/core/edge/paths.js +107 -0
  101. package/dist/core/edge/routes.js +251 -0
  102. package/dist/core/edge/routeyml.js +195 -0
  103. package/dist/core/edge/runtime.js +493 -0
  104. package/dist/core/edge/spec.js +305 -0
  105. package/dist/core/edge/types.js +202 -0
  106. package/dist/core/eks-docs.js +135 -0
  107. package/dist/core/eks.js +2240 -0
  108. package/dist/core/envvars.js +562 -0
  109. package/dist/core/eventlog.js +541 -0
  110. package/dist/core/firstrun.js +153 -0
  111. package/dist/core/journal.js +694 -0
  112. package/dist/core/kube/ask.js +231 -0
  113. package/dist/core/kube/capabilities.js +269 -0
  114. package/dist/core/kube/certmanager.js +452 -0
  115. package/dist/core/kube/chart.js +413 -0
  116. package/dist/core/kube/cluster.js +196 -0
  117. package/dist/core/kube/context.js +545 -0
  118. package/dist/core/kube/endpoints.js +448 -0
  119. package/dist/core/kube/exec.js +195 -0
  120. package/dist/core/kube/forward.js +732 -0
  121. package/dist/core/kube/grafana-ingress.js +110 -0
  122. package/dist/core/kube/ingress.js +218 -0
  123. package/dist/core/kube/manifests.js +361 -0
  124. package/dist/core/kube/monitoring.js +768 -0
  125. package/dist/core/kube/names.js +237 -0
  126. package/dist/core/kube/namespace.js +678 -0
  127. package/dist/core/kube/operator.js +941 -0
  128. package/dist/core/kube/probe.js +202 -0
  129. package/dist/core/kube/reachability.js +163 -0
  130. package/dist/core/kube/release.js +439 -0
  131. package/dist/core/kube/replicaset.js +180 -0
  132. package/dist/core/kube/scale.js +398 -0
  133. package/dist/core/kube/status.js +633 -0
  134. package/dist/core/kube/tools.js +238 -0
  135. package/dist/core/kube/transfer.js +173 -0
  136. package/dist/core/kube/workspace.js +423 -0
  137. package/dist/core/lifecycle/admin.js +64 -0
  138. package/dist/core/lifecycle/create-docker.js +1549 -0
  139. package/dist/core/lifecycle/create-k8s.js +960 -0
  140. package/dist/core/lifecycle/destroy.js +339 -0
  141. package/dist/core/lifecycle/inspect.js +636 -0
  142. package/dist/core/lifecycle/naming.js +298 -0
  143. package/dist/core/lifecycle/notes.js +862 -0
  144. package/dist/core/lifecycle/ownership.js +313 -0
  145. package/dist/core/lifecycle/payload.js +401 -0
  146. package/dist/core/lifecycle/ports.js +388 -0
  147. package/dist/core/lifecycle/preconditions.js +367 -0
  148. package/dist/core/lifecycle/pruning.js +551 -0
  149. package/dist/core/lifecycle/ready.js +818 -0
  150. package/dist/core/lifecycle/request.js +510 -0
  151. package/dist/core/lifecycle/seeding.js +281 -0
  152. package/dist/core/lifecycle/sizing.js +392 -0
  153. package/dist/core/lifecycle/state.js +286 -0
  154. package/dist/core/lifecycle/tlsplan.js +704 -0
  155. package/dist/core/lifecycle/types.js +232 -0
  156. package/dist/core/loadtest.js +1051 -0
  157. package/dist/core/migrate.js +612 -0
  158. package/dist/core/monitor.js +494 -0
  159. package/dist/core/postready.js +976 -0
  160. package/dist/core/promote.js +804 -0
  161. package/dist/core/rcapi.js +1336 -0
  162. package/dist/core/recovery.js +75 -0
  163. package/dist/core/runner/engine.js +394 -0
  164. package/dist/core/runner/host.js +298 -0
  165. package/dist/core/runner/locks.js +129 -0
  166. package/dist/core/runner/paths.js +173 -0
  167. package/dist/core/runner/ports.js +172 -0
  168. package/dist/core/runner/queries.js +612 -0
  169. package/dist/core/runner/record.js +563 -0
  170. package/dist/core/scaleseed.js +271 -0
  171. package/dist/core/seed-db.js +208 -0
  172. package/dist/core/sessions.js +472 -0
  173. package/dist/core/skill.js +326 -0
  174. package/dist/core/sso-identities.js +172 -0
  175. package/dist/core/sso.js +703 -0
  176. package/dist/core/tls-local.js +311 -0
  177. package/dist/core/tls.js +878 -0
  178. package/dist/core/topology.js +482 -0
  179. package/dist/core/upgrade.js +877 -0
  180. package/dist/core/users.js +739 -0
  181. package/dist/lib/audit.js +100 -0
  182. package/dist/lib/close-matches.js +238 -0
  183. package/dist/lib/compose.js +672 -0
  184. package/dist/lib/config.js +1398 -0
  185. package/dist/lib/context.js +18 -0
  186. package/dist/lib/errors.js +305 -0
  187. package/dist/lib/events.js +208 -0
  188. package/dist/lib/float-text.js +126 -0
  189. package/dist/lib/format.js +1320 -0
  190. package/dist/lib/home.js +325 -0
  191. package/dist/lib/journal.js +122 -0
  192. package/dist/lib/json-text.js +733 -0
  193. package/dist/lib/jsonout.js +382 -0
  194. package/dist/lib/lock.js +516 -0
  195. package/dist/lib/login-name.js +202 -0
  196. package/dist/lib/map-limit.js +29 -0
  197. package/dist/lib/mkdir-parents.js +90 -0
  198. package/dist/lib/mongo-kernel.js +67 -0
  199. package/dist/lib/monitoring.js +492 -0
  200. package/dist/lib/platform-name.js +59 -0
  201. package/dist/lib/presets/common.js +390 -0
  202. package/dist/lib/presets/composite.js +326 -0
  203. package/dist/lib/presets/e2ee.js +143 -0
  204. package/dist/lib/presets/email.js +172 -0
  205. package/dist/lib/presets/guides.js +27 -0
  206. package/dist/lib/presets/index.js +490 -0
  207. package/dist/lib/presets/keycloak.js +371 -0
  208. package/dist/lib/presets/ldap.js +1285 -0
  209. package/dist/lib/presets/livechat.js +220 -0
  210. package/dist/lib/presets/multi-instance.js +124 -0
  211. package/dist/lib/presets/oidc.js +161 -0
  212. package/dist/lib/presets/public.js +496 -0
  213. package/dist/lib/presets/registry.js +64 -0
  214. package/dist/lib/presets/s3-minio.js +300 -0
  215. package/dist/lib/presets/saml.js +149 -0
  216. package/dist/lib/presets/scenario.js +51 -0
  217. package/dist/lib/presets/types.js +86 -0
  218. package/dist/lib/presets/voice-pbx.js +320 -0
  219. package/dist/lib/presets/voice.js +345 -0
  220. package/dist/lib/presets/webhooks.js +182 -0
  221. package/dist/lib/redact.js +106 -0
  222. package/dist/lib/seed-options.js +68 -0
  223. package/dist/lib/seed-profiles.js +59 -0
  224. package/dist/lib/targz.js +1383 -0
  225. package/dist/lib/teammode.js +25 -0
  226. package/dist/lib/tempdir.js +162 -0
  227. package/dist/lib/unicode-tables.js +2335 -0
  228. package/dist/lib/version-spec.js +357 -0
  229. package/dist/lib/versions.js +463 -0
  230. package/dist/lib/yaml-dump.js +1361 -0
  231. package/dist/perf/baseline.js +168 -0
  232. package/dist/perf/constrain.js +299 -0
  233. package/dist/perf/k6.js +235 -0
  234. package/dist/perf/mongoprof.js +171 -0
  235. package/dist/perf/rcmetrics.js +191 -0
  236. package/dist/perf/report.js +386 -0
  237. package/dist/perf/resources.js +236 -0
  238. package/dist/perf/slo.js +111 -0
  239. package/dist/perf/timeline.js +187 -0
  240. package/dist/perf/timings.js +85 -0
  241. package/dist/perf/verdict.js +201 -0
  242. package/dist/seams/aws-cli.js +126 -0
  243. package/dist/seams/docker-cli.js +280 -0
  244. package/dist/seams/exec.js +861 -0
  245. package/dist/seams/fs/lock.js +528 -0
  246. package/dist/seams/kubectl.js +83 -0
  247. package/dist/seams/rc-http.js +921 -0
  248. package/dist/seed/apply.js +190 -0
  249. package/dist/seed/assets.js +76 -0
  250. package/dist/seed/check.js +391 -0
  251. package/dist/seed/client.js +172 -0
  252. package/dist/seed/executor.js +726 -0
  253. package/dist/seed/history.js +281 -0
  254. package/dist/seed/kinds.js +91 -0
  255. package/dist/seed/plan.js +432 -0
  256. package/dist/seed/receipt.js +339 -0
  257. package/dist/seed/repairs.js +75 -0
  258. package/dist/seed/verification.js +363 -0
  259. package/dist/seed/wording.js +248 -0
  260. package/dist/web/app.js +326 -0
  261. package/dist/web/jobs.js +510 -0
  262. package/dist/web/route-deps.js +211 -0
  263. package/dist/web/route-table.js +213 -0
  264. package/dist/web/routes/backup.js +244 -0
  265. package/dist/web/routes/clusters.js +303 -0
  266. package/dist/web/routes/data.js +187 -0
  267. package/dist/web/routes/edge.js +82 -0
  268. package/dist/web/routes/index.js +63 -0
  269. package/dist/web/routes/jobs.js +95 -0
  270. package/dist/web/routes/logs.js +297 -0
  271. package/dist/web/routes/meta.js +191 -0
  272. package/dist/web/routes/people.js +151 -0
  273. package/dist/web/routes/perf.js +95 -0
  274. package/dist/web/routes/repros.js +550 -0
  275. package/dist/web/routes/session.js +361 -0
  276. package/dist/web/routes/spa.js +198 -0
  277. package/dist/web/security.js +475 -0
  278. package/dist/web/signin.js +246 -0
  279. package/package.json +70 -32
  280. package/.eslintrc +0 -94
  281. package/.swcrc +0 -18
  282. package/dist/bin.js +0 -3
  283. package/dist/cli.js +0 -184
  284. package/dist/commands/createBranch.js +0 -194
  285. package/dist/outputCI.js +0 -59
  286. package/src/bin.js +0 -4
  287. package/src/cli.ts +0 -25
  288. package/src/commands/createBranch.ts +0 -28
  289. package/src/outputCI.ts +0 -12
  290. package/src-old/logs.js +0 -323
  291. package/src-old/md.js +0 -191
  292. package/src-old/release-table.js +0 -60
  293. package/src-old/set-version.js +0 -614
  294. package/src-old/utils.js +0 -15
@@ -0,0 +1,768 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GRAFANA_DELETE_WAIT = exports.GRAFANA_KINDS = exports.CRD_WAIT = exports.PODMONITOR_CRD = exports.CERT_MANAGER_NAMESPACE = exports.GRAFANA_WAIT_INTERVAL = exports.GRAFANA_WAIT_TRIES = exports.GRAFANA_INGRESS_LABEL = exports.GRAFANA_PORT = exports.GRAFANA_DEPLOYMENT = exports.GRAFANA_SERVICE = exports.MONITORING_NAMESPACE = exports.MONITORING_CHART = exports.MONITORING_RELEASE = exports.MONITORING_LABEL = void 0;
4
+ exports.monitoringInstalled = monitoringInstalled;
5
+ exports.waitForGrafana = waitForGrafana;
6
+ exports.ensurePodMonitor = ensurePodMonitor;
7
+ exports.ensureMonitoring = ensureMonitoring;
8
+ exports.removeGrafanaIngress = removeGrafanaIngress;
9
+ exports.grafanaLeftovers = grafanaLeftovers;
10
+ exports.clearGrafanaFinalizers = clearGrafanaFinalizers;
11
+ exports.monitoringWanted = monitoringWanted;
12
+ exports.setMonitoringLabel = setMonitoringLabel;
13
+ exports.removeMonitoring = removeMonitoring;
14
+ exports.releaseSystemNamespace = releaseSystemNamespace;
15
+ /**
16
+ * Prometheus and Grafana in the cluster, attachable to any workspace.
17
+ *
18
+ * Shared, like the operator, and reference-counted the same careful way.
19
+ */
20
+ const errors_1 = require("../../lib/errors");
21
+ const events_1 = require("../../lib/events");
22
+ const monitoring_1 = require("../../lib/monitoring");
23
+ const ask_1 = require("./ask");
24
+ const capabilities_1 = require("./capabilities");
25
+ const exec_1 = require("./exec");
26
+ const names_1 = require("./names");
27
+ const operator_1 = require("./operator");
28
+ const release_1 = require("./release");
29
+ const realSleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
30
+ /**
31
+ * The namespace label that says a workspace wants the shared stack. One name, in one
32
+ * place: it was a literal at the setter AND a literal in the reference count, which is two
33
+ * chances to disagree about the thing that decides whether the shared stack gets
34
+ * uninstalled.
35
+ */
36
+ exports.MONITORING_LABEL = 'houston.io/monitoring';
37
+ exports.MONITORING_RELEASE = 'monitoring';
38
+ exports.MONITORING_CHART = `${names_1.HELM_REPO}/monitoring`;
39
+ /**
40
+ * Installed ONCE per cluster, next to the MongoDB operator, for the same reason and then
41
+ * one more. kube-prometheus-stack owns cluster-scoped CRDs, so a per-workspace install
42
+ * collides on them at the second workspace. And even with every dependency disabled the
43
+ * chart still renders a ClusterRole and ClusterRoleBinding at FIXED names plus a
44
+ * log-collector DaemonSet -- so the per-namespace install that looks like the compose
45
+ * shape does not compose either, and would put one collector per node per workspace on the
46
+ * same host paths.
47
+ *
48
+ * Sharing is also what makes this affordable: one 1.0 GB stack for every workspace on the
49
+ * box rather than 1.0 GB each, on a tool whose capacity preflight exists because it runs on
50
+ * laptops.
51
+ */
52
+ exports.MONITORING_NAMESPACE = operator_1.OPERATOR_NAMESPACE;
53
+ /**
54
+ * grafana-operator names the Grafana instance's Service this; `monitoring-grafana` is the
55
+ * operator itself and serves nothing useful. Forwarding the wrong one gives a page that
56
+ * loads and has no dashboards.
57
+ */
58
+ exports.GRAFANA_SERVICE = 'monitoring-grafana-service';
59
+ exports.GRAFANA_DEPLOYMENT = 'monitoring-grafana-deployment';
60
+ exports.GRAFANA_PORT = 3000;
61
+ exports.GRAFANA_INGRESS_LABEL = 'houston.io/grafana-ingress';
62
+ function bag(value) {
63
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
64
+ ? value
65
+ : {};
66
+ }
67
+ function containersOf(doc) {
68
+ const containers = bag(bag(bag(doc.spec).template).spec).containers;
69
+ return Array.isArray(containers) ? containers.map(bag) : [];
70
+ }
71
+ const GRAFANA_ENV = {
72
+ GF_SERVER_SERVE_FROM_SUB_PATH: 'true',
73
+ GF_AUTH_ANONYMOUS_ENABLED: 'true',
74
+ GF_AUTH_ANONYMOUS_ORG_ROLE: 'Viewer',
75
+ GF_SECURITY_ALLOW_EMBEDDING: 'true',
76
+ };
77
+ /** Share the same Logs dashboard as Docker, using the chart's Loki datasource. */
78
+ async function ensureLogsDashboard(context) {
79
+ const name = `${exports.MONITORING_RELEASE}-houston-logs`;
80
+ // APPLY_TIMEOUT for every must-answer question on the attach path, for the reason
81
+ // `removeGrafanaIngress` gives: a refusal fails the job, and nobody is waiting on a screen.
82
+ const seen = (0, ask_1.require_)(await (0, ask_1.askObject)('grafanadashboard', name, {
83
+ context,
84
+ namespace: exports.MONITORING_NAMESPACE,
85
+ timeout: names_1.APPLY_TIMEOUT,
86
+ }), 'the shared Logs dashboard', { context });
87
+ if ((0, ask_1.present)(seen) && bag(bag(seen.doc.metadata).labels)[names_1.OWNER_LABEL_KEY] !== names_1.OWNER_LABEL_VALUE)
88
+ throw new errors_1.CreateFailedError(`refusing to replace '${name}': it is not owned by houston`);
89
+ await (0, release_1.apply)(JSON.stringify({
90
+ apiVersion: 'grafana.integreatly.org/v1beta1',
91
+ kind: 'GrafanaDashboard',
92
+ metadata: {
93
+ name,
94
+ namespace: exports.MONITORING_NAMESPACE,
95
+ labels: { [names_1.OWNER_LABEL_KEY]: names_1.OWNER_LABEL_VALUE, dashboards: 'grafana' },
96
+ },
97
+ spec: {
98
+ allowCrossNamespaceImport: true,
99
+ folder: 'General',
100
+ instanceSelector: { matchLabels: { grafana: 'dashboards' } },
101
+ datasources: [{ inputName: 'DS_LOKI', datasourceName: 'loki' }],
102
+ // Docker provisions a fixed UID; the operator resolves ${DS_LOKI} to
103
+ // this cluster's chart-provisioned datasource named "loki".
104
+ json: (0, monitoring_1.dashboard)('houston-logs.json').replaceAll('"DS_LOKI"', '"${DS_LOKI}"'),
105
+ },
106
+ }), { context, namespace: exports.MONITORING_NAMESPACE });
107
+ }
108
+ /** The chart has no values for anonymous viewing or embedding, so configure its CR. */
109
+ async function configureGrafana(context, rootUrl) {
110
+ const seen = (0, ask_1.require_)(await (0, ask_1.askObject)('grafana', `${exports.MONITORING_RELEASE}-grafana`, {
111
+ context,
112
+ namespace: exports.MONITORING_NAMESPACE,
113
+ timeout: names_1.APPLY_TIMEOUT,
114
+ }), 'the shared Grafana configuration', { context });
115
+ if (!(0, ask_1.present)(seen))
116
+ throw new errors_1.CreateFailedError('the monitoring chart did not create Grafana');
117
+ const spec = bag(seen.doc.spec);
118
+ const containers = containersOf(bag(spec.deployment));
119
+ const grafana = containers.find((container) => container.name === 'grafana');
120
+ if (grafana === undefined)
121
+ throw new errors_1.CreateFailedError('the shared Grafana has no container configuration');
122
+ const env = Array.isArray(grafana.env) ? grafana.env.map(bag) : [];
123
+ const wanted = { ...GRAFANA_ENV, GF_SERVER_ROOT_URL: rootUrl };
124
+ if (Object.entries(wanted).every(([name, value]) => env.some((entry) => entry.name === name && entry.value === value)))
125
+ return false;
126
+ const updated = env.filter((entry) => !(String(entry.name) in wanted));
127
+ updated.push(...Object.entries(wanted).map(([name, value]) => ({ name, value })));
128
+ const res = await exec_1.kube.run([
129
+ 'kubectl',
130
+ '--context',
131
+ context,
132
+ '-n',
133
+ exports.MONITORING_NAMESPACE,
134
+ 'patch',
135
+ 'grafana',
136
+ `${exports.MONITORING_RELEASE}-grafana`,
137
+ '--type=merge',
138
+ '-p',
139
+ JSON.stringify({
140
+ spec: {
141
+ deployment: {
142
+ spec: {
143
+ template: {
144
+ spec: {
145
+ containers: containers.map((container) => container === grafana ? { ...container, env: updated } : container),
146
+ },
147
+ },
148
+ },
149
+ },
150
+ },
151
+ }),
152
+ ], { own: (0, names_1.isOurs)(context), timeout: names_1.APPLY_TIMEOUT });
153
+ if (res.returncode !== 0)
154
+ throw new errors_1.CreateFailedError(`could not configure shared Grafana: ${(0, ask_1.why)(res)}`);
155
+ return true;
156
+ }
157
+ /**
158
+ * Up to four minutes. The operator has to reconcile a Grafana CR into a Deployment and then
159
+ * pull its image, which is well past what helm's own wait allows for.
160
+ */
161
+ exports.GRAFANA_WAIT_TRIES = 48;
162
+ exports.GRAFANA_WAIT_INTERVAL = 5.0;
163
+ /**
164
+ * cert-manager's namespace is baked into its own manifests and its CRDs are cluster-scoped,
165
+ * so it is not one of ours to place.
166
+ */
167
+ exports.CERT_MANAGER_NAMESPACE = 'cert-manager';
168
+ /**
169
+ * Whether this cluster already has a WORKING shared stack.
170
+ *
171
+ * `helm status` exits 0 for a release in any state, including one a killed install left in
172
+ * `pending-install` -- so this returned true for a namespace holding no Prometheus and no
173
+ * Grafana, the install was skipped, and `monitor` reported the stack attached. The
174
+ * dashboards did not exist.
175
+ *
176
+ * Only `deployed` means there is something to leave alone; pending, failed and absent all
177
+ * mean the install below should run, and it is `upgrade --install`, so running it is the
178
+ * repair.
179
+ */
180
+ async function monitoringInstalled(context) {
181
+ try {
182
+ const [state] = await (0, release_1.releaseState)(exports.MONITORING_RELEASE, exports.MONITORING_NAMESPACE, context);
183
+ return state === 'deployed';
184
+ }
185
+ catch (error) {
186
+ // Could not ask. Not "installed" -- the caller's next step is an idempotent `upgrade
187
+ // --install`, which is the safer way to be wrong here.
188
+ if (error instanceof errors_1.DockerError)
189
+ return false;
190
+ throw error;
191
+ }
192
+ }
193
+ /**
194
+ * Wait for the Grafana the operator builds, in two steps, because it arrives late.
195
+ *
196
+ * `monitoring-grafana-deployment` does not exist when helm returns: the grafana-operator
197
+ * has to see the Grafana custom resource and create it. So this waits for the Deployment to
198
+ * EXIST and only then for it to be available -- `kubectl rollout status` on a missing
199
+ * Deployment is an error, not a wait, which would turn "not yet" into "failed".
200
+ */
201
+ async function waitForGrafana({ context, emit = events_1.nullEmit, sleep = realSleep, rootUrl = '', }) {
202
+ for (let attempt = 0; attempt < exports.GRAFANA_WAIT_TRIES; attempt += 1) {
203
+ if (rootUrl) {
204
+ const seen = (0, ask_1.require_)(await (0, ask_1.askObject)('deployment', exports.GRAFANA_DEPLOYMENT, {
205
+ context,
206
+ namespace: exports.MONITORING_NAMESPACE,
207
+ timeout: names_1.APPLY_TIMEOUT,
208
+ }), 'the shared Grafana deployment', { context });
209
+ if ((0, ask_1.present)(seen)) {
210
+ const spec = bag(seen.doc.spec);
211
+ const status = bag(seen.doc.status);
212
+ const env = containersOf(seen.doc).find((container) => container.name === 'grafana')?.env;
213
+ const wanted = { ...GRAFANA_ENV, GF_SERVER_ROOT_URL: rootUrl };
214
+ if (Array.isArray(env) &&
215
+ Object.entries(wanted).every(([name, value]) => env.some((entry) => bag(entry).name === name && bag(entry).value === value)) &&
216
+ Number(status.observedGeneration) >= Number(bag(seen.doc.metadata).generation) &&
217
+ Number(status.updatedReplicas) === Number(spec.replicas ?? 1) &&
218
+ Number(status.availableReplicas) >= Number(spec.replicas ?? 1))
219
+ return;
220
+ }
221
+ if (attempt % 5 === 0)
222
+ (0, events_1.info)(emit, 'waiting for Grafana to reconcile its /grafana configuration', {
223
+ phase: 'monitor',
224
+ });
225
+ await sleep(exports.GRAFANA_WAIT_INTERVAL);
226
+ continue;
227
+ }
228
+ const res = await exec_1.kube.run([
229
+ 'kubectl',
230
+ '--context',
231
+ context,
232
+ '-n',
233
+ exports.MONITORING_NAMESPACE,
234
+ 'get',
235
+ 'deployment',
236
+ exports.GRAFANA_DEPLOYMENT,
237
+ '-o',
238
+ 'jsonpath={.status.availableReplicas}',
239
+ ], { own: (0, names_1.isOurs)(context) });
240
+ const seen = res.stdout.trim();
241
+ if (seen !== '' && seen !== '0')
242
+ return;
243
+ if (attempt % 5 === 0)
244
+ (0, events_1.info)(emit, 'waiting for Grafana', { phase: 'monitor' });
245
+ await sleep(exports.GRAFANA_WAIT_INTERVAL);
246
+ }
247
+ (0, events_1.warn)(emit, 'Grafana has not come up yet; the stack is installed and it should appear shortly — ' +
248
+ `kubectl -n ${exports.MONITORING_NAMESPACE} get pods`, { phase: 'monitor' });
249
+ }
250
+ /** The kind the Rocket.Chat chart's PodMonitor is, which the shared stack brings. */
251
+ exports.PODMONITOR_CRD = 'podmonitors.monitoring.coreos.com';
252
+ /** How long a just-installed CRD gets to be served, in seconds. */
253
+ exports.CRD_WAIT = 60;
254
+ /**
255
+ * Have the workspace's release publish its PodMonitor, once the cluster can hold one.
256
+ *
257
+ * The chart renders its PodMonitor only where the cluster serves that kind, and a first
258
+ * `up --monitor` installs the release BEFORE the shared stack brings the CRD -- the stack
259
+ * waits for a workspace that serves. So helm rendered no PodMonitor, Prometheus had no target
260
+ * and Grafana's Rocket.Chat dashboard was empty, until a re-up happened to render the release
261
+ * again. Rendered again here instead, once the CRD is Established, when the chart wants a
262
+ * PodMonitor and the namespace has none; a release rendered after the CRD already has one.
263
+ */
264
+ async function ensurePodMonitor({ namespace, context, emit = events_1.nullEmit, }) {
265
+ const established = await exec_1.kube.run([
266
+ 'kubectl',
267
+ '--context',
268
+ context,
269
+ 'wait',
270
+ '--for=condition=Established',
271
+ `crd/${exports.PODMONITOR_CRD}`,
272
+ `--timeout=${String(exports.CRD_WAIT)}s`,
273
+ ], { timeout: exports.CRD_WAIT + names_1.APPLY_TIMEOUT, own: (0, names_1.isOurs)(context) });
274
+ if (established.returncode !== 0) {
275
+ (0, events_1.warn)(emit, `Prometheus cannot find Rocket.Chat: the cluster does not serve ${exports.PODMONITOR_CRD} ` +
276
+ `(${(0, ask_1.why)(established)})`, { phase: 'monitor' });
277
+ return;
278
+ }
279
+ const values = await (0, release_1.releaseValues)(names_1.RELEASE, namespace, context, { all: true });
280
+ if (bag(values.podMonitor).enabled !== true)
281
+ return; // a chart that publishes none
282
+ const monitors = (0, ask_1.require_)(await (0, ask_1.askList)('podmonitors', { context, namespace, timeout: names_1.APPLY_TIMEOUT }), `the PodMonitors in ${namespace}`, { context });
283
+ if ((0, ask_1.items)(monitors).length > 0)
284
+ return;
285
+ (0, events_1.info)(emit, 'rendering the Rocket.Chat release again, now that the cluster serves PodMonitors, so ' +
286
+ 'Prometheus finds it', { phase: 'monitor' });
287
+ await (0, release_1.rerenderRelease)(namespace, context);
288
+ }
289
+ /**
290
+ * Install the shared stack, or leave the existing one alone.
291
+ *
292
+ * The two `...SelectorNilUsesHelmValues=false` overrides are the whole reason a shared stack
293
+ * works. kube-prometheus-stack defaults them to true, which restricts Prometheus to monitors
294
+ * carrying its OWN release label -- so a workspace's PodMonitor, in a different namespace
295
+ * and a different release, is ignored and Grafana shows a dashboard with no data. Nothing
296
+ * errors; the graphs are simply empty.
297
+ *
298
+ * Rocket.Chat's own chart needs nothing: the PodMonitor is already its default. The scrape
299
+ * starts because the shared Prometheus is willing to look outside its own release, not
300
+ * because `--monitor` changed anything about the workspace.
301
+ */
302
+ async function ensureMonitoring({ context, emit = events_1.nullEmit, publicUrl = '', }) {
303
+ await exec_1.kube.run(['helm', 'repo', 'add', names_1.HELM_REPO, names_1.HELM_REPO_URL, '--force-update'], {
304
+ timeout: names_1.APPLY_TIMEOUT,
305
+ env: (0, exec_1.helmEnv)(context),
306
+ });
307
+ const installed = await monitoringInstalled(context);
308
+ let values = {};
309
+ if (installed) {
310
+ const result = await exec_1.kube.run([
311
+ 'helm',
312
+ 'get',
313
+ 'values',
314
+ exports.MONITORING_RELEASE,
315
+ '-n',
316
+ exports.MONITORING_NAMESPACE,
317
+ '--kube-context',
318
+ context,
319
+ '-o',
320
+ 'json',
321
+ ], { timeout: names_1.APPLY_TIMEOUT, env: (0, exec_1.helmEnv)(context) });
322
+ if (result.returncode !== 0)
323
+ throw new errors_1.DockerError(`could not read shared monitoring values: ${(0, ask_1.why)(result)}`);
324
+ try {
325
+ values = bag(JSON.parse(result.stdout));
326
+ }
327
+ catch {
328
+ throw new errors_1.DockerError('could not read shared monitoring values: invalid JSON');
329
+ }
330
+ }
331
+ const ingress = bag(values.ingress);
332
+ const grafana = bag(ingress.grafana);
333
+ const existingHost = typeof grafana.host === 'string' ? grafana.host : '';
334
+ const publicHost = publicUrl ? new URL(publicUrl).host : '';
335
+ // The first public host becomes canonical; later hosts share relative paths without
336
+ // flipping this shared setting and restarting everybody's Grafana.
337
+ // shortcut: one Grafana per cluster, so its root URL names the preferred loopback forward
338
+ // (5050); a second monitored workspace's forward on 5051 renders its dashboards, but links
339
+ // Grafana builds itself (sign-in redirects, share links) name 5050. Upgrade if that bites.
340
+ const host = existingHost && !(existingHost === 'localhost:5050' && publicHost)
341
+ ? existingHost
342
+ : publicHost || 'localhost:5050';
343
+ const tls = publicHost !== '' || ingress.tls === true;
344
+ const rootUrl = `${tls ? 'https' : 'http'}://${host}/grafana/`;
345
+ const upgrade = !installed ||
346
+ grafana.path !== '/grafana' ||
347
+ existingHost !== host ||
348
+ ingress.enabled !== false ||
349
+ ingress.tls !== tls;
350
+ if (!upgrade) {
351
+ (0, events_1.info)(emit, 'monitoring stack already on this cluster (shared)', { phase: 'monitor' });
352
+ if (await configureGrafana(context, rootUrl))
353
+ await waitForGrafana({ context, emit, rootUrl });
354
+ await ensureLogsDashboard(context);
355
+ return;
356
+ }
357
+ (0, events_1.info)(emit, installed
358
+ ? 'upgrading the SHARED monitoring stack to serve /grafana; Grafana restarts, and existing port-forwards must be re-established with `houston monitor`'
359
+ : `installing the monitoring stack in ${exports.MONITORING_NAMESPACE} (once per cluster, ~1 GB)`, { phase: 'monitor' });
360
+ // Deliberately NOT `--wait`. This chart creates grafana-operator custom resources in the
361
+ // same release that installs the operator, and helm's readiness check reaches them before
362
+ // the operator has reconciled anything -- "resource GrafanaDashboard/... not ready.
363
+ // status: NotFound" -- which is a race, not a failure: the stack came up perfectly well
364
+ // anyway, and ten pods were Running while helm reported it broken.
365
+ await (0, operator_1.waitForSystemNamespace)(context, emit);
366
+ await (0, release_1.clearPendingRelease)(exports.MONITORING_RELEASE, exports.MONITORING_NAMESPACE, context, { emit });
367
+ const res = await exec_1.kube.run([
368
+ 'helm',
369
+ 'upgrade',
370
+ ...(installed ? ['--reuse-values'] : ['--install']),
371
+ exports.MONITORING_RELEASE,
372
+ exports.MONITORING_CHART,
373
+ '--kube-context',
374
+ context,
375
+ '-n',
376
+ exports.MONITORING_NAMESPACE,
377
+ '--create-namespace',
378
+ '--set',
379
+ 'ingress.enabled=false',
380
+ '--set',
381
+ 'ingress.grafana.path=/grafana',
382
+ '--set-string',
383
+ `ingress.grafana.host=${host}`,
384
+ '--set',
385
+ `ingress.tls=${String(tls)}`,
386
+ '--set',
387
+ 'operator.prometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues=false',
388
+ '--set',
389
+ 'operator.prometheus.prometheusSpec.podMonitorSelectorNilUsesHelmValues=false',
390
+ '--timeout',
391
+ '9m',
392
+ ...(await (0, release_1.helmRollbackOnFailure)()),
393
+ ], { timeout: names_1.INSTALL_TIMEOUT, env: (0, exec_1.helmEnv)(context) });
394
+ if (res.returncode !== 0) {
395
+ throw new errors_1.CreateFailedError(`could not install the monitoring stack: ${(0, ask_1.why)(res)}`);
396
+ }
397
+ await configureGrafana(context, rootUrl);
398
+ await waitForGrafana({ context, emit, rootUrl });
399
+ await ensureLogsDashboard(context);
400
+ }
401
+ /** Remove only Houston-labelled Grafana routes, certificates and secrets. */
402
+ async function removeGrafanaIngress(workspace, { context, emit = events_1.nullEmit }) {
403
+ const selector = `${names_1.OWNER_SELECTOR},${exports.GRAFANA_INGRESS_LABEL}=true` +
404
+ (workspace ? `,${names_1.WORKSPACE_LABEL}=${workspace}` : '');
405
+ // APPLY_TIMEOUT, NOT THE PROBE'S 8 s. These questions must be answered -- a refusal fails
406
+ // the job -- and they run inside a teardown that has just waited a minute for a namespace
407
+ // to go, where nobody is waiting on a screen. MEASURED on EKS over a slow link: the
408
+ // workspace's namespace and volume were gone when the certificate question hit 8 s, and
409
+ // the whole `down` failed for a Grafana route.
410
+ const crd = (0, ask_1.require_)(await (0, ask_1.askObject)('customresourcedefinition', 'certificates.cert-manager.io', {
411
+ context,
412
+ timeout: names_1.APPLY_TIMEOUT,
413
+ }), 'the certificate API', { context });
414
+ const kinds = (0, ask_1.present)(crd) ? ['ingress', 'certificate', 'secret'] : ['ingress', 'secret'];
415
+ for (const kind of kinds) {
416
+ const seen = (0, ask_1.require_)(await (0, ask_1.askList)(kind, {
417
+ context,
418
+ namespace: exports.MONITORING_NAMESPACE,
419
+ selector,
420
+ timeout: names_1.APPLY_TIMEOUT,
421
+ }), `Grafana ${kind} resources`, { context });
422
+ if (!(0, ask_1.present)(seen))
423
+ continue;
424
+ if (!Array.isArray(seen.doc.items))
425
+ throw new errors_1.DockerError(`could not read Grafana ${kind} resources: invalid list`);
426
+ if (seen.doc.items.length === 0)
427
+ continue;
428
+ (0, events_1.info)(emit, `removing Grafana ${kind} resources${workspace ? ` for '${workspace}'` : ''}`, {
429
+ phase: 'monitor',
430
+ });
431
+ const result = await exec_1.kube.run([
432
+ 'kubectl',
433
+ '--context',
434
+ context,
435
+ '-n',
436
+ exports.MONITORING_NAMESPACE,
437
+ 'delete',
438
+ kind,
439
+ '-l',
440
+ selector,
441
+ '--ignore-not-found',
442
+ '--wait=true',
443
+ '--timeout=120s',
444
+ ], { own: (0, names_1.isOurs)(context), timeout: names_1.APPLY_TIMEOUT });
445
+ if (result.returncode !== 0)
446
+ throw new errors_1.DockerError(`could not remove Grafana ${kind} resources: ${(0, ask_1.why)(result)}`);
447
+ }
448
+ }
449
+ /**
450
+ * The grafana-operator custom resources this chart creates, in the order they must be
451
+ * deleted -- children before the Grafana instance that owns them.
452
+ */
453
+ exports.GRAFANA_KINDS = [
454
+ 'grafanadashboard',
455
+ 'grafanadatasource',
456
+ 'grafanafolder',
457
+ 'grafana',
458
+ ];
459
+ /**
460
+ * How long ONE kind's delete may block. Short on purpose: a delete that has not finished in
461
+ * this long is waiting on a finalizer nothing will clear, and the useful response is to
462
+ * clear it, not to keep waiting.
463
+ */
464
+ exports.GRAFANA_DELETE_WAIT = 15;
465
+ /**
466
+ * `[kind, name]` for every grafana-operator resource still present.
467
+ *
468
+ * Read AFTER a delete has been asked for and given a deadline, so a non-empty result means
469
+ * "these are not going to go on their own".
470
+ */
471
+ async function grafanaLeftovers(context) {
472
+ const out = [];
473
+ for (const kind of exports.GRAFANA_KINDS) {
474
+ const res = await exec_1.kube.run([
475
+ 'kubectl',
476
+ '--context',
477
+ context,
478
+ '-n',
479
+ exports.MONITORING_NAMESPACE,
480
+ 'get',
481
+ kind,
482
+ '-o',
483
+ 'jsonpath={.items[*].metadata.name}',
484
+ ], { own: (0, names_1.isOurs)(context) });
485
+ if (res.returncode !== 0)
486
+ continue; // the CRD is not installed; nothing to find
487
+ for (const name of res.stdout.split(/\s+/u).filter((entry) => entry !== '')) {
488
+ out.push([kind, name]);
489
+ }
490
+ }
491
+ return out;
492
+ }
493
+ /**
494
+ * Strip the operator finalizer from whatever is left, so the delete completes.
495
+ *
496
+ * A last resort, and safe as one: the operator that put the finalizer there is gone, so
497
+ * there is nothing whose cleanup we are skipping -- and the alternative is a namespace that
498
+ * sits in Terminating for ever and a release the next `--monitor` cannot install into.
499
+ */
500
+ async function clearGrafanaFinalizers(context) {
501
+ let cleared = 0;
502
+ for (const [kind, name] of await grafanaLeftovers(context)) {
503
+ const res = await exec_1.kube.run([
504
+ 'kubectl',
505
+ '--context',
506
+ context,
507
+ '-n',
508
+ exports.MONITORING_NAMESPACE,
509
+ 'patch',
510
+ kind,
511
+ name,
512
+ '--type=merge',
513
+ '-p',
514
+ '{"metadata":{"finalizers":[]}}',
515
+ ], { own: (0, names_1.isOurs)(context) });
516
+ if (res.returncode === 0)
517
+ cleared += 1;
518
+ }
519
+ return cleared;
520
+ }
521
+ /**
522
+ * Whether a workspace namespace is marked as wanting monitoring.
523
+ *
524
+ * A label on the namespace rather than a lookup in repro.json: `removeMonitoring` has to
525
+ * answer "does anyone else still want this?" about workspaces it is not holding the record
526
+ * for, and possibly ones created by a different user of the same cluster.
527
+ *
528
+ * NULL WHEN THE LABEL COULD NOT BE READ. This returned false for any failed call, and false
529
+ * here means "this workspace does not want monitoring" -- so it is the INNER test of the
530
+ * reference count. Fixing `workspaceNamespaces` to stop claiming an empty cluster does not
531
+ * help if the per-namespace question then answers "no" for a namespace nobody could read.
532
+ */
533
+ async function monitoringWanted(namespace, { context }) {
534
+ // `-o json` rather than a jsonpath, because an empty jsonpath result cannot say whether
535
+ // the LABEL is absent or the NAMESPACE is.
536
+ const seen = await (0, ask_1.askObject)('namespace', namespace, { context });
537
+ if ((0, ask_1.refused)(seen))
538
+ return null;
539
+ if ((0, ask_1.absent)(seen))
540
+ return false;
541
+ const meta = (0, ask_1.present)(seen) ? seen.doc.metadata : undefined;
542
+ const labels = meta !== null && typeof meta === 'object'
543
+ ? (meta.labels ?? {})
544
+ : {};
545
+ return String(labels[exports.MONITORING_LABEL] ?? '').trim() === 'true';
546
+ }
547
+ /**
548
+ * Mark (or unmark) a namespace as wanting the shared stack.
549
+ *
550
+ * THE MARK IS THE STACK'S REFERENCE COUNT, so one that did not land is raised, not ignored:
551
+ * an attach whose label was refused still recorded `monitoring: true`, and the next teardown
552
+ * of any other workspace counted nobody, uninstalled the stack and deleted its volumes. An
553
+ * unmark that did not land only keeps the stack, so that one is let go.
554
+ */
555
+ async function setMonitoringLabel(namespace, { context, wanted }) {
556
+ const res = await exec_1.kube.run([
557
+ 'kubectl',
558
+ '--context',
559
+ context,
560
+ 'label',
561
+ '--overwrite',
562
+ 'namespace',
563
+ namespace,
564
+ wanted ? `${exports.MONITORING_LABEL}=true` : `${exports.MONITORING_LABEL}-`,
565
+ ], { own: (0, names_1.isOurs)(context) });
566
+ if (wanted && res.returncode !== 0) {
567
+ throw new errors_1.DockerError(`could not mark namespace ${namespace} as using the shared monitoring stack: ${(0, ask_1.why)(res)} ` +
568
+ "— monitoring was not attached, so another workspace's teardown cannot remove the " +
569
+ 'stack from under it');
570
+ }
571
+ }
572
+ /** Namespaces other than `excluding` that still request the shared stack. */
573
+ async function monitoringConsumers(context, excluding, emit) {
574
+ const held = await (0, capabilities_1.workspaceNamespaces)(context);
575
+ if (held === null) {
576
+ (0, events_1.warn)(emit, "not removing the shared monitoring stack: the cluster's namespace list could not be " +
577
+ 'read, so whether another workspace still wants it is unknown', { phase: 'monitor' });
578
+ return null;
579
+ }
580
+ const others = [];
581
+ for (const ns of held) {
582
+ if (ns === excluding)
583
+ continue;
584
+ const wants = await monitoringWanted(ns, { context });
585
+ if (wants === null) {
586
+ (0, events_1.warn)(emit, `not removing the shared monitoring stack: could not read whether ${ns} still wants it`, { phase: 'monitor' });
587
+ return null;
588
+ }
589
+ if (wants)
590
+ others.push(ns);
591
+ }
592
+ return others;
593
+ }
594
+ /** Delete operator resources before uninstalling the operator that finalises them. */
595
+ async function removeGrafanaResources(context, emit) {
596
+ // The grafana-operator's own resources go FIRST, while the operator that processes their
597
+ // finalizers is still running. Letting helm delete everything at once deadlocks: it
598
+ // removes the operator Deployment and then waits on a GrafanaFolder whose finalizer
599
+ // nothing is left to clear.
600
+ //
601
+ // The ordering is not sufficient when the operator is already gone: the resources then
602
+ // spend their full delete timeout waiting for finalizers nothing can clear. So the deletes
603
+ // get a SHORT deadline and are then CHECKED.
604
+ (0, events_1.info)(emit, 'removing the Grafana resources', { phase: 'monitor' });
605
+ for (const kind of exports.GRAFANA_KINDS) {
606
+ await exec_1.kube.run([
607
+ 'kubectl',
608
+ '--context',
609
+ context,
610
+ '-n',
611
+ exports.MONITORING_NAMESPACE,
612
+ 'delete',
613
+ kind,
614
+ '--all',
615
+ '--ignore-not-found',
616
+ `--timeout=${String(exports.GRAFANA_DELETE_WAIT)}s`,
617
+ ], { timeout: names_1.APPLY_TIMEOUT, own: (0, names_1.isOurs)(context) });
618
+ }
619
+ const stuck = await grafanaLeftovers(context);
620
+ if (stuck.length > 0) {
621
+ (0, events_1.warn)(emit, `${String(stuck.length)} Grafana resource(s) will not delete — nothing is left to ` +
622
+ 'clear their finalizers, so clearing them now', { phase: 'monitor' });
623
+ await clearGrafanaFinalizers(context);
624
+ }
625
+ }
626
+ /** Uninstall Helm while retaining the best-effort finalizer recovery. */
627
+ async function uninstallMonitoringRelease(context, emit) {
628
+ (0, events_1.info)(emit, 'uninstalling the monitoring release', { phase: 'monitor' });
629
+ const res = await exec_1.kube.run([
630
+ 'helm',
631
+ 'uninstall',
632
+ exports.MONITORING_RELEASE,
633
+ '--kube-context',
634
+ context,
635
+ '-n',
636
+ exports.MONITORING_NAMESPACE,
637
+ '--wait',
638
+ '--timeout',
639
+ '5m',
640
+ ], { timeout: names_1.INSTALL_TIMEOUT, own: (0, names_1.isOurs)(context) });
641
+ if (res.returncode !== 0) {
642
+ // The release is removed either way; a stuck finalizer must not leave the cluster in a
643
+ // state the next `--monitor` cannot install into.
644
+ await clearGrafanaFinalizers(context);
645
+ (0, events_1.warn)(emit, `the monitoring stack needed its finalizers cleared by hand: ${(0, ask_1.why)(res)}`, {
646
+ phase: 'monitor',
647
+ });
648
+ }
649
+ }
650
+ /** Remove the Prometheus claims Helm deliberately leaves behind. */
651
+ async function reclaimMonitoringVolumes(context, emit) {
652
+ const pvcs = await exec_1.kube.run(['kubectl', '--context', context, '-n', exports.MONITORING_NAMESPACE, 'get', 'pvc', '-o', 'name'], { timeout: names_1.APPLY_TIMEOUT, own: (0, names_1.isOurs)(context) });
653
+ const names = pvcs.stdout
654
+ .split('\n')
655
+ .map((line) => line.trim())
656
+ .filter((line) => line !== '');
657
+ if (pvcs.returncode !== 0) {
658
+ (0, events_1.warn)(emit, 'could not check whether the monitoring stack left a volume behind — `kubectl -n ' +
659
+ `${exports.MONITORING_NAMESPACE} get pvc\` shows it`, { phase: 'monitor' });
660
+ return;
661
+ }
662
+ if (names.length === 0)
663
+ return;
664
+ const gone = await exec_1.kube.run([
665
+ 'kubectl',
666
+ '--context',
667
+ context,
668
+ '-n',
669
+ exports.MONITORING_NAMESPACE,
670
+ 'delete',
671
+ 'pvc',
672
+ '--all',
673
+ '--ignore-not-found',
674
+ `--timeout=${String(exports.GRAFANA_DELETE_WAIT)}s`,
675
+ ], { timeout: names_1.APPLY_TIMEOUT, own: (0, names_1.isOurs)(context) });
676
+ if (gone.returncode === 0) {
677
+ (0, events_1.info)(emit, `reclaimed ${String(names.length)} monitoring volume(s)`, { phase: 'monitor' });
678
+ }
679
+ else {
680
+ (0, events_1.warn)(emit, `the monitoring stack's ${String(names.length)} volume(s) could not be reclaimed and ` +
681
+ `are still allocated: ${(0, ask_1.why)(gone)}`, { phase: 'monitor' });
682
+ }
683
+ }
684
+ /**
685
+ * Uninstall the shared stack. Returns false if another workspace still wants it.
686
+ *
687
+ * Shared, so `--off` on one workspace must not blind the others. This is the whole
688
+ * behavioural difference from Compose, where the stack belongs to a project and detaching it
689
+ * is unambiguous.
690
+ *
691
+ * `excluding` is the namespace of a workspace being DESTROYED, and it exists because the
692
+ * count reads a label on the namespace while `workspaceNamespaces` does not filter by phase:
693
+ * a namespace still Terminating is still listed and still labelled, so a teardown asking
694
+ * "does anyone else want this?" would be told yes by the workspace it is deleting.
695
+ */
696
+ async function removeMonitoring({ context, excluding = '', emit = events_1.nullEmit, }) {
697
+ // Nothing installed is nothing to report. Without this, `monitor --off` on a workspace
698
+ // that never had monitoring ran the uninstall anyway, helm answered "release: not found",
699
+ // and the fallback path announced that "the monitoring stack needed its finalizers cleared
700
+ // by hand" -- a frightening sentence about wreckage that did not exist.
701
+ if (!(await (0, operator_1.releaseInstalled)(exports.MONITORING_RELEASE, exports.MONITORING_NAMESPACE, context)))
702
+ return false;
703
+ const others = await monitoringConsumers(context, excluding, emit);
704
+ if (others === null)
705
+ return false;
706
+ if (others.length > 0) {
707
+ (0, events_1.info)(emit, 'leaving the monitoring stack up — still used by ' +
708
+ others
709
+ .map((ns) => (ns.startsWith(names_1.NAMESPACE_PREFIX) ? ns.slice(names_1.NAMESPACE_PREFIX.length) : ns))
710
+ .sort()
711
+ .join(', '), { phase: 'monitor' });
712
+ return false;
713
+ }
714
+ await removeGrafanaIngress('', { context, emit });
715
+ await removeGrafanaResources(context, emit);
716
+ await uninstallMonitoringRelease(context, emit);
717
+ // THE PROMETHEUS VOLUME, which helm does not take with the release. A StatefulSet's
718
+ // PersistentVolumeClaims outlive it by design -- that is what keeps a workspace's MongoDB
719
+ // data across a plain `down` -- but nothing here ever deleted these: a clean `monitor
720
+ // --off` left a 10 Gi claim Bound, permanently. On a laptop that is disk; on EKS it is a
721
+ // billed EBS volume nobody can see the source of. Deleted by NAMESPACE, not by label: the
722
+ // chart's PVCs carry its own labels, not houston's, and this namespace is houston's own.
723
+ await reclaimMonitoringVolumes(context, emit);
724
+ await releaseSystemNamespace(context, emit);
725
+ return true;
726
+ }
727
+ /**
728
+ * `houston-system`, once nothing of houston's needs it.
729
+ *
730
+ * helm made it (`--create-namespace`) for the operator and the monitoring stack, and
731
+ * neither removal took it: after the last workspace was gone it stayed, holding a webhook
732
+ * Secret the monitoring chart leaves behind. Removed only when neither release is there
733
+ * (an unreadable release counts as there) and no workload or volume is left in it -- an
734
+ * operator adopted rather than installed lives here too, and is not houston's to delete.
735
+ */
736
+ async function releaseSystemNamespace(context, emit) {
737
+ if (await (0, operator_1.releaseInstalled)(exports.MONITORING_RELEASE, exports.MONITORING_NAMESPACE, context))
738
+ return;
739
+ if (await (0, operator_1.releaseInstalled)(operator_1.OPERATOR_RELEASE, operator_1.OPERATOR_NAMESPACE, context))
740
+ return;
741
+ const left = await (0, ask_1.askList)('deployments,statefulsets,daemonsets,jobs,pvc', {
742
+ context,
743
+ namespace: operator_1.OPERATOR_NAMESPACE,
744
+ });
745
+ if (!(0, ask_1.present)(left) || (0, ask_1.items)(left).length > 0)
746
+ return;
747
+ const res = await exec_1.kube.run([
748
+ 'kubectl',
749
+ '--context',
750
+ context,
751
+ 'delete',
752
+ 'namespace',
753
+ operator_1.OPERATOR_NAMESPACE,
754
+ '--wait=true',
755
+ '--timeout=90s',
756
+ ], { timeout: names_1.APPLY_TIMEOUT, own: (0, names_1.isOurs)(context) });
757
+ if (res.returncode === 0) {
758
+ (0, events_1.info)(emit, `removed the ${operator_1.OPERATOR_NAMESPACE} namespace — nothing of houston's uses it now`, {
759
+ phase: 'teardown',
760
+ });
761
+ }
762
+ else if (!(0, ask_1.absent)((0, ask_1.classify)(res, { single: true }))) {
763
+ // NotFound is the answer this asked for: a workspace that never had monitoring took
764
+ // `down` here and warned that it "could not confirm" a namespace already gone.
765
+ (0, events_1.warn)(emit, `could not confirm ${operator_1.OPERATOR_NAMESPACE} is gone: ${(0, ask_1.why)(res)} — a new operator or ` +
766
+ 'monitoring install must wait for its deletion to finish', { phase: 'teardown' });
767
+ }
768
+ }