slatebox 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +21 -0
- package/README.md +231 -2
- package/bin/slatebox.mjs +9 -0
- package/package.json +44 -4
- package/src/agent-prompt.mjs +79 -0
- package/src/ai/settings-adapter.mjs +198 -0
- package/src/answers.mjs +513 -0
- package/src/cli.mjs +711 -0
- package/src/cloud.mjs +261 -0
- package/src/errors.mjs +23 -0
- package/src/image.mjs +141 -0
- package/src/interview.mjs +199 -0
- package/src/move.mjs +447 -0
- package/src/output.mjs +51 -0
- package/src/plan.mjs +51 -0
- package/src/prompt.mjs +87 -0
- package/src/record.mjs +46 -0
- package/src/render/compose.mjs +47 -0
- package/src/render/helm.mjs +78 -0
- package/src/render/k8s.mjs +204 -0
- package/src/render/settings.mjs +67 -0
- package/src/runner.mjs +50 -0
- package/src/secret-values.mjs +45 -0
- package/src/secrets.mjs +124 -0
- package/src/setup-link.mjs +88 -0
- package/src/targets/address.mjs +281 -0
- package/src/targets/docker.mjs +797 -0
- package/src/targets/export.mjs +73 -0
- package/src/targets/hosts.mjs +202 -0
- package/src/targets/k8s.mjs +405 -0
- package/src/yaml.mjs +293 -0
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
// Kubernetes: render the objects in code, show the plan with the context it
|
|
2
|
+
// will touch, then `kubectl apply --server-side` on standard input. kubectl
|
|
3
|
+
// only; Helm is optional (export --format helm).
|
|
4
|
+
import { createHash } from 'node:crypto'
|
|
5
|
+
import { mkdirSync, rmSync } from 'node:fs'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { EXIT, InstallError } from '../errors.mjs'
|
|
8
|
+
import { collect, resolveAnswers } from '../answers.mjs'
|
|
9
|
+
import { checkArch, DEFAULT_IMAGE, FALLBACK_CAPABILITIES, hasRegistry, isTag, probeImage } from '../image.mjs'
|
|
10
|
+
import { emptyPlan } from '../plan.mjs'
|
|
11
|
+
import { installDir, recordText, writeRecord } from '../record.mjs'
|
|
12
|
+
import { MANAGER, names, renderK8s, renderSecret } from '../render/k8s.mjs'
|
|
13
|
+
import { settingsFor } from '../render/settings.mjs'
|
|
14
|
+
import { secretValues } from '../secret-values.mjs'
|
|
15
|
+
import { firstAdmin, makeSetupLink, setupState, stillWaiting } from '../setup-link.mjs'
|
|
16
|
+
import { checkTeamAddress, ensureTeamAddress, TUNNEL_TOKEN } from './address.mjs'
|
|
17
|
+
import { stringifyAll } from '../yaml.mjs'
|
|
18
|
+
|
|
19
|
+
const SLATEBOX = '/opt/slatebox/bin/slatebox'
|
|
20
|
+
const lastLine = text => text.trim().split('\n').filter(Boolean).pop() || ''
|
|
21
|
+
const PROD = /(^|[^a-z])(prod|production)([^a-z]|$)/i
|
|
22
|
+
|
|
23
|
+
export function kube(ctx, context) {
|
|
24
|
+
return (args, options) => ctx.run('kubectl', ['--context', context, ...args], options)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Which context, and may the installer touch it? */
|
|
28
|
+
export async function chooseContext(ctx, answers, { explicit }) {
|
|
29
|
+
let context = answers.k8s.context
|
|
30
|
+
if (!context) {
|
|
31
|
+
const current = await ctx.run('kubectl', ['config', 'current-context'])
|
|
32
|
+
if (current.code === 127) throw new InstallError(EXIT.PRECONDITION, 'kubectl is not installed. Install it, or use --target export --format manifests to write the files only.')
|
|
33
|
+
if (current.code !== 0 || !current.stdout.trim()) throw new InstallError(EXIT.PRECONDITION, 'There is no current kube context. Give one with --k8s-context <name>.')
|
|
34
|
+
context = current.stdout.trim()
|
|
35
|
+
}
|
|
36
|
+
if (PROD.test(context) && !explicit) {
|
|
37
|
+
throw new InstallError(EXIT.PRECONDITION, `The current kube context is "${context}". The installer does not apply to a production-looking context unless it is named: run again with --k8s-context ${context}.`, { field: 'k8s.context' })
|
|
38
|
+
}
|
|
39
|
+
return context
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const RESOURCES = answers => [
|
|
43
|
+
['configmaps', ''], ['secrets', ''], ['services', ''], ['persistentvolumeclaims', ''], ['statefulsets', 'apps'],
|
|
44
|
+
...(answers.k8s.route === 'ingress' ? [['ingresses', 'networking.k8s.io']] : []),
|
|
45
|
+
...(answers.k8s.route === 'gateway' ? [['httproutes', 'gateway.networking.k8s.io']] : []),
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
async function preflight(ctx, k, answers, context) {
|
|
49
|
+
const version = await k(['version', '-o', 'json'], { timeout: 30_000 })
|
|
50
|
+
if (version.code !== 0) throw new InstallError(EXIT.PRECONDITION, `The cluster of context "${context}" does not answer: ${lastLine(version.stderr)}`)
|
|
51
|
+
const ns = answers.k8s.namespace
|
|
52
|
+
const nsExists = (await k(['get', 'namespace', ns, '-o', 'name'])).code === 0
|
|
53
|
+
const checks = [
|
|
54
|
+
...(nsExists ? [] : [['create', 'namespaces', '']]),
|
|
55
|
+
...RESOURCES(answers).flatMap(([resource, group]) => [['create', resource, group], ['patch', resource, group]]),
|
|
56
|
+
// Reading the Secret is how the key encryption key is kept: without it the installer would make a new one.
|
|
57
|
+
['get', 'secrets', ''], ['get', 'pods', ''], ['delete', 'pods', ''], ['create', 'pods/exec', ''],
|
|
58
|
+
]
|
|
59
|
+
const denied = []
|
|
60
|
+
for (const [verb, resource, group] of checks) {
|
|
61
|
+
const result = await k(['auth', 'can-i', verb, group ? `${resource}.${group}` : resource, ...(resource === 'namespaces' ? [] : ['-n', ns])])
|
|
62
|
+
if (result.stdout.trim() !== 'yes') denied.push(`${verb} ${group ? `${resource}.${group}` : resource}${resource === 'namespaces' ? '' : ` in ${ns}`}`)
|
|
63
|
+
}
|
|
64
|
+
if (denied.length) {
|
|
65
|
+
throw new InstallError(EXIT.PRECONDITION, `Your access to "${context}" does not allow: ${denied.join('; ')}. Ask a cluster admin for these, or use --target export to hand them the manifests.`, { denied })
|
|
66
|
+
}
|
|
67
|
+
const notes = []
|
|
68
|
+
if (answers.k8s.storageClass) {
|
|
69
|
+
if ((await k(['get', 'storageclass', answers.k8s.storageClass, '-o', 'name'])).code !== 0) throw new InstallError(EXIT.PRECONDITION, `There is no StorageClass "${answers.k8s.storageClass}" in "${context}".`)
|
|
70
|
+
} else {
|
|
71
|
+
const classes = await k(['get', 'storageclass', '-o', 'json'])
|
|
72
|
+
const items = classes.code === 0 ? JSON.parse(classes.stdout).items : []
|
|
73
|
+
const preferred = items.find(item => item.metadata.annotations?.['storageclass.kubernetes.io/is-default-class'] === 'true')
|
|
74
|
+
if (!preferred) throw new InstallError(EXIT.PRECONDITION, `"${context}" has no default StorageClass. Give one with --storage-class <name> (${items.map(item => item.metadata.name).join(', ') || 'none found'}).`)
|
|
75
|
+
notes.push(`Volumes from the default StorageClass "${preferred.metadata.name}".`)
|
|
76
|
+
}
|
|
77
|
+
if (answers.k8s.tlsIssuer) {
|
|
78
|
+
const { kind, name } = answers.k8s.tlsIssuer
|
|
79
|
+
const args = kind === 'Issuer' ? ['get', 'issuers.cert-manager.io', name, '-n', ns] : ['get', 'clusterissuers.cert-manager.io', name]
|
|
80
|
+
if ((await k([...args, '-o', 'name'])).code !== 0) throw new InstallError(EXIT.PRECONDITION, `cert-manager ${kind} "${name}" was not found in "${context}". Install cert-manager and the issuer first, or leave --tls-issuer out.`)
|
|
81
|
+
}
|
|
82
|
+
if (answers.k8s.route === 'gateway') {
|
|
83
|
+
const [gns, gname] = answers.k8s.gatewayRef.split('/')
|
|
84
|
+
if ((await k(['get', 'gateways.gateway.networking.k8s.io', gname, '-n', gns, '-o', 'name'])).code !== 0) throw new InstallError(EXIT.PRECONDITION, `Gateway ${answers.k8s.gatewayRef} was not found in "${context}".`)
|
|
85
|
+
}
|
|
86
|
+
if (answers.k8s.route === 'ingress' && answers.k8s.ingressClass) {
|
|
87
|
+
if ((await k(['get', 'ingressclass', answers.k8s.ingressClass, '-o', 'name'])).code !== 0) throw new InstallError(EXIT.PRECONDITION, `IngressClass "${answers.k8s.ingressClass}" was not found in "${context}".`)
|
|
88
|
+
}
|
|
89
|
+
return { nsExists, notes }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* A registry reference the cluster can pull, pinned when this computer can tell
|
|
94
|
+
* the digest. For an upgrade (refresh) a tag is fetched here first, because a
|
|
95
|
+
* tag string that did not change says nothing about the bytes behind it; if
|
|
96
|
+
* no digest can be found that way the upgrade is refused rather than called
|
|
97
|
+
* "nothing to change".
|
|
98
|
+
*/
|
|
99
|
+
export async function clusterImage(ctx, ref, { refresh = false } = {}) {
|
|
100
|
+
const wanted = ref || DEFAULT_IMAGE
|
|
101
|
+
if (wanted.includes('@sha256:')) return { ref: wanted, pinned: wanted, local: false }
|
|
102
|
+
let pullError = null
|
|
103
|
+
if (refresh && isTag(wanted)) {
|
|
104
|
+
const pulled = await ctx.run('docker', ['pull', wanted], { timeout: 60 * 60_000 })
|
|
105
|
+
if (pulled.code !== 0) pullError = pulled.stderr.trim().split('\n').pop() || 'docker pull failed'
|
|
106
|
+
}
|
|
107
|
+
const inspected = await ctx.run('docker', ['image', 'inspect', '--format', '{{json .}}', wanted])
|
|
108
|
+
const info = inspected.code === 0 ? JSON.parse(inspected.stdout) : null
|
|
109
|
+
const repository = wanted.replace(/:[^/:]+$/, '')
|
|
110
|
+
const digest = info && (info.RepoDigests || []).find(item => item.startsWith(`${repository}@`))
|
|
111
|
+
if (refresh && isTag(wanted) && (pullError || !digest)) {
|
|
112
|
+
throw new InstallError(EXIT.PRECONDITION, `Cannot tell which image ${wanted} is now${pullError ? ` (pulling it here failed: ${pullError})` : ' (no registry digest for it here)'}, so the upgrade would not know what it changes. Nothing was changed. Give the image by digest: slatebox upgrade --to ${repository}@sha256:<digest>.`)
|
|
113
|
+
}
|
|
114
|
+
if (info) return { ref: wanted, pinned: hasRegistry(wanted) && digest ? digest : wanted, local: true, id: info.Id, architecture: info.Architecture || null }
|
|
115
|
+
return { ref: wanted, pinned: wanted, local: false }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function checkNodeArch(k, image, context) {
|
|
119
|
+
if (!image.architecture) return
|
|
120
|
+
const nodes = await k(['get', 'nodes', '-o', 'jsonpath={.items[*].metadata.labels.kubernetes\\.io/arch}'])
|
|
121
|
+
if (nodes.code !== 0 || !nodes.stdout.trim()) return // nodes may not be listable with namespace rights
|
|
122
|
+
checkArch(image, nodes.stdout.trim().split(/\s+/), `the nodes of "${context}"`)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function capabilities(ctx, image, warnings) {
|
|
126
|
+
if (image.local) {
|
|
127
|
+
try { return await probeImage((args, o) => ctx.run('docker', args, o), image.id || image.ref) } catch { /* fall through */ }
|
|
128
|
+
}
|
|
129
|
+
warnings.push(`The image was not on this computer, so its settings could not be read from it; the installer assumed the settings of the current image (pull ${image.ref} first to check).`)
|
|
130
|
+
return FALLBACK_CAPABILITIES
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The Secret's values; {} only when it does not exist. Any other failure stops the run: a guess would make a new key. */
|
|
134
|
+
async function existingSecret(k, answers) {
|
|
135
|
+
const result = await k(['get', 'secret', names(answers).secret, '-n', answers.k8s.namespace, '-o', 'json'])
|
|
136
|
+
if (result.code !== 0) {
|
|
137
|
+
if (/NotFound|not found/.test(result.stderr)) return {}
|
|
138
|
+
throw new InstallError(EXIT.PRECONDITION, `The Secret ${answers.k8s.namespace}/${names(answers).secret} could not be read: ${lastLine(result.stderr) || `kubectl exit ${result.code}`}. Nothing was changed: without it the installer cannot keep SLATEBOX_KEY_ENCRYPTION_KEY.`)
|
|
139
|
+
}
|
|
140
|
+
const data = JSON.parse(result.stdout).data || {}
|
|
141
|
+
return Object.fromEntries(Object.entries(data).map(([key, value]) => [key, Buffer.from(value, 'base64').toString('utf8')]))
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function currentImage(k, answers) {
|
|
145
|
+
const result = await k(['get', 'statefulset', names(answers).set, '-n', answers.k8s.namespace, '-o', 'jsonpath={.spec.template.spec.containers[0].image}'])
|
|
146
|
+
return result.code === 0 ? result.stdout.trim() || null : null
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function rollout(ctx, k, answers) {
|
|
150
|
+
const n = names(answers)
|
|
151
|
+
const status = await k(['rollout', 'status', `statefulset/${n.set}`, '-n', answers.k8s.namespace, `--timeout=${ctx.healthTimeout}s`], { timeout: (ctx.healthTimeout + 60) * 1000 })
|
|
152
|
+
if (status.code !== 0) return { ok: false, why: lastLine(status.stderr) || 'rollout did not finish' }
|
|
153
|
+
const deep = await k(['exec', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'health', '--deep', '--wait', '60'], { timeout: 120_000 })
|
|
154
|
+
if (deep.code !== 0) return { ok: false, why: lastLine(deep.stderr) || 'slatebox health failed' }
|
|
155
|
+
if (answers.address.team) {
|
|
156
|
+
for (let attempt = 0; attempt < (ctx.teamHealthAttempts ?? 30); attempt++) {
|
|
157
|
+
try {
|
|
158
|
+
const response = await ctx.fetch(`${answers.address.url}/readyz`, { signal: AbortSignal.timeout(8000) })
|
|
159
|
+
if (response.ok) return { ok: true }
|
|
160
|
+
} catch { /* retry */ }
|
|
161
|
+
await new Promise(resolve => setTimeout(resolve, ctx.teamHealthDelay ?? 2000))
|
|
162
|
+
}
|
|
163
|
+
return { ok: true, warning: `Slatebox is healthy in the cluster, but ${answers.address.url} does not answer from here yet: the secure tunnel keeps trying by itself (kubectl logs ${n.pod} -c slatebox | grep tunnel).` }
|
|
164
|
+
}
|
|
165
|
+
if (answers.k8s.route !== 'none') {
|
|
166
|
+
try {
|
|
167
|
+
const response = await ctx.fetch(`${answers.address.url}/readyz`, { signal: AbortSignal.timeout(8000) })
|
|
168
|
+
if (!response.ok) return { ok: true, warning: `${answers.address.url}/readyz answered HTTP ${response.status} from here; check the route and DNS.` }
|
|
169
|
+
} catch (error) {
|
|
170
|
+
return { ok: true, warning: `${answers.address.url} does not answer from here yet (${error.cause?.code || error.message}); check DNS and the ${answers.k8s.route}.` }
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return { ok: true }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const apply = (k, objects) => k(['apply', '--server-side', `--field-manager=${MANAGER}`, '-f', '-'], { input: stringifyAll(objects), timeout: 120_000 })
|
|
177
|
+
|
|
178
|
+
export async function applyK8s(ctx, answers, { record, planOnly = false, imageRef, explicitContext, refresh = false }) {
|
|
179
|
+
const { out } = ctx
|
|
180
|
+
if (ctx.flags['image-archive']) throw new InstallError(EXIT.USAGE, 'An image archive cannot be loaded into a cluster. Push the image to a registry the cluster can pull from and give --image <ref>.')
|
|
181
|
+
const context = await chooseContext(ctx, answers, { explicit: explicitContext })
|
|
182
|
+
answers.k8s.context = context
|
|
183
|
+
const k = kube(ctx, context)
|
|
184
|
+
out.step('preflight', 'start', `Checking kube context "${context}"`)
|
|
185
|
+
const facts = await preflight(ctx, k, answers, context)
|
|
186
|
+
out.step('preflight', 'ok', `Context "${context}", namespace ${answers.k8s.namespace}${facts.nsExists ? '' : ' (new)'}`)
|
|
187
|
+
const team = answers.address.team ? await checkTeamAddress(ctx, answers) : null
|
|
188
|
+
|
|
189
|
+
const warnings = []
|
|
190
|
+
const image = await clusterImage(ctx, imageRef || answers.image, { refresh })
|
|
191
|
+
await checkNodeArch(k, image, context)
|
|
192
|
+
if (!image.pinned.includes('@sha256:')) warnings.push(`${image.pinned} is not pinned to a digest, so the cluster may pull different bytes later. Give --image <repo>@sha256:<digest> to pin it.`)
|
|
193
|
+
const caps = await capabilities(ctx, image, warnings)
|
|
194
|
+
const settings = settingsFor(answers, caps)
|
|
195
|
+
const stored = await existingSecret(k, answers)
|
|
196
|
+
const previous = await currentImage(k, answers)
|
|
197
|
+
if (settings.secrets.SLATEBOX_KEY_ENCRYPTION_KEY === 'generate' && !stored.SLATEBOX_KEY_ENCRYPTION_KEY && !ctx.flags['new-encryption-key']) {
|
|
198
|
+
const pvc = (await k(['get', 'pvc', `data-${names(answers).set}-0`, '-n', answers.k8s.namespace, '-o', 'name'])).code === 0
|
|
199
|
+
if (previous || pvc) {
|
|
200
|
+
throw new InstallError(EXIT.PRECONDITION, `Slatebox "${answers.name}" already has ${previous ? 'a StatefulSet' : 'a data volume'} in ${answers.k8s.namespace}, but its Secret ${names(answers).secret} holds no SLATEBOX_KEY_ENCRYPTION_KEY. A new key would make every AI and call key people saved unreadable. Nothing was changed. Put the Secret back from your backup, or add --new-encryption-key to start over with a new key.`, { needs: 'encryption-key' })
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
// The Secret is part of the server-side diff, so a team address still to be claimed is claimed
|
|
204
|
+
// (after its own yes) before the plan; a plan-only run shows a stand-in and claims nothing.
|
|
205
|
+
let secretCtx = ctx
|
|
206
|
+
if (team && !stored[TUNNEL_TOKEN]) {
|
|
207
|
+
if (planOnly) secretCtx = { ...ctx, tunnelToken: 'pending-team-address-claim' }
|
|
208
|
+
else {
|
|
209
|
+
if (team.claim) {
|
|
210
|
+
const claimPlan = emptyPlan({ action: 'claim', target: 'k8s', name: answers.name, where: 'Slatebox Cloud', address: answers.address.url,
|
|
211
|
+
notes: [`You sign in to Slatebox in your browser to claim ${team.host}. Its tunnel token goes into the Secret ${names(answers).secret}; the install credential stays on this computer (mode 0600).`] })
|
|
212
|
+
ctx.emitPlan(claimPlan)
|
|
213
|
+
await ctx.confirm(claimPlan)
|
|
214
|
+
}
|
|
215
|
+
await ensureTeamAddress(ctx, answers, team, stored)
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
const { values, generated } = await secretValues(secretCtx, settings.secrets, stored)
|
|
219
|
+
const secretsHash = createHash('sha256').update(JSON.stringify(values)).digest('hex')
|
|
220
|
+
const imageChanged = Boolean(previous && previous !== image.pinned)
|
|
221
|
+
|
|
222
|
+
const n = names(answers)
|
|
223
|
+
const nextRecord = {
|
|
224
|
+
...answers, image: image.ref, installedVersion: ctx.version, imageRef: image.ref, imageDigest: image.pinned,
|
|
225
|
+
previousImageDigest: imageChanged ? previous : record?.previousImageDigest ?? null,
|
|
226
|
+
secretRefs: settings.secrets, secretsLocation: `Secret ${answers.k8s.namespace}/${n.secret} in context ${context}`,
|
|
227
|
+
installedAt: record?.installedAt || new Date().toISOString(), state: 'installed',
|
|
228
|
+
}
|
|
229
|
+
const objects = renderK8s(answers, { image: image.pinned, env: settings.env, secretsHash, record: recordText(nextRecord) })
|
|
230
|
+
const secret = renderSecret(answers, values)
|
|
231
|
+
|
|
232
|
+
// Server-side diff: the same answers applied twice change nothing.
|
|
233
|
+
const all = [objects[0], secret, ...objects.slice(1)]
|
|
234
|
+
const diff = previous ? await k(['diff', '--server-side', `--field-manager=${MANAGER}`, '-f', '-'], { input: stringifyAll(all), timeout: 120_000 }) : { code: 1 }
|
|
235
|
+
const nothing = diff.code === 0 && (await k(['get', 'pod', n.pod, '-n', answers.k8s.namespace, '-o', 'jsonpath={.status.containerStatuses[?(@.name=="slatebox")].ready}'])).stdout.trim() === 'true'
|
|
236
|
+
const plan = emptyPlan({
|
|
237
|
+
action: nothing ? 'nothing' : previous ? (imageChanged ? 'upgrade' : 'change') : 'install', target: 'k8s', name: answers.name,
|
|
238
|
+
where: `kube context "${context}", namespace ${answers.k8s.namespace}`, address: answers.address.url,
|
|
239
|
+
image: { ref: image.ref, pinned: image.pinned, previous: previous || undefined },
|
|
240
|
+
secretsLocation: nextRecord.secretsLocation, warnings: [...warnings, ...settings.warnings], notes: [...facts.notes, ...settings.notes],
|
|
241
|
+
objects: [...objects.slice(0, 1), secret, ...objects.slice(1)].map(object => `${object.kind}/${object.metadata.name}`),
|
|
242
|
+
})
|
|
243
|
+
if (imageChanged) plan.commands.push(`back up first: kubectl exec ${n.pod} -c slatebox -- slatebox backup > ${join(installDir(ctx.home, answers.name), 'backups', 'pre-upgrade-….gz')}`)
|
|
244
|
+
plan.commands.push(`kubectl --context ${context} apply --server-side --field-manager=${MANAGER} -f - (the objects above, on standard input)`,
|
|
245
|
+
`kubectl rollout status statefulset/${n.set} -n ${answers.k8s.namespace}`, `kubectl exec ${n.pod} -c slatebox -- slatebox health --deep`)
|
|
246
|
+
if (answers.k8s.route === 'none') plan.notes.push(`No route: reach it with kubectl --context ${context} -n ${answers.k8s.namespace} port-forward svc/${n.service} 7070:7070, then open http://localhost:7070.`)
|
|
247
|
+
if (answers.k8s.route === 'gateway') plan.notes.push('TLS for the HTTPRoute is the Gateway listener\'s certificate; the installer does not change the Gateway.')
|
|
248
|
+
ctx.emitPlan(plan)
|
|
249
|
+
if (planOnly) return { planned: true, plan }
|
|
250
|
+
if (nothing) {
|
|
251
|
+
nextRecord.lastHealthy = new Date().toISOString()
|
|
252
|
+
ctx.recordFile = writeRecord(ctx.home, nextRecord)
|
|
253
|
+
await stillWaiting(ctx, args => k(['exec', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, ...args]))
|
|
254
|
+
return {
|
|
255
|
+
address: answers.address.url, name: answers.name, target: 'k8s', version: null, imageDigest: image.pinned,
|
|
256
|
+
installRecord: ctx.recordFile, secretsFile: nextRecord.secretsLocation, nothingToChange: true, keyGenerated: false, fresh: false,
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
await ctx.confirm(plan)
|
|
260
|
+
|
|
261
|
+
let preUpgrade = null
|
|
262
|
+
if (imageChanged) {
|
|
263
|
+
preUpgrade = join(installDir(ctx.home, answers.name), 'backups', `pre-upgrade-${Date.now()}.gz`)
|
|
264
|
+
mkdirSync(join(preUpgrade, '..'), { recursive: true, mode: 0o700 })
|
|
265
|
+
out.step('backup', 'start', `Backing up before the upgrade to ${preUpgrade}`)
|
|
266
|
+
const backup = await k(['exec', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'backup'], { outputFile: preUpgrade, timeout: 60 * 60_000 })
|
|
267
|
+
if (backup.code !== 0) {
|
|
268
|
+
rmSync(preUpgrade, { force: true })
|
|
269
|
+
throw new InstallError(EXIT.PRECONDITION, `The backup before the upgrade failed, so nothing was changed: ${lastLine(backup.stderr)}`)
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
const previousObjects = previous ? previousState(answers, record, { image: previous, caps, stored, nextRecord }) : null
|
|
273
|
+
|
|
274
|
+
out.step('apply', 'start', `Applying ${objects.length + 1} objects to "${context}"`)
|
|
275
|
+
const applied = await apply(k, all)
|
|
276
|
+
if (applied.code !== 0) throw new InstallError(EXIT.PRECONDITION, `kubectl apply failed: ${lastLine(applied.stderr)}`)
|
|
277
|
+
out.step('apply', 'ok', 'Applied')
|
|
278
|
+
out.step('start', 'start', `Waiting until Slatebox is ready (up to ${ctx.healthTimeout}s)`)
|
|
279
|
+
const result = await rollout(ctx, k, answers)
|
|
280
|
+
if (!result.ok) {
|
|
281
|
+
out.step('start', 'fail', `Slatebox did not become ready: ${result.why}`)
|
|
282
|
+
const manual = [`kubectl --context ${context} -n ${answers.k8s.namespace} logs ${n.pod} -c slatebox`, `kubectl --context ${context} -n ${answers.k8s.namespace} describe pod ${n.pod}`]
|
|
283
|
+
if (!previousObjects) {
|
|
284
|
+
throw new InstallError(EXIT.ROLLED_BACK, `Slatebox did not become ready (${result.why}). The objects are kept for you to inspect.`, { commands: manual })
|
|
285
|
+
}
|
|
286
|
+
out.step('rollback', 'start', 'Putting the previous version back')
|
|
287
|
+
await apply(k, previousObjects)
|
|
288
|
+
// A StatefulSet does not replace a pod that never became ready; do it here.
|
|
289
|
+
await k(['delete', 'pod', n.pod, '-n', answers.k8s.namespace, '--wait=false'])
|
|
290
|
+
let back = await rollout(ctx, k, answers)
|
|
291
|
+
if (back.ok && preUpgrade) {
|
|
292
|
+
const restored = await k(['exec', '-i', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'restore'], { inputFile: preUpgrade, timeout: 60 * 60_000 })
|
|
293
|
+
if (restored.code !== 0) back = { ok: false, why: lastLine(restored.stderr) }
|
|
294
|
+
}
|
|
295
|
+
if (!back.ok) {
|
|
296
|
+
throw new InstallError(EXIT.ROLLBACK_FAILED, `The change failed (${result.why}) and putting the previous version back failed too (${back.why}). The volumes are untouched.`, {
|
|
297
|
+
commands: [...manual, ...(preUpgrade ? [`kubectl --context ${context} -n ${answers.k8s.namespace} exec -i ${n.pod} -c slatebox -- slatebox restore < ${preUpgrade}`] : [])],
|
|
298
|
+
})
|
|
299
|
+
}
|
|
300
|
+
throw new InstallError(EXIT.ROLLED_BACK, `The change failed (${result.why}), so the previous version was put back and is ready.`, { commands: manual })
|
|
301
|
+
}
|
|
302
|
+
if (result.warning) out.step('route', 'warn', result.warning)
|
|
303
|
+
out.step('start', 'ok', `Slatebox is ready${answers.k8s.route === 'none' ? ' (port-forward to reach it)' : ` at ${answers.address.url}`}`)
|
|
304
|
+
// The first admin comes from the image's one-time setup link; an image without one keeps the old advice.
|
|
305
|
+
const linked = await firstAdmin(ctx, args => k(['exec', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, ...args]))
|
|
306
|
+
if (!linked && !previous) {
|
|
307
|
+
out.say(`\n${answers.adminEmail ? `Open ${answers.address.url} and create the first account with ${answers.adminEmail}.` : `Open ${answers.address.url} and create the first account.`}`)
|
|
308
|
+
}
|
|
309
|
+
nextRecord.lastHealthy = new Date().toISOString()
|
|
310
|
+
ctx.recordFile = writeRecord(ctx.home, nextRecord)
|
|
311
|
+
ctx.record = nextRecord
|
|
312
|
+
return {
|
|
313
|
+
address: answers.address.url, name: answers.name, target: 'k8s', version: null, imageDigest: image.pinned,
|
|
314
|
+
installRecord: `${ctx.recordFile} (and ConfigMap ${answers.k8s.namespace}/${n.record})`, secretsFile: nextRecord.secretsLocation,
|
|
315
|
+
keyGenerated: generated.includes('SLATEBOX_KEY_ENCRYPTION_KEY'), fresh: !previous,
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* What was running before this change: the previous answers (from the install
|
|
321
|
+
* record) with the previous Secret's values and image, so a rollback puts the
|
|
322
|
+
* settings and keys back too, not only the image.
|
|
323
|
+
*/
|
|
324
|
+
const withoutHealthy = ({ lastHealthy, ...rest }) => rest
|
|
325
|
+
|
|
326
|
+
function previousState(answers, record, { image, caps, stored, nextRecord }) {
|
|
327
|
+
let before = answers
|
|
328
|
+
if (record) {
|
|
329
|
+
const resolved = resolveAnswers(collect({ record }), {})
|
|
330
|
+
if (!resolved.errors.length) before = { ...resolved.answers, k8s: { ...resolved.answers.k8s, context: answers.k8s.context } }
|
|
331
|
+
}
|
|
332
|
+
const settings = settingsFor(before, caps)
|
|
333
|
+
const values = Object.fromEntries(Object.keys(settings.secrets).filter(name => name in stored).map(name => [name, stored[name]]))
|
|
334
|
+
const secretsHash = createHash('sha256').update(JSON.stringify(values)).digest('hex')
|
|
335
|
+
const objects = renderK8s(before, { image, env: settings.env, secretsHash, record: recordText(record ? withoutHealthy(record) : { ...nextRecord, imageDigest: image }) })
|
|
336
|
+
return [objects[0], renderSecret(before, values), ...objects.slice(1)]
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export async function statusK8s(ctx, record) {
|
|
340
|
+
const k = kube(ctx, record.k8s.context)
|
|
341
|
+
const n = names(record)
|
|
342
|
+
const pod = await k(['get', 'pod', n.pod, '-n', record.k8s.namespace, '-o', 'json'])
|
|
343
|
+
const info = pod.code === 0 ? JSON.parse(pod.stdout) : null
|
|
344
|
+
const ready = info?.status?.containerStatuses?.find(item => item.name === 'slatebox')?.ready
|
|
345
|
+
const version = ready ? await k(['exec', '-n', record.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'version']) : null
|
|
346
|
+
const backups = ready && record.backups.to !== 'off' ? await k(['exec', '-n', record.k8s.namespace, n.pod, '-c', 'backups', '--', 'sh', '-c', 'ls -1t /backups | head -1']) : null
|
|
347
|
+
const setup = ready ? await setupState(args => k(['exec', '-n', record.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, ...args])) : null
|
|
348
|
+
return {
|
|
349
|
+
name: record.name, target: 'k8s', where: `context ${record.k8s.context}, namespace ${record.k8s.namespace}`, address: record.address.url,
|
|
350
|
+
running: Boolean(info), health: ready ? 'healthy' : info ? info.status.phase : 'missing',
|
|
351
|
+
version: version?.code === 0 ? JSON.parse(version.stdout) : null, imageDigest: record.imageDigest,
|
|
352
|
+
ai: record.ai.mode === 'none' ? 'off' : record.ai.providers.map(provider => provider.id).join(', '),
|
|
353
|
+
sso: record.sso.enabled ? 'on' : 'off', lastBackup: backups?.stdout.trim() || null,
|
|
354
|
+
setup: setup ? (setup.setUp ? 'done' : 'waiting for the first admin') : null,
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
export async function backupK8s(ctx, record, { to }) {
|
|
359
|
+
const k = kube(ctx, record.k8s.context)
|
|
360
|
+
const n = names(record)
|
|
361
|
+
const dir = to ? (to.startsWith('/') ? to : join(process.cwd(), to)) : join(installDir(ctx.home, record.name), 'backups')
|
|
362
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
363
|
+
const file = join(dir, `slatebox-${new Date().toISOString().replace(/[-:]/g, '').replace(/\..*/, '').replace('T', '-')}.gz`)
|
|
364
|
+
const result = await k(['exec', '-n', record.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'backup'], { outputFile: file, timeout: 60 * 60_000 })
|
|
365
|
+
if (result.code !== 0) { rmSync(file, { force: true }); throw new InstallError(EXIT.PRECONDITION, `The backup failed: ${lastLine(result.stderr)}`) }
|
|
366
|
+
return { file, where: 'this computer' }
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export async function restoreK8s(ctx, record, archive) {
|
|
370
|
+
const k = kube(ctx, record.k8s.context)
|
|
371
|
+
const result = await k(['exec', '-i', '-n', record.k8s.namespace, names(record).pod, '-c', 'slatebox', '--', SLATEBOX, 'restore'], { inputFile: archive, timeout: 60 * 60_000 })
|
|
372
|
+
if (result.code !== 0) throw new InstallError(EXIT.PRECONDITION, `The restore failed: ${lastLine(result.stderr)}`)
|
|
373
|
+
return { restored: archive }
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export async function uninstallK8s(ctx, record, { deleteData }) {
|
|
377
|
+
const k = kube(ctx, record.k8s.context)
|
|
378
|
+
const ns = record.k8s.namespace
|
|
379
|
+
const n = names(record)
|
|
380
|
+
const selector = `slatebox.com/install=${record.name}`
|
|
381
|
+
const kinds = ['statefulset', 'service', 'ingress.networking.k8s.io', 'configmap', ...(record.k8s.route === 'gateway' ? ['httproutes.gateway.networking.k8s.io'] : [])]
|
|
382
|
+
for (const kind of kinds) await k(['delete', kind, '-n', ns, '-l', selector, '--ignore-not-found'])
|
|
383
|
+
if (deleteData) {
|
|
384
|
+
await k(['delete', 'pvc,secret', '-n', ns, '-l', selector, '--ignore-not-found'])
|
|
385
|
+
await k(['delete', 'pvc', `data-${n.set}-0`, '-n', ns, '--ignore-not-found'])
|
|
386
|
+
return { dataDeleted: true }
|
|
387
|
+
}
|
|
388
|
+
return { dataDeleted: false, volume: `PersistentVolumeClaims data-${n.set}-0 and ${n.backups} in ${ns}`, secretsFile: `Secret ${ns}/${n.secret}` }
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export function execNodeK8s(ctx, record, script, args = []) {
|
|
392
|
+
const k = kube(ctx, record.k8s.context)
|
|
393
|
+
return k(['exec', '-i', '-n', record.k8s.namespace, names(record).pod, '-c', 'slatebox', '--', 'node', '--input-type=module', '-', ...args], { input: script, timeout: 120_000 })
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** A fresh one-time setup link from the install's pod (setup-link.mjs makeSetupLink). */
|
|
397
|
+
export function setupLinkK8s(ctx, record) {
|
|
398
|
+
const k = kube(ctx, record.k8s.context)
|
|
399
|
+
return makeSetupLink(ctx, args => k(['exec', '-n', record.k8s.namespace, names(record).pod, '-c', 'slatebox', '--', SLATEBOX, ...args]))
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
export async function readSecretK8s(ctx, record, name) {
|
|
403
|
+
const k = kube(ctx, record.k8s.context)
|
|
404
|
+
return (await existingSecret(k, record))[name]
|
|
405
|
+
}
|