@rocket.chat/houston 0.27.0-next.2 → 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 (291) 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 -192
  284. package/src/bin.js +0 -4
  285. package/src/cli.ts +0 -25
  286. package/src/commands/createBranch.ts +0 -25
  287. package/src-old/logs.js +0 -323
  288. package/src-old/md.js +0 -191
  289. package/src-old/release-table.js +0 -60
  290. package/src-old/set-version.js +0 -614
  291. package/src-old/utils.js +0 -15
@@ -0,0 +1,941 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.WATCH_ENV = exports.MONGODB_CRD = exports.LICENSE_KEY = exports.LICENSE_SECRET = exports.REG_TOKEN_KEY = exports.REG_TOKEN_SECRET = exports.MONGO_URL_SECRET = exports.USE_OPERATOR_ENV = exports.MONGO_DB_SERVICE_ACCOUNT = exports.MONGO_APP_DB = exports.MONGO_APP_USER = exports.MONGO_ADMIN_USER = exports.OPERATOR_MIN_MONGO = exports.OPERATOR_CHART = exports.OPERATOR_REPO_URL = exports.OPERATOR_REPO = exports.OPERATOR_RELEASE = exports.OPERATOR_NAMESPACE = void 0;
37
+ exports.operatorEnabled = operatorEnabled;
38
+ exports.operatorSupports = operatorSupports;
39
+ exports.wouldUseOperator = wouldUseOperator;
40
+ exports.mongoRbacManifest = mongoRbacManifest;
41
+ exports.mongoSecretManifest = mongoSecretManifest;
42
+ exports.operatorVersion = operatorVersion;
43
+ exports.mongodbCommunityManifest = mongodbCommunityManifest;
44
+ exports.licenseSecretManifest = licenseSecretManifest;
45
+ exports.regTokenSecretManifest = regTokenSecretManifest;
46
+ exports.mongoUrlSecretManifest = mongoUrlSecretManifest;
47
+ exports.operatorMongoUrl = operatorMongoUrl;
48
+ exports.mongoToolAuth = mongoToolAuth;
49
+ exports.toolAuthenticated = toolAuthenticated;
50
+ exports.shellAuthenticated = shellAuthenticated;
51
+ exports.operatorPresence = operatorPresence;
52
+ exports.operatorIsOurs = operatorIsOurs;
53
+ exports.operatorWatchScope = operatorWatchScope;
54
+ exports.operatorWatches = operatorWatches;
55
+ exports.waitForSystemNamespace = waitForSystemNamespace;
56
+ exports.ensureOperator = ensureOperator;
57
+ exports.mongodbResources = mongodbResources;
58
+ exports.releaseInstalled = releaseInstalled;
59
+ exports.operatorInstalled = operatorInstalled;
60
+ exports.removeOperator = removeOperator;
61
+ exports.waitForMongodb = waitForMongodb;
62
+ /**
63
+ * The MongoDB Community operator: installing it, owning it, and knowing when it is
64
+ * somebody else's.
65
+ *
66
+ * Shared across every workspace on the cluster, so nothing here removes it without checking
67
+ * who else is using it -- and a list that could not be read is never proof that nobody is.
68
+ */
69
+ const YAML = __importStar(require("yaml"));
70
+ const config = __importStar(require("../../lib/config"));
71
+ const errors_1 = require("../../lib/errors");
72
+ const events_1 = require("../../lib/events");
73
+ const ask_1 = require("./ask");
74
+ const exec_1 = require("./exec");
75
+ const manifests_1 = require("./manifests");
76
+ const names_1 = require("./names");
77
+ const namespace_1 = require("./namespace");
78
+ const release_1 = require("./release");
79
+ const replicaset_1 = require("./replicaset");
80
+ const realSleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
81
+ /**
82
+ * The operator lives ONCE per cluster, in houston's own namespace, watching all
83
+ * namespaces. The official guide installs it into the workspace namespace because it
84
+ * assumes one Rocket.Chat per cluster; its CRDs are cluster-scoped, so a second
85
+ * per-namespace install collides on them rather than giving you a second operator.
86
+ */
87
+ exports.OPERATOR_NAMESPACE = 'houston-system';
88
+ exports.OPERATOR_RELEASE = 'mongodb-kubernetes-operator';
89
+ exports.OPERATOR_REPO = 'mongodb';
90
+ exports.OPERATOR_REPO_URL = 'https://mongodb.github.io/helm-charts';
91
+ exports.OPERATOR_CHART = `${exports.OPERATOR_REPO}/mongodb-kubernetes`;
92
+ /**
93
+ * The oldest MongoDB the operator will manage. Below this houston falls back to the
94
+ * hand-written StatefulSet, which is why that code stays: houston pairs twelve MongoDB
95
+ * versions because "the customer's exact version" is the product's promise, and the
96
+ * operator's window does not reach the old half.
97
+ *
98
+ * 6.0 was a guess, and this is what came of checking it: the operator's own documentation
99
+ * states NO minimum server version; its image repository publishes tags back to 4.4, so
100
+ * the pullable floor is 4.4; and 6.0 is verified live end to end. So 6.0 stays --
101
+ * deliberately conservative, now evidenced rather than invented.
102
+ */
103
+ exports.OPERATOR_MIN_MONGO = [6, 0];
104
+ /** SCRAM users, matching the guide's names so its commands transfer. */
105
+ exports.MONGO_ADMIN_USER = 'admin';
106
+ exports.MONGO_APP_USER = 'rocketchat';
107
+ exports.MONGO_APP_DB = 'rocketchat';
108
+ /**
109
+ * The ServiceAccount the operator puts on the database pod. Not configurable and not
110
+ * namespaced to the operator: the StatefulSet the operator writes into OUR namespace names
111
+ * this account, so it has to exist THERE, not where the operator runs.
112
+ */
113
+ exports.MONGO_DB_SERVICE_ACCOUNT = 'mongodb-kubernetes-appdb';
114
+ /**
115
+ * The operator is OPT-IN until it is proven, and the reason is a regression. The
116
+ * hand-written StatefulSet was verified end to end on a live cluster -- admin login, PVC
117
+ * Bound, data surviving a down/up cycle. Routing MongoDB 6.0+ to the operator by default
118
+ * replaced that with a path whose PVC never binds. A default that breaks the working case
119
+ * is worse than a missing feature.
120
+ */
121
+ exports.USE_OPERATOR_ENV = 'HOUSTON_MONGO_OPERATOR';
122
+ /** Whether to use the operator at all. Off by default -- see `USE_OPERATOR_ENV`. */
123
+ function operatorEnabled() {
124
+ return ['1', 'true', 'yes'].includes(config.env(exports.USE_OPERATOR_ENV).trim().toLowerCase());
125
+ }
126
+ /**
127
+ * Whether the operator will manage this MongoDB version.
128
+ *
129
+ * `forced` is `--mongo-operator`: the user asked for it explicitly, so the opt-in switch is
130
+ * satisfied and only the VERSION floor still applies. Asking for the operator on MongoDB
131
+ * 5.0 still falls back, because the operator cannot manage it -- silently ignoring the flag
132
+ * would be worse than the fallback.
133
+ */
134
+ function operatorSupports(mongoTag, { forced = false } = {}) {
135
+ if (!forced && !operatorEnabled())
136
+ return false;
137
+ const parts = String(mongoTag)
138
+ .split('.')
139
+ .slice(0, 2)
140
+ .map((part) => Number.parseInt(part, 10));
141
+ if (parts.length !== 2 || parts.some((part) => !Number.isFinite(part)))
142
+ return false;
143
+ const [major, minor] = parts;
144
+ const [floorMajor, floorMinor] = exports.OPERATOR_MIN_MONGO;
145
+ return major > floorMajor || (major === floorMajor && minor >= floorMinor);
146
+ }
147
+ /** Whether a create would put MongoDB under the operator: asked for, and able to run it. */
148
+ function wouldUseOperator(mongoTag, forced) {
149
+ return (forced || operatorEnabled()) && operatorSupports(mongoTag, { forced });
150
+ }
151
+ /** A label block at the manifest indent the templates below use. */
152
+ function labelBlock(name, owner) {
153
+ return Object.entries((0, namespace_1.labelsFor)(name, owner))
154
+ .map(([key, value]) => ` ${(0, manifests_1.scalar)(key)}: ${(0, manifests_1.scalar)(value)}`)
155
+ .join('\n');
156
+ }
157
+ /** Render the namespaced service account, role and binding. */
158
+ function mongoRbacDocument(lab) {
159
+ return `apiVersion: v1
160
+ kind: ServiceAccount
161
+ metadata:
162
+ name: ${exports.MONGO_DB_SERVICE_ACCOUNT}
163
+ labels:
164
+ ${lab}
165
+ ---
166
+ apiVersion: rbac.authorization.k8s.io/v1
167
+ kind: Role
168
+ metadata:
169
+ name: ${exports.MONGO_DB_SERVICE_ACCOUNT}
170
+ labels:
171
+ ${lab}
172
+ rules:
173
+ - apiGroups: [""]
174
+ resources: ["secrets"]
175
+ verbs: ["get"]
176
+ - apiGroups: [""]
177
+ resources: ["pods"]
178
+ verbs: ["patch", "delete", "get"]
179
+ ---
180
+ apiVersion: rbac.authorization.k8s.io/v1
181
+ kind: RoleBinding
182
+ metadata:
183
+ name: ${exports.MONGO_DB_SERVICE_ACCOUNT}
184
+ labels:
185
+ ${lab}
186
+ roleRef:
187
+ apiGroup: rbac.authorization.k8s.io
188
+ kind: Role
189
+ name: ${exports.MONGO_DB_SERVICE_ACCOUNT}
190
+ subjects:
191
+ - kind: ServiceAccount
192
+ name: ${exports.MONGO_DB_SERVICE_ACCOUNT}
193
+ `;
194
+ }
195
+ /**
196
+ * The database pod's ServiceAccount, Role and RoleBinding, in OUR namespace.
197
+ *
198
+ * The guide never mentions these because it installs the operator into the same namespace
199
+ * as MongoDB, where the operator's own chart creates them. houston cannot do that, so the
200
+ * operator lives once in `houston-system` and watches everything -- which works for
201
+ * reconciliation and silently does not work for the database pod.
202
+ *
203
+ * Missing, the failure names none of this: the "forbidden: error looking up service
204
+ * account" is an event on the StatefulSet, while the MongoDBCommunity resource -- the thing
205
+ * anyone would look at -- reports only "Pending ReplicaSet is not yet ready", forever. No
206
+ * pod is ever created, so `WaitForFirstConsumer` keeps both PVCs Pending, which points at
207
+ * storage, which is not the problem.
208
+ */
209
+ function mongoRbacManifest(name, { owner = '' } = {}) {
210
+ return mongoRbacDocument(labelBlock(name, owner));
211
+ }
212
+ /**
213
+ * The guide's Secrets, with generated passwords rather than placeholders.
214
+ *
215
+ * `stringData` so Kubernetes does the base64; writing it ourselves is one more place to get
216
+ * wrong. The passwords never touch disk on this side -- the manifest goes to `kubectl
217
+ * apply` on stdin.
218
+ */
219
+ function mongoSecretManifest(name, { adminPassword, appPassword, owner = '', }) {
220
+ const lab = labelBlock(name, owner);
221
+ const secret = (sname, data) => {
222
+ const body = Object.entries(data)
223
+ .map(([key, value]) => ` ${(0, manifests_1.scalar)(key)}: ${(0, manifests_1.scalar)(value)}`)
224
+ .join('\n');
225
+ return (`---\napiVersion: v1\nkind: Secret\nmetadata:\n name: ${sname}\n` +
226
+ ` labels:\n${lab}\ntype: Opaque\nstringData:\n${body}\n`);
227
+ };
228
+ return [
229
+ secret('mongodb-admin-password', { password: adminPassword }),
230
+ secret('mongodb-rocketchat-password', { password: appPassword }),
231
+ secret('admin-scram-credentials', { username: exports.MONGO_ADMIN_USER, password: adminPassword }),
232
+ secret('rocketchat-scram-credentials', { username: exports.MONGO_APP_USER, password: appPassword }),
233
+ ].join('');
234
+ }
235
+ /**
236
+ * A full MongoDB release version for the operator's `spec.version`.
237
+ *
238
+ * houston carries a Docker TAG -- "8.0" -- because that is what pulls an image. The operator
239
+ * wants a RELEASE version and the guide shows "8.0.0"; given "8.0" it accepts the resource
240
+ * and then never reconciles it, so the workspace sits at no `.status.phase` until the wait
241
+ * gives up. The failure names nothing: the resource exists, the operator is healthy, and
242
+ * MongoDB simply never appears.
243
+ */
244
+ function operatorVersion(tag) {
245
+ const parts = String(tag).split('.');
246
+ while (parts.length < 3)
247
+ parts.push('0');
248
+ return parts.slice(0, 3).join('.');
249
+ }
250
+ /** The data and logs claims required by the operator-managed pod. */
251
+ function mongodbVolumeClaims(storageGb) {
252
+ return ` volumeClaimTemplates:
253
+ - metadata:
254
+ name: data-volume
255
+ spec:
256
+ accessModes: ["ReadWriteOnce"]
257
+ resources:
258
+ requests:
259
+ storage: ${String(storageGb)}Gi
260
+ # \`logs-volume\` as well as \`data-volume\`, because overriding
261
+ # volumeClaimTemplates REPLACES the operator's list rather than merging with
262
+ # it -- confirmed by watching a run that declared only data-volume produce
263
+ # exactly one PVC -- while both of the pod's containers mount both volumes:
264
+ #
265
+ # mongod: data-volume ... logs-volume ...
266
+ # mongodb-agent: data-volume ... logs-volume ...
267
+ #
268
+ # so a template list that drops one leaves the pod referencing a claim nothing
269
+ # creates. The guide shows only data-volume because its example is the whole
270
+ # override, and it is reproduced here in full for the same reason.
271
+ - metadata:
272
+ name: logs-volume
273
+ spec:
274
+ accessModes: ["ReadWriteOnce"]
275
+ resources:
276
+ requests:
277
+ storage: 2Gi
278
+ `;
279
+ }
280
+ /**
281
+ * The guide's MongoDBCommunity resource.
282
+ *
283
+ * `type: ReplicaSet` with `members: 1` is what makes this worth doing: the operator owns
284
+ * initiation, readiness and the bootstrap DNS -- the three things that produced four
285
+ * separate live failures when this module did them by hand.
286
+ *
287
+ * The text is the established one byte for byte, as it reaches `kubectl apply -f -`:
288
+ * `version:` is always double-quoted there (the tag is validated to letters, digits, `.`,
289
+ * `_` and `-` before it gets here), and two YAML comments keep their established full
290
+ * length.
291
+ */
292
+ function mongodbCommunityManifest(name, tag, { owner = '', storageGb = names_1.MONGO_VOLUME_GB } = {}) {
293
+ return `apiVersion: mongodbcommunity.mongodb.com/v1
294
+ kind: MongoDBCommunity
295
+ metadata:
296
+ name: ${names_1.MONGO_SERVICE}
297
+ labels:
298
+ ${labelBlock(name, owner)}
299
+ spec:
300
+ members: 1
301
+ type: ReplicaSet
302
+ version: "${operatorVersion(tag)}"
303
+ security:
304
+ authentication:
305
+ modes: ["SCRAM"]
306
+ tls:
307
+ enabled: false
308
+ users:
309
+ - name: ${exports.MONGO_ADMIN_USER}
310
+ db: admin
311
+ passwordSecretRef:
312
+ name: mongodb-admin-password
313
+ scramCredentialsSecretName: admin-scram-credentials
314
+ roles:
315
+ - name: root
316
+ db: admin
317
+ - name: ${exports.MONGO_APP_USER}
318
+ db: ${exports.MONGO_APP_DB}
319
+ passwordSecretRef:
320
+ name: mongodb-rocketchat-password
321
+ scramCredentialsSecretName: rocketchat-scram-credentials
322
+ roles:
323
+ - name: readWrite
324
+ db: ${exports.MONGO_APP_DB}
325
+ # clusterMonitor is what makes MONGO_OPLOG_URL work, and it is what Rocket.Chat's
326
+ # OWN chart grants: templates/mongodb-init-configmap.yaml runs
327
+ # db.getSiblingDB('<db>').grantRolesToUser('<user>',
328
+ # [{ role: 'clusterMonitor', db: 'admin' }])
329
+ # against its bundled MongoDB, commenting "having clusterMonitor role shouldn't
330
+ # hurt". readWrite on the app database alone cannot read \`local\`, so Rocket.Chat
331
+ # below 8.x -- the only versions that still tail the oplog -- could authenticate
332
+ # and then fail to tail. This is upstream's answer, not an invention.
333
+ - name: clusterMonitor
334
+ db: admin
335
+ statefulSet:
336
+ spec:
337
+ # The mongod container's own limits, merged by container name. The operator's default
338
+ # is a 500M limit, and mongodump and mongorestore run INSIDE this container, under that
339
+ # same limit: a backup seconds after a re-up had the container OOMKilled, and Rocket.Chat
340
+ # crash-looping with it. These are the hand-written StatefulSet's values, which run the
341
+ # same tools in the same place; a limit is a ceiling, not a reservation.
342
+ template:
343
+ spec:
344
+ containers:
345
+ - name: mongod
346
+ resources:
347
+ requests:
348
+ cpu: 100m
349
+ memory: 256Mi
350
+ limits:
351
+ memory: 2Gi
352
+ ${mongodbVolumeClaims(storageGb)}`;
353
+ }
354
+ /**
355
+ * The Secret the chart reads its MongoDB URL from, instead of the URL sitting in the
356
+ * release's values where `helm get values rocketchat` prints it in full -- password
357
+ * included -- to anyone with read access to the namespace.
358
+ */
359
+ exports.MONGO_URL_SECRET = 'rocketchat-mongodb-url';
360
+ /**
361
+ * The EE registration token travels in its own Opaque Secret, referenced from the container
362
+ * env by `valueFrom`. NEVER in helm values or `extraEnv` as a literal: values are readable
363
+ * with `helm get values`, and houston also writes them to
364
+ * `repros/<n>/kubernetes/values.yaml` for a human to read. The manifest goes to stdin so the
365
+ * token never appears in argv either, where `ps` would show it to every user on the box.
366
+ */
367
+ exports.REG_TOKEN_SECRET = 'houston-reg-token';
368
+ exports.REG_TOKEN_KEY = 'token';
369
+ /**
370
+ * The Enterprise licence, the same way: its own Secret, `valueFrom` in the container env.
371
+ * Not the chart's own `license:` value, which renders the licence into the Deployment in
372
+ * plain text and turns on LICENSE_DEBUG.
373
+ */
374
+ exports.LICENSE_SECRET = 'houston-license';
375
+ exports.LICENSE_KEY = 'license';
376
+ /** An Opaque Secret holding the Enterprise licence. */
377
+ function licenseSecretManifest(name, { license, owner = '' }) {
378
+ return YAML.stringify({
379
+ apiVersion: 'v1',
380
+ kind: 'Secret',
381
+ metadata: { name: exports.LICENSE_SECRET, labels: (0, namespace_1.labelsFor)(name, owner) },
382
+ type: 'Opaque',
383
+ stringData: { [exports.LICENSE_KEY]: license },
384
+ }, { compat: 'yaml-1.1', indentSeq: false, lineWidth: 0 });
385
+ }
386
+ /** An Opaque Secret holding the cloud registration token. */
387
+ function regTokenSecretManifest(name, { token, owner = '' }) {
388
+ return YAML.stringify({
389
+ apiVersion: 'v1',
390
+ kind: 'Secret',
391
+ metadata: { name: exports.REG_TOKEN_SECRET, labels: (0, namespace_1.labelsFor)(name, owner) },
392
+ type: 'Opaque',
393
+ stringData: { [exports.REG_TOKEN_KEY]: token },
394
+ }, { compat: 'yaml-1.1', indentSeq: false, lineWidth: 0 });
395
+ }
396
+ /**
397
+ * A Secret holding the connection strings, for `existingMongodbSecret`.
398
+ *
399
+ * BOTH keys, always. Chart 6.26.0 reads `mongo-uri` and `mongo-oplog-uri` from this Secret
400
+ * unconditionally once `existingMongodbSecret` is set -- there is no `if oplog` around the
401
+ * second one -- so omitting it on a chart that wants it leaves the pod unable to start on a
402
+ * missing key.
403
+ */
404
+ function mongoUrlSecretManifest(name, { mongoUrl, oplogUrl, owner = '' }) {
405
+ return `apiVersion: v1
406
+ kind: Secret
407
+ metadata:
408
+ name: ${exports.MONGO_URL_SECRET}
409
+ labels:
410
+ ${labelBlock(name, owner)}
411
+ type: Opaque
412
+ stringData:
413
+ mongo-uri: ${(0, manifests_1.scalar)(mongoUrl)}
414
+ mongo-oplog-uri: ${(0, manifests_1.scalar)(oplogUrl)}
415
+ `;
416
+ }
417
+ /**
418
+ * The authenticated URI, built as the guide builds it.
419
+ *
420
+ * The operator names its service `<name>-svc`, not `<name>` -- a detail worth stating,
421
+ * because the hand-written path uses the bare name and the two are not interchangeable.
422
+ *
423
+ * `authSource` is on BOTH forms, and the oplog one is where it was missing. The oplog URL
424
+ * addresses the `local` DATABASE, but the user is defined in the app database -- and
425
+ * without authSource the driver authenticates against the database in the path, so it
426
+ * looked for a user in `local` that has never existed there.
427
+ */
428
+ function operatorMongoUrl(namespace, password, { oplog = false } = {}) {
429
+ const db = oplog ? 'local' : exports.MONGO_APP_DB;
430
+ return (`mongodb://${exports.MONGO_APP_USER}:${password}@` +
431
+ `${names_1.MONGO_SERVICE}-0.${names_1.MONGO_SERVICE}-svc.${namespace}.svc.cluster.local:27017/` +
432
+ `${db}?replicaSet=${names_1.MONGO_SERVICE}&authSource=${exports.MONGO_APP_DB}`);
433
+ }
434
+ /**
435
+ * The application user's password, for the database tools under an operator-managed MongoDB;
436
+ * '' when it cannot be read.
437
+ *
438
+ * The operator enables SCRAM, so an unauthenticated `mongodump` fails with "Command
439
+ * listCollections requires authentication" -- which is exactly what it did: backup was
440
+ * broken on the operator path, the path the official guide recommends, while working
441
+ * perfectly on the hand-written StatefulSet that has no auth.
442
+ *
443
+ * The password is read back out of the Secret rather than kept anywhere: it is generated at
444
+ * create time and deliberately never written to disk. It reaches the tools on STDIN, through
445
+ * `toolAuthenticated` and `shellAuthenticated` below, never as an argument.
446
+ */
447
+ async function mongoToolAuth(name, { context }) {
448
+ const res = await exec_1.kube.run([
449
+ 'kubectl',
450
+ '--context',
451
+ context,
452
+ '-n',
453
+ await (0, namespace_1.namespaceFor)(name),
454
+ 'get',
455
+ 'secret',
456
+ 'mongodb-rocketchat-password',
457
+ '-o',
458
+ 'jsonpath={.data.password}',
459
+ ], { own: (0, names_1.isOurs)(context) });
460
+ const encoded = res.stdout.trim();
461
+ if (res.returncode !== 0 || encoded === '')
462
+ return '';
463
+ try {
464
+ return Buffer.from(encoded, 'base64').toString('utf8').trim();
465
+ }
466
+ catch {
467
+ return '';
468
+ }
469
+ }
470
+ /**
471
+ * Hands a database tool its password as a `--config` file made from the first line of stdin,
472
+ * then runs it on the rest of stdin -- `mongorestore --archive` reads its archive there.
473
+ *
474
+ * NEVER AN ARGUMENT, here or on the host. `ps` shows every command line on the machine, and a
475
+ * local cluster's pods share the host's process table: `--password` in this argv was readable
476
+ * by any user, in the tool's command line, in `kubectl exec`'s and in the exec seam's relay.
477
+ * The file is 0600 in the pod's own /tmp and is unlinked before the tool starts; the tool
478
+ * reads it through the descriptor the shell keeps open. `read` and `printf` are shell
479
+ * builtins, so the line is never an argument of a process either.
480
+ */
481
+ const CONFIG_FROM_STDIN = 'IFS= read -r line || exit 1; umask 077; f=$(mktemp) || exit 1; ' +
482
+ 'printf "%s\\n" "$line" > "$f"; exec 3< "$f"; rm -f "$f"; exec "$@" --config=/dev/fd/3';
483
+ /**
484
+ * A `mongodump`/`mongorestore` argv authenticated as the application user, and what goes on
485
+ * its stdin first.
486
+ *
487
+ * authenticationDatabase is the APP database, not `admin`: the app user is DEFINED in the
488
+ * application database, and authenticating against admin looks for a user that was never
489
+ * created there.
490
+ */
491
+ function toolAuthenticated(argv, password) {
492
+ return [
493
+ [
494
+ 'sh',
495
+ '-c',
496
+ CONFIG_FROM_STDIN,
497
+ 'sh',
498
+ ...argv,
499
+ '--username',
500
+ exports.MONGO_APP_USER,
501
+ '--authenticationDatabase',
502
+ exports.MONGO_APP_DB,
503
+ ],
504
+ // A JSON string is a YAML double-quoted scalar, and keeps the line one line.
505
+ `password: ${JSON.stringify(password)}\n`,
506
+ ];
507
+ }
508
+ /**
509
+ * `mongosh` running `script` against `database` as the application user, and its stdin.
510
+ *
511
+ * The script comes in on stdin and connects first, as the seed does, because the shell has
512
+ * no way to take a password other than an argument. Always `mongosh`: the operator manages
513
+ * MongoDB 6.0 and later, whose images ship no other shell. A WRITABLE HOME, or the shell's own
514
+ * ~/.mongodb warning fills the output in the operator's pod, whose user's home is not writable.
515
+ */
516
+ function shellAuthenticated(database, script, password) {
517
+ const uri = `mongodb://${exports.MONGO_APP_USER}:${encodeURIComponent(password)}@127.0.0.1:27017/` +
518
+ `${encodeURIComponent(database)}?authSource=${exports.MONGO_APP_DB}&directConnection=true`;
519
+ return [
520
+ ['env', 'HOME=/tmp', 'mongosh', '--quiet', '--nodb', '--file', '/dev/stdin'],
521
+ `var db = connect(${JSON.stringify(uri)});\n${script}\n`,
522
+ ];
523
+ }
524
+ /**
525
+ * The CRD that defines "MongoDBCommunity resources exist in this cluster". Presence is keyed
526
+ * on this and NOT on houston's release name: an operator a platform team installed --
527
+ * different namespace, different release, or plain manifests -- is invisible to a question
528
+ * asked about our release.
529
+ */
530
+ exports.MONGODB_CRD = 'mongodbcommunity.mongodb.com';
531
+ /**
532
+ * The env var the community operator reads to decide what it reconciles. Empty means its own
533
+ * namespace only; `*` means the whole cluster.
534
+ */
535
+ exports.WATCH_ENV = 'WATCH_NAMESPACE';
536
+ /**
537
+ * Whether a MongoDB Community operator's CRD is here, whoever installed it.
538
+ *
539
+ * THE ASYMMETRY THIS CLOSES: cert-manager is keyed on its CRD and ingress on any existing
540
+ * IngressClass, and both therefore ADOPT a foreign install. The MongoDB operator was the one
541
+ * place that principle was not applied -- it asked whether houston's own release existed in
542
+ * houston's own namespace, so a platform team's operator was invisible and `helm upgrade
543
+ * --install` ran anyway.
544
+ */
545
+ async function operatorPresence(context) {
546
+ return await (0, ask_1.askObject)('crd', exports.MONGODB_CRD, { context });
547
+ }
548
+ /**
549
+ * Whether the CRD in `seen` is managed by houston's own helm release.
550
+ *
551
+ * Helm stamps every resource it manages with `meta.helm.sh/release-name` and
552
+ * `meta.helm.sh/release-namespace`, so the CRD itself says who owns it. A CRD with no such
553
+ * annotations was applied by something other than helm and is nobody's release; it is
554
+ * emphatically not ours.
555
+ */
556
+ function operatorIsOurs(seen) {
557
+ const doc = (0, ask_1.present)(seen) ? seen.doc : {};
558
+ const meta = doc.metadata;
559
+ const annotations = meta !== null && typeof meta === 'object'
560
+ ? (meta.annotations ?? {})
561
+ : {};
562
+ return (annotations['meta.helm.sh/release-name'] === exports.OPERATOR_RELEASE &&
563
+ annotations['meta.helm.sh/release-namespace'] === exports.OPERATOR_NAMESPACE);
564
+ }
565
+ /**
566
+ * `[what the operator on this cluster watches, why that could not be read]`.
567
+ *
568
+ * An adopted operator is only useful if it reconciles the namespace the workspace goes in.
569
+ *
570
+ * BEST EFFORT, and the caller must treat a reason as "I could not ask" rather than as "it
571
+ * does not watch us". Adopting is the action that installs nothing, so it is the safe thing
572
+ * to do when the scope is unknown; refusing on ignorance would break every cluster whose
573
+ * operator we simply could not introspect.
574
+ */
575
+ async function operatorWatchScope(context) {
576
+ const found = await (0, ask_1.askList)('deployments', { context, allNamespaces: true });
577
+ if ((0, ask_1.refused)(found)) {
578
+ return ['', found.res !== undefined ? (0, ask_1.why)(found.res, { limit: 120 }) : 'could not be listed'];
579
+ }
580
+ for (const dep of (0, ask_1.items)(found)) {
581
+ const spec = dep.spec;
582
+ for (const container of spec?.template?.spec?.containers ?? []) {
583
+ for (const env of (container.env ?? [])) {
584
+ if (env.name !== exports.WATCH_ENV)
585
+ continue;
586
+ // `valueFrom` (a fieldRef to the pod's own namespace) is the chart's
587
+ // single-namespace default. It is a real answer -- own namespace only -- and not
588
+ // an unreadable one.
589
+ if (!('value' in env)) {
590
+ const meta = dep.metadata;
591
+ return [meta?.namespace ?? '', ''];
592
+ }
593
+ return [String(env.value ?? ''), ''];
594
+ }
595
+ }
596
+ }
597
+ return ['', 'no operator Deployment was found'];
598
+ }
599
+ /** Whether `scope` covers `namespace`. `*` or empty-with-no-reason means all. */
600
+ function operatorWatches(scope, namespace) {
601
+ if (scope === '*' || scope === '')
602
+ return true;
603
+ return scope
604
+ .split(',')
605
+ .map((part) => part.trim())
606
+ .filter((part) => part !== '')
607
+ .includes(namespace);
608
+ }
609
+ /** Wait out an earlier teardown before Helm can reuse its shared namespace. */
610
+ async function waitForSystemNamespace(context, emit) {
611
+ const seen = await (0, ask_1.askObject)('namespace', exports.OPERATOR_NAMESPACE, {
612
+ context,
613
+ timeout: names_1.APPLY_TIMEOUT,
614
+ });
615
+ if ((0, ask_1.refused)(seen)) {
616
+ throw new errors_1.DockerError(`could not read namespace ${exports.OPERATOR_NAMESPACE}: ${(0, ask_1.answerWhy)(seen)}`);
617
+ }
618
+ if (!(0, ask_1.present)(seen))
619
+ return;
620
+ const metadata = seen.doc.metadata;
621
+ const status = seen.doc.status;
622
+ const deleting = typeof metadata?.deletionTimestamp === 'string' && metadata.deletionTimestamp !== '';
623
+ if (!deleting && status?.phase !== 'Terminating')
624
+ return;
625
+ (0, events_1.info)(emit, `waiting for ${exports.OPERATOR_NAMESPACE} to finish its previous teardown`, {
626
+ phase: 'provision',
627
+ });
628
+ const res = await exec_1.kube.run([
629
+ 'kubectl',
630
+ '--context',
631
+ context,
632
+ 'wait',
633
+ '--for=delete',
634
+ `namespace/${exports.OPERATOR_NAMESPACE}`,
635
+ '--timeout=90s',
636
+ ], { timeout: names_1.APPLY_TIMEOUT, own: (0, names_1.isOurs)(context) });
637
+ if (res.returncode !== 0) {
638
+ // It may have disappeared between the read and kubectl's wait invocation. Only
639
+ // the cluster confirming absence makes that a successful wait.
640
+ const after = await (0, ask_1.askObject)('namespace', exports.OPERATOR_NAMESPACE, {
641
+ context,
642
+ timeout: names_1.APPLY_TIMEOUT,
643
+ });
644
+ if ((0, ask_1.absent)(after))
645
+ return;
646
+ throw new errors_1.CreateFailedError(`${exports.OPERATOR_NAMESPACE} has not finished its previous teardown: ${(0, ask_1.why)(res)}`);
647
+ }
648
+ }
649
+ /** Install houston's shared operator release after adoption checks pass. */
650
+ async function installOperator(context, emit) {
651
+ await waitForSystemNamespace(context, emit);
652
+ await exec_1.kube.run(['helm', 'repo', 'add', exports.OPERATOR_REPO, exports.OPERATOR_REPO_URL, '--force-update'], {
653
+ timeout: names_1.APPLY_TIMEOUT,
654
+ env: (0, exec_1.helmEnv)(context),
655
+ });
656
+ await exec_1.kube.run(['helm', 'repo', 'update', exports.OPERATOR_REPO], {
657
+ timeout: names_1.APPLY_TIMEOUT,
658
+ env: (0, exec_1.helmEnv)(context),
659
+ });
660
+ (0, events_1.info)(emit, `MongoDB operator in ${exports.OPERATOR_NAMESPACE} (once per cluster)`, {
661
+ phase: 'provision',
662
+ pct: 15,
663
+ });
664
+ // A KILLED INSTALL WEDGES THIS FOR EVERY WORKSPACE ON THE CLUSTER, which is why it matters
665
+ // more here than for a workspace's own release: `houston-system` is shared, so one Ctrl-C
666
+ // inside the five-minute `--wait` leaves every later `--mongo-operator` failing with
667
+ // "another operation is in progress".
668
+ await (0, release_1.clearPendingRelease)(exports.OPERATOR_RELEASE, exports.OPERATOR_NAMESPACE, context, { emit });
669
+ const res = await exec_1.kube.run([
670
+ 'helm',
671
+ 'upgrade',
672
+ '--install',
673
+ exports.OPERATOR_RELEASE,
674
+ exports.OPERATOR_CHART,
675
+ '--kube-context',
676
+ context,
677
+ '-n',
678
+ exports.OPERATOR_NAMESPACE,
679
+ '--create-namespace',
680
+ '--set',
681
+ 'operator.watchNamespace=*',
682
+ // TELEMETRY OFF. The chart sends the cluster UID, the Kubernetes version and
683
+ // deployment UIDs to MongoDB on a weekly timer, enabled by default. Nobody using a
684
+ // support reproduction tool opted into third-party analytics about the cluster they
685
+ // are debugging on, and on a customer's adopted cluster houston would be the thing
686
+ // that started it.
687
+ '--set',
688
+ 'operator.telemetry.send.enabled=false',
689
+ '--set',
690
+ 'operator.telemetry.collection.enabled=false',
691
+ '--wait',
692
+ '--timeout',
693
+ '5m',
694
+ ...(await (0, release_1.helmRollbackOnFailure)()),
695
+ ], { timeout: names_1.INSTALL_TIMEOUT, env: (0, exec_1.helmEnv)(context) });
696
+ if (res.returncode !== 0) {
697
+ throw new errors_1.CreateFailedError(`could not install the MongoDB operator: ${(0, ask_1.why)(res)}`);
698
+ }
699
+ }
700
+ /**
701
+ * Install the MongoDB operator once for the cluster, watching all namespaces.
702
+ *
703
+ * Cluster-scoped by necessity, not by preference: the chart manages CRDs, and CRDs are not
704
+ * namespaced. Installing it per workspace collides on them at the second workspace.
705
+ *
706
+ * AND IT ADOPTS RATHER THAN INSTALLS when the operator is somebody else's.
707
+ */
708
+ async function ensureOperator({ context, namespace = '', emit = events_1.nullEmit, }) {
709
+ // ASKED BEFORE ANYTHING IS WRITTEN, including the helm repo add. Nothing below this point
710
+ // should run on a cluster whose operator houston does not own.
711
+ const seen = await operatorPresence(context);
712
+ if (seen.state === ask_1.REFUSED) {
713
+ // "I could not ask" is not "there is none", and the action on the other side of this
714
+ // question installs CLUSTER-SCOPED CRDs. Getting it wrong on a shared cluster reaches
715
+ // other people's databases, so this is the one place the module's rule has to produce a
716
+ // refusal rather than a best guess.
717
+ throw new errors_1.PreflightError('cannot tell whether this cluster already has a MongoDB operator: the ' +
718
+ `${exports.MONGODB_CRD} CRD could not be read (` +
719
+ (seen.res !== undefined ? (0, ask_1.why)(seen.res, { limit: 160 }) : 'no reason given') +
720
+ '). Installing one anyway would take ownership of cluster-scoped CRDs that may ' +
721
+ 'belong to somebody else. Grant read on customresourcedefinitions, or run without ' +
722
+ "`--mongo-operator` to use the chart's own MongoDB.");
723
+ }
724
+ if ((0, ask_1.present)(seen) && !operatorIsOurs(seen)) {
725
+ const [scope, unreadable] = await operatorWatchScope(context);
726
+ // AGAINST THE NAMESPACE THIS WORKSPACE ACTUALLY GOES IN. houston's namespaces are
727
+ // `houston-<name>`, a prefix and not one fixed name. With no namespace to check the
728
+ // scope is not a question that can be answered, so it is not asked.
729
+ if (namespace !== '' && unreadable === '' && !operatorWatches(scope, namespace)) {
730
+ // A real answer, and it does not cover us. Said as a refusal rather than left to
731
+ // become a five-minute timeout on a workspace whose database nothing was ever going
732
+ // to reconcile.
733
+ throw new errors_1.PreflightError('this cluster has a MongoDB operator that houston did not install, and it watches ' +
734
+ `'${scope}' — which does not include '${namespace}'. Installing a second ` +
735
+ 'cluster-scoped operator beside it would have both reconcile the same resources. ' +
736
+ 'Ask whoever owns it to watch `*`, or run without `--mongo-operator`.');
737
+ }
738
+ const adopted = unreadable === ''
739
+ ? `watching ${scope !== '' ? scope : 'its own namespace'}`
740
+ : `scope unread: ${unreadable}`;
741
+ (0, events_1.info)(emit, `adopting the MongoDB operator already in this cluster (${adopted}) — houston ` +
742
+ 'installs nothing and removes nothing', { phase: 'provision', pct: 15 });
743
+ return;
744
+ }
745
+ await installOperator(context, emit);
746
+ }
747
+ /**
748
+ * Namespaces that still hold a `MongoDBCommunity`, i.e. still need the operator.
749
+ *
750
+ * Empty when the CRD is not installed at all, which is the answer, not an error.
751
+ */
752
+ async function mongodbResources(context) {
753
+ const res = await exec_1.kube.run([
754
+ 'kubectl',
755
+ '--context',
756
+ context,
757
+ 'get',
758
+ 'mongodbcommunity',
759
+ '-A',
760
+ '--ignore-not-found',
761
+ '-o',
762
+ 'jsonpath={range .items[*]}{.metadata.namespace}{"\\n"}{end}',
763
+ ], { timeout: names_1.APPLY_TIMEOUT, own: (0, names_1.isOurs)(context) });
764
+ if (res.returncode !== 0) {
765
+ // null, not []: this is the SHARED operator's reference count, and an empty one means
766
+ // "uninstall it". A read nobody could perform is not evidence that nothing needs it.
767
+ return null;
768
+ }
769
+ return [...new Set(res.stdout.split(/\s+/u).filter((entry) => entry !== ''))].sort();
770
+ }
771
+ /**
772
+ * Whether a helm release is in this cluster. Used before uninstalling one, so "there was
773
+ * nothing there" is reported as nothing rather than as a failure.
774
+ */
775
+ async function releaseInstalled(release, namespace, context) {
776
+ try {
777
+ return (await (0, release_1.releaseState)(release, namespace, context))[0] !== '';
778
+ }
779
+ catch (error) {
780
+ // These callers ask before an uninstall. Not knowing is not "absent", and the uninstall
781
+ // itself reports its own failure honestly, so let it try.
782
+ if (error instanceof errors_1.DockerError)
783
+ return true;
784
+ throw error;
785
+ }
786
+ }
787
+ /** Whether the shared MongoDB operator release is in this cluster. */
788
+ async function operatorInstalled(context) {
789
+ return await releaseInstalled(exports.OPERATOR_RELEASE, exports.OPERATOR_NAMESPACE, context);
790
+ }
791
+ /** Remove houston's operator release while retaining its shared CRD. */
792
+ async function uninstallOperator(context, emit) {
793
+ (0, events_1.info)(emit, `uninstalling the MongoDB operator from ${exports.OPERATOR_NAMESPACE} — nothing is using it now`, { phase: 'teardown' });
794
+ const res = await exec_1.kube.run([
795
+ 'helm',
796
+ 'uninstall',
797
+ exports.OPERATOR_RELEASE,
798
+ '--kube-context',
799
+ context,
800
+ '-n',
801
+ exports.OPERATOR_NAMESPACE,
802
+ '--wait',
803
+ '--timeout',
804
+ '5m',
805
+ ], { timeout: names_1.INSTALL_TIMEOUT, own: (0, names_1.isOurs)(context) });
806
+ if (res.returncode !== 0) {
807
+ // Not an error worth failing a teardown for: the workspace is already gone and the next
808
+ // `--mongo-operator` runs `upgrade --install`, which repairs it.
809
+ (0, events_1.warn)(emit, `the MongoDB operator could not be uninstalled and is still running in ` +
810
+ `${exports.OPERATOR_NAMESPACE}: ${(0, ask_1.why)(res)}`, { phase: 'teardown' });
811
+ return false;
812
+ }
813
+ await removeTheOperatorWebhook(context, emit);
814
+ (0, events_1.info)(emit, 'the MongoDB operator is gone; its CRDs stay on purpose — removing them would delete ' +
815
+ "every MongoDBCommunity in the cluster, another workspace's database included", { phase: 'teardown' });
816
+ return true;
817
+ }
818
+ /** Registered by the operator itself at startup: no Helm label, so `helm uninstall` leaves it. */
819
+ const OPERATOR_WEBHOOK = 'mdbpolicy.mongodb.com';
820
+ /**
821
+ * Delete that webhook, which would otherwise point at a Service just deleted -- but only when
822
+ * every hook in it points into houston's operator namespace. Anything else is somebody else's
823
+ * operator; and a read refused or absent leaves it be, since it fails open (`Ignore`).
824
+ */
825
+ async function removeTheOperatorWebhook(context, emit) {
826
+ const answer = await (0, ask_1.askObject)('validatingwebhookconfiguration', OPERATOR_WEBHOOK, { context });
827
+ if (!(0, ask_1.present)(answer))
828
+ return;
829
+ const hooks = Array.isArray(answer.doc.webhooks) ? answer.doc.webhooks : [];
830
+ const into = hooks.map((hook) => hook?.clientConfig
831
+ ?.service?.namespace);
832
+ if (into.length === 0 || into.some((namespace) => namespace !== exports.OPERATOR_NAMESPACE))
833
+ return;
834
+ const res = await exec_1.kube.run([
835
+ 'kubectl',
836
+ '--context',
837
+ context,
838
+ 'delete',
839
+ 'validatingwebhookconfiguration',
840
+ OPERATOR_WEBHOOK,
841
+ '--ignore-not-found',
842
+ ], { timeout: names_1.APPLY_TIMEOUT, own: (0, names_1.isOurs)(context) });
843
+ if (res.returncode !== 0) {
844
+ (0, events_1.warn)(emit, `the operator's webhook ${OPERATOR_WEBHOOK} could not be removed (it fails open, so ` +
845
+ `nothing is blocked): ${(0, ask_1.why)(res)}`, { phase: 'teardown' });
846
+ }
847
+ }
848
+ /**
849
+ * Uninstall the shared MongoDB operator once nothing is using it any more.
850
+ *
851
+ * The ORDER is what makes removing it safe rather than destructive. The custom resources go
852
+ * FIRST, and they already have: this is called after the workspace's namespace is deleted,
853
+ * which takes its `MongoDBCommunity` with it while the operator is still alive to clear the
854
+ * finalizer. Removing the operator first deadlocks on a resource nothing is left to
855
+ * finalise, and the namespace then sits in Terminating forever.
856
+ *
857
+ * The reference count is a real check: with a second workspace still holding a
858
+ * `MongoDBCommunity`, removing the operator leaves its finalizer with nothing to clear it.
859
+ *
860
+ * The CRD stays. `helm uninstall` does not remove it anyway, and deleting it would delete
861
+ * every `MongoDBCommunity` in the cluster -- every other workspace's database, instantly.
862
+ */
863
+ async function removeOperator({ context, excluding = '', emit = events_1.nullEmit, }) {
864
+ // OURS, DELIBERATELY, and this is the guard that makes adoption safe: an operator houston
865
+ // adopted was never installed as our release, so this answers false for it and the
866
+ // uninstall below is never reached.
867
+ if (!(await operatorInstalled(context)))
868
+ return false;
869
+ // `excluding` because the workspace being destroyed must not be counted as still needing
870
+ // the operator. Its MongoDBCommunity is normally gone by the time the namespace finishes,
871
+ // but "normally" is a race.
872
+ const using = await mongodbResources(context);
873
+ if (using === null) {
874
+ (0, events_1.warn)(emit, 'not removing the shared MongoDB operator: its MongoDBCommunity resources could not ' +
875
+ 'be listed, so whether another workspace still needs it is unknown. Removing it ' +
876
+ 'would leave their finalizers with nothing to clear.', { phase: 'teardown' });
877
+ return false;
878
+ }
879
+ const still = using.filter((ns) => ns !== excluding);
880
+ if (still.length > 0) {
881
+ (0, events_1.info)(emit, 'leaving the MongoDB operator up — still used by ' +
882
+ still
883
+ .map((ns) => (ns.startsWith(names_1.NAMESPACE_PREFIX) ? ns.slice(names_1.NAMESPACE_PREFIX.length) : ns))
884
+ .join(', '), { phase: 'teardown' });
885
+ return false;
886
+ }
887
+ return await uninstallOperator(context, emit);
888
+ }
889
+ /**
890
+ * Wait for the operator to report the MongoDBCommunity Running.
891
+ *
892
+ * The operator owns initiation and readiness, so this asks IT rather than poking mongod --
893
+ * which is the whole point of using it. `.status.phase` is the resource's own answer; there
894
+ * is no exec, no rs.initiate and no readiness probe to race.
895
+ */
896
+ async function waitForMongodb({ namespace, context, emit = events_1.nullEmit, sleep = realSleep, }) {
897
+ for (let attempt = 0; attempt < names_1.tuning.MONGO_READY_TRIES; attempt += 1) {
898
+ const res = await exec_1.kube.run([
899
+ 'kubectl',
900
+ '--context',
901
+ context,
902
+ '-n',
903
+ namespace,
904
+ 'get',
905
+ 'mongodbcommunity',
906
+ names_1.MONGO_SERVICE,
907
+ '-o',
908
+ 'jsonpath={.status.phase}',
909
+ ], { own: (0, names_1.isOurs)(context) });
910
+ if (res.stdout.trim() === 'Running') {
911
+ (0, events_1.info)(emit, 'MongoDB ready (operator-managed, SCRAM)', { phase: 'boot' });
912
+ return;
913
+ }
914
+ if (attempt % 6 === 0) {
915
+ (0, events_1.info)(emit, 'waiting for the operator to bring MongoDB up', { phase: 'wait' });
916
+ }
917
+ await sleep(replicaset_1.MONGO_READY_INTERVAL);
918
+ }
919
+ // Say what the resource itself reports. An empty phase means the operator never reconciled
920
+ // it at all -- which is what an unusable `spec.version` looks like, and "did not come up"
921
+ // sent the reader to the wrong place for it.
922
+ const detail = await exec_1.kube.run([
923
+ 'kubectl',
924
+ '--context',
925
+ context,
926
+ '-n',
927
+ namespace,
928
+ 'get',
929
+ 'mongodbcommunity',
930
+ names_1.MONGO_SERVICE,
931
+ '-o',
932
+ 'jsonpath={.status.phase}{" "}{.status.message}',
933
+ ], { own: (0, names_1.isOurs)(context) });
934
+ const said = detail.stdout.trim();
935
+ throw new errors_1.CreateFailedError('the operator did not bring MongoDB up' +
936
+ (said !== ''
937
+ ? ` — it reports: ${said}`
938
+ : ' — and reports no status at all, which means it never reconciled the resource ' +
939
+ '(usually an unusable spec.version)') +
940
+ `. kubectl -n ${namespace} describe mongodbcommunity ${names_1.MONGO_SERVICE}`);
941
+ }