slatebox 0.0.0-stage → 0.1.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 +151 -2
- package/bin/slatebox.mjs +9 -0
- package/package.json +41 -4
- package/src/agent-prompt.mjs +64 -0
- package/src/ai/settings-adapter.mjs +198 -0
- package/src/answers.mjs +489 -0
- package/src/cli.mjs +477 -0
- package/src/errors.mjs +23 -0
- package/src/image.mjs +138 -0
- package/src/interview.mjs +170 -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 +59 -0
- package/src/runner.mjs +50 -0
- package/src/secret-values.mjs +40 -0
- package/src/secrets.mjs +119 -0
- package/src/targets/docker.mjs +685 -0
- package/src/targets/export.mjs +73 -0
- package/src/targets/hosts.mjs +202 -0
- package/src/targets/k8s.mjs +366 -0
- package/src/yaml.mjs +293 -0
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Export only: write the compose file, the Kubernetes manifests or a Helm
|
|
2
|
+
// chart for GitOps, with placeholders where secrets go. Nothing is applied and
|
|
3
|
+
// no host or cluster is contacted (the local Docker is asked for the image's
|
|
4
|
+
// digest and settings when it has the image).
|
|
5
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
|
|
6
|
+
import { dirname, join, resolve } from 'node:path'
|
|
7
|
+
import { EXIT, InstallError } from '../errors.mjs'
|
|
8
|
+
import { DEFAULT_IMAGE, FALLBACK_CAPABILITIES, probeImage } from '../image.mjs'
|
|
9
|
+
import { emptyPlan } from '../plan.mjs'
|
|
10
|
+
import { renderCompose, SECRETS_FILE, SETTINGS_FILE } from '../render/compose.mjs'
|
|
11
|
+
import { renderHelmChart } from '../render/helm.mjs'
|
|
12
|
+
import { names, renderK8s, renderSecret } from '../render/k8s.mjs'
|
|
13
|
+
import { settingsFor } from '../render/settings.mjs'
|
|
14
|
+
import { envFileText } from '../secrets.mjs'
|
|
15
|
+
import { stringify, stringifyAll } from '../yaml.mjs'
|
|
16
|
+
import { clusterImage } from './k8s.mjs'
|
|
17
|
+
|
|
18
|
+
function placeholder(name, ref) {
|
|
19
|
+
if (ref === 'generate') return '<32 random bytes in base64: openssl rand -base64 32; keep it with your backups>'
|
|
20
|
+
return `<the value of ${ref}>`
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function exportFiles(ctx, answers, { planOnly = false } = {}) {
|
|
24
|
+
const dir = resolve(answers.export.dir)
|
|
25
|
+
const warnings = []
|
|
26
|
+
const image = await clusterImage(ctx, answers.image || DEFAULT_IMAGE)
|
|
27
|
+
let caps = FALLBACK_CAPABILITIES
|
|
28
|
+
if (image.local) {
|
|
29
|
+
try { caps = await probeImage((args, o) => ctx.run('docker', args, o), image.id) } catch { warnings.push('The image did not list its settings; the current image\'s settings were assumed.') }
|
|
30
|
+
} else {
|
|
31
|
+
warnings.push(`${image.ref} is not on this computer, so the files assume the current image's settings and are not pinned to a digest.`)
|
|
32
|
+
}
|
|
33
|
+
const settings = settingsFor(answers, caps)
|
|
34
|
+
const placeholders = Object.fromEntries(Object.entries(settings.secrets).map(([name, ref]) => [name, placeholder(name, ref)]))
|
|
35
|
+
const files = {}
|
|
36
|
+
if (answers.export.format === 'compose') {
|
|
37
|
+
files['compose.yaml'] = renderCompose(answers, { image: image.pinned, hostGateway: settings.hostGateway, pullPolicy: null })
|
|
38
|
+
files[SETTINGS_FILE] = envFileText(settings.env, 'Settings for Slatebox. No secrets.')
|
|
39
|
+
files[`${SECRETS_FILE}.example`] = envFileText(placeholders, `Copy to ${SECRETS_FILE} (mode 0600) and fill in. Never commit the real file.`)
|
|
40
|
+
files['README.md'] = `# Slatebox "${answers.name}"\n\n1. \`cp ${SECRETS_FILE}.example ${SECRETS_FILE} && chmod 600 ${SECRETS_FILE}\` and fill in each value.\n2. \`docker compose up -d --wait\`\n3. Open ${answers.address.url}\n\nBack up with \`docker exec ${answers.name} slatebox backup > slatebox-backup.gz\`, and keep SLATEBOX_KEY_ENCRYPTION_KEY with your backups: they do not contain it.\n`
|
|
41
|
+
} else {
|
|
42
|
+
const record = stringify({ ...answers, imageDigest: image.pinned, secretRefs: settings.secrets, state: 'exported' })
|
|
43
|
+
const secret = renderSecret(answers, placeholders)
|
|
44
|
+
if (answers.export.format === 'manifests') {
|
|
45
|
+
files['slatebox.yaml'] = `# Slatebox "${answers.name}". Apply with: kubectl apply --server-side -f slatebox.yaml (after the Secret).\n${stringifyAll(renderK8s(answers, { image: image.pinned, env: settings.env, record }))}`
|
|
46
|
+
} else {
|
|
47
|
+
const version = ctx.version
|
|
48
|
+
for (const [path, text] of Object.entries(renderHelmChart(answers, { image: image.pinned, env: settings.env, version, appVersion: image.pinned.split(/[@:]/).pop().slice(0, 19) }))) {
|
|
49
|
+
files[join('slatebox', path)] = text
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
files['secret.example.yaml'] = `# Fill in, then: kubectl apply -n ${answers.k8s.namespace} -f secret.yaml (never commit the filled-in file)\n${stringify(secret)}`
|
|
53
|
+
files['README.md'] = `# Slatebox "${answers.name}" on Kubernetes\n\n1. Copy secret.example.yaml to secret.yaml, fill in each value, apply it.\n2. ${answers.export.format === 'helm' ? `helm upgrade --install ${answers.name} ./slatebox -n ${answers.k8s.namespace} --create-namespace` : 'kubectl apply --server-side -f slatebox.yaml'}\n3. Open ${answers.address.url}${answers.k8s.route === 'none' ? ` after kubectl -n ${answers.k8s.namespace} port-forward svc/${names(answers).service} 7070:7070` : ''}\n`
|
|
54
|
+
}
|
|
55
|
+
const plan = emptyPlan({
|
|
56
|
+
action: 'export', target: 'export', name: answers.name, where: dir, address: answers.address.url,
|
|
57
|
+
image: { ref: image.ref, pinned: image.pinned }, files: Object.keys(files).map(path => ({ path: join(dir, path) })),
|
|
58
|
+
warnings: [...warnings, ...settings.warnings], notes: settings.notes,
|
|
59
|
+
})
|
|
60
|
+
ctx.emitPlan(plan)
|
|
61
|
+
if (planOnly) return { planned: true, plan }
|
|
62
|
+
const clashes = Object.keys(files).filter(path => existsSync(join(dir, path)) && !ctx.yes)
|
|
63
|
+
if (clashes.length && !ctx.interactive) {
|
|
64
|
+
throw new InstallError(EXIT.NEEDS_INPUT, `${dir} already has ${clashes.join(', ')}. Run again with --yes to overwrite them.`, { needsConfirmation: true })
|
|
65
|
+
}
|
|
66
|
+
if (clashes.length) await ctx.confirm({ ...plan, action: 'export' })
|
|
67
|
+
for (const [path, text] of Object.entries(files)) {
|
|
68
|
+
const full = join(dir, path)
|
|
69
|
+
mkdirSync(dirname(full), { recursive: true })
|
|
70
|
+
writeFileSync(full, text)
|
|
71
|
+
}
|
|
72
|
+
return { address: answers.address.url, name: answers.name, target: 'export', format: answers.export.format, dir, files: Object.keys(files), imageDigest: image.pinned }
|
|
73
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// A Docker host: this computer, or a Linux server reached over SSH. The
|
|
2
|
+
// install flow (docker.mjs) is the same for both; only these primitives differ.
|
|
3
|
+
import { accessSync, constants, existsSync, mkdirSync, readFileSync, renameSync, rmSync, rmdirSync, statSync, writeFileSync, chmodSync } from 'node:fs'
|
|
4
|
+
import { createServer } from 'node:net'
|
|
5
|
+
import { dirname, join } from 'node:path'
|
|
6
|
+
import { EXIT, InstallError } from '../errors.mjs'
|
|
7
|
+
import { shq } from '../runner.mjs'
|
|
8
|
+
|
|
9
|
+
function bindable(port, address) {
|
|
10
|
+
return new Promise(resolve => {
|
|
11
|
+
const server = createServer()
|
|
12
|
+
server.once('error', error => resolve(['EADDRNOTAVAIL', 'EAFNOSUPPORT'].includes(error.code) ? 'n/a' : false))
|
|
13
|
+
server.listen({ port, host: address, exclusive: true }, () => server.close(() => resolve(true)))
|
|
14
|
+
})
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Is a TCP port free on this computer? Bind it on every interface, as Docker
|
|
19
|
+
* would, and on the loopback addresses too: on macOS a dev server on
|
|
20
|
+
* 127.0.0.1 or ::1 does not stop a bind on 0.0.0.0, yet it answers
|
|
21
|
+
* http://localhost:<port> first.
|
|
22
|
+
*/
|
|
23
|
+
export async function portFree(port) {
|
|
24
|
+
for (const address of ['0.0.0.0', '127.0.0.1', '::1']) {
|
|
25
|
+
if ((await bindable(port, address)) === false) return false
|
|
26
|
+
}
|
|
27
|
+
return true
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The absolute path of a program on PATH, or null (cron runs with a short PATH, so scripts name it in full). */
|
|
31
|
+
export function which(name, path = process.env.PATH || '') {
|
|
32
|
+
for (const dir of path.split(':').filter(Boolean)) {
|
|
33
|
+
const candidate = join(dir, name)
|
|
34
|
+
try {
|
|
35
|
+
accessSync(candidate, constants.X_OK)
|
|
36
|
+
if (statSync(candidate).isFile()) return candidate
|
|
37
|
+
} catch { /* not here */ }
|
|
38
|
+
}
|
|
39
|
+
return null
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// The files an install writes into its folder; deleting data removes these and nothing else.
|
|
43
|
+
export const MARKER = '.slatebox-install'
|
|
44
|
+
export const INSTALL_FILES = ['compose.yaml', 'slatebox.env', 'secrets.env', 'secrets.kept.env', 'backup.sh', 'backup.log', 'install.yaml', MARKER]
|
|
45
|
+
const BACKUP_FILES = ['slatebox-*.gz', 'pre-upgrade-*.gz', '*.gz.part']
|
|
46
|
+
|
|
47
|
+
export async function firstFreePort(from = 7070, tries = 100) {
|
|
48
|
+
for (let port = from; port < from + tries; port++) if (await portFree(port)) return port
|
|
49
|
+
return null
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function localHost(ctx, { dir, name }) {
|
|
53
|
+
const docker = (args, options) => ctx.run('docker', args, options)
|
|
54
|
+
return {
|
|
55
|
+
kind: 'local',
|
|
56
|
+
where: 'this computer',
|
|
57
|
+
dir,
|
|
58
|
+
name,
|
|
59
|
+
docker,
|
|
60
|
+
compose: (args, options) => docker(['compose', '--project-directory', dir, '-f', join(dir, 'compose.yaml'), '-p', name, ...args], options),
|
|
61
|
+
async readFile(path) {
|
|
62
|
+
return existsSync(path) ? readFileSync(path, 'utf8') : null
|
|
63
|
+
},
|
|
64
|
+
async writeFile(path, content, mode = 0o600) {
|
|
65
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
|
|
66
|
+
writeFileSync(`${path}.tmp`, content, { mode })
|
|
67
|
+
chmodSync(`${path}.tmp`, mode)
|
|
68
|
+
renameSync(`${path}.tmp`, path)
|
|
69
|
+
},
|
|
70
|
+
async readMarker() {
|
|
71
|
+
const path = join(dir, MARKER)
|
|
72
|
+
return existsSync(path) ? readFileSync(path, 'utf8').trim() : null
|
|
73
|
+
},
|
|
74
|
+
async removeInstall({ backups }) {
|
|
75
|
+
for (const file of INSTALL_FILES) rmSync(join(dir, file), { force: true })
|
|
76
|
+
if (backups && existsSync(backups)) {
|
|
77
|
+
const { readdirSync } = await import('node:fs')
|
|
78
|
+
for (const file of readdirSync(backups)) if (/^(slatebox-|pre-upgrade-).*\.gz(\.part)?$/.test(file)) rmSync(join(backups, file), { force: true })
|
|
79
|
+
try { rmdirSync(backups) } catch { /* not empty: someone else's files */ }
|
|
80
|
+
}
|
|
81
|
+
try { rmdirSync(dir) } catch { /* not empty */ }
|
|
82
|
+
},
|
|
83
|
+
loadArchive: file => docker(['load', '-i', file], { timeout: 60 * 60_000 }),
|
|
84
|
+
/** A complete backup into a file on this host (the image writes nothing until the archive checks out). */
|
|
85
|
+
async backupToFile(container, path) {
|
|
86
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
|
|
87
|
+
const result = await docker(['exec', container, '/opt/slatebox/bin/slatebox', 'backup'], { outputFile: path, timeout: 60 * 60_000 })
|
|
88
|
+
if (result.code !== 0) rmSync(path, { force: true })
|
|
89
|
+
return result
|
|
90
|
+
},
|
|
91
|
+
restoreFromFile: (container, path) => docker(['exec', '-i', container, '/opt/slatebox/bin/slatebox', 'restore'], { inputFile: path, timeout: 60 * 60_000 }),
|
|
92
|
+
restoreFromLocal(container, path) { return this.restoreFromFile(container, path) },
|
|
93
|
+
sh: (script, options) => ctx.run('sh', ['-s'], { input: script, ...options }),
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* A server over SSH, with the system ssh (so ~/.ssh/config, ProxyJump, agents
|
|
99
|
+
* and hardware keys work). One multiplexed connection; every step is a small
|
|
100
|
+
* script on standard input, never left on the server.
|
|
101
|
+
*/
|
|
102
|
+
export function sshHost(ctx, ssh, { name, home }) {
|
|
103
|
+
const controlDir = join(home, 'cm')
|
|
104
|
+
const multiplex = controlDir.length < 50
|
|
105
|
+
if (multiplex) mkdirSync(controlDir, { recursive: true, mode: 0o700 })
|
|
106
|
+
const base = [
|
|
107
|
+
'-o', 'BatchMode=yes',
|
|
108
|
+
...(multiplex ? ['-o', 'ControlMaster=auto', '-o', `ControlPath=${join(controlDir, '%C')}`, '-o', 'ControlPersist=120'] : []),
|
|
109
|
+
'-p', String(ssh.port),
|
|
110
|
+
...(ssh.identity ? ['-i', ssh.identity.replace(/^~(?=\/)/, ctx.env.HOME || '')] : []),
|
|
111
|
+
...ssh.options.flatMap(option => ['-o', option]),
|
|
112
|
+
ssh.user ? `${ssh.user}@${ssh.host}` : ssh.host,
|
|
113
|
+
]
|
|
114
|
+
const host = {
|
|
115
|
+
kind: 'ssh',
|
|
116
|
+
where: `${ssh.user ? `${ssh.user}@` : ''}${ssh.host}`,
|
|
117
|
+
dir: ssh.dir,
|
|
118
|
+
name,
|
|
119
|
+
sudo: '',
|
|
120
|
+
remote: (command, options) => ctx.run('ssh', [...base, command], options),
|
|
121
|
+
docker: (args, options) => host.remote(`${host.sudo}docker ${args.map(shq).join(' ')}`, options),
|
|
122
|
+
// The directory is root's (mode 0700): compose reads it under sudo, never through a cd as the login user.
|
|
123
|
+
compose: (args, options) => host.remote(`${host.sudo}docker compose --project-directory ${shq(ssh.dir)} -f ${shq(join(ssh.dir, 'compose.yaml'))} -p ${shq(name)} ${args.map(shq).join(' ')}`, options),
|
|
124
|
+
/** The file's text; null only when it does not exist. Any other failure is an error, never "no file". */
|
|
125
|
+
async readFile(path) {
|
|
126
|
+
const script = `if [ -e ${shq(path)} ]; then cat ${shq(path)}; else exit 3; fi`
|
|
127
|
+
const result = await host.remote(`${host.sudo}sh -c ${shq(script)}`)
|
|
128
|
+
if (result.code === 0) return result.stdout
|
|
129
|
+
if (result.code === 3) return null
|
|
130
|
+
throw new InstallError(EXIT.PRECONDITION, `Could not read ${path} on ${host.where}: ${result.stderr.trim().split('\n').pop() || `exit ${result.code}`}. Nothing was changed.`)
|
|
131
|
+
},
|
|
132
|
+
async writeFile(path, content, mode = 0o600) {
|
|
133
|
+
const octal = mode.toString(8)
|
|
134
|
+
const script = `umask 077; mkdir -p ${shq(dirname(path))} && cat > ${shq(`${path}.tmp`)} && chmod ${octal} ${shq(`${path}.tmp`)} && mv ${shq(`${path}.tmp`)} ${shq(path)}`
|
|
135
|
+
const result = await host.remote(`${host.sudo}sh -c ${shq(script)}`, { input: content })
|
|
136
|
+
if (result.code !== 0) throw new Error(`Could not write ${path} on ${host.where}: ${result.stderr.trim()}`)
|
|
137
|
+
},
|
|
138
|
+
async readMarker() {
|
|
139
|
+
const result = await host.remote(`${host.sudo}cat ${shq(join(ssh.dir, MARKER))}`)
|
|
140
|
+
return result.code === 0 ? result.stdout.trim() : null
|
|
141
|
+
},
|
|
142
|
+
async removeInstall({ backups }) {
|
|
143
|
+
const files = INSTALL_FILES.map(file => shq(join(ssh.dir, file))).join(' ')
|
|
144
|
+
const old = backups ? BACKUP_FILES.map(glob => `${shq(backups)}/${glob}`).join(' ') : ''
|
|
145
|
+
const script = `rm -f ${files}${backups ? `; rm -f ${old}; rmdir ${shq(backups)} 2>/dev/null` : ''}; rmdir ${shq(ssh.dir)} 2>/dev/null; true`
|
|
146
|
+
const result = await host.remote(`${host.sudo}sh -c ${shq(script)}`)
|
|
147
|
+
if (result.code !== 0) throw new Error(`Could not remove the install files on ${host.where}: ${result.stderr.trim()}`)
|
|
148
|
+
},
|
|
149
|
+
loadArchive: file => host.remote(`${host.sudo}docker load`, { inputFile: file, timeout: 60 * 60_000 }),
|
|
150
|
+
async backupToFile(container, path) {
|
|
151
|
+
const script = `umask 077; mkdir -p ${shq(dirname(path))} && if docker exec ${shq(container)} /opt/slatebox/bin/slatebox backup > ${shq(`${path}.part`)}; then mv ${shq(`${path}.part`)} ${shq(path)}; else rm -f ${shq(`${path}.part`)}; exit 1; fi`
|
|
152
|
+
return host.remote(`${host.sudo}sh -c ${shq(script)}`, { timeout: 60 * 60_000 })
|
|
153
|
+
},
|
|
154
|
+
restoreFromFile: (container, path) => host.remote(`${host.sudo}sh -c ${shq(`docker exec -i ${shq(container)} /opt/slatebox/bin/slatebox restore < ${shq(path)}`)}`, { timeout: 60 * 60_000 }),
|
|
155
|
+
restoreFromLocal: (container, file) => host.remote(`${host.sudo}docker exec -i ${shq(container)} /opt/slatebox/bin/slatebox restore`, { inputFile: file, timeout: 60 * 60_000 }),
|
|
156
|
+
sh: (script, options) => host.remote(`${host.sudo}sh -s`, { input: script, ...options }),
|
|
157
|
+
close: () => (multiplex ? ctx.run('ssh', ['-O', 'exit', ...base], { timeout: 10_000 }) : null),
|
|
158
|
+
}
|
|
159
|
+
return host
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** What the server is, before anything is changed on it. One round trip. */
|
|
163
|
+
export function remotePreflightScript(ports) {
|
|
164
|
+
return `
|
|
165
|
+
set -u
|
|
166
|
+
uid=$(id -u)
|
|
167
|
+
echo "uid=$uid"
|
|
168
|
+
S=""
|
|
169
|
+
if [ "$uid" != 0 ]; then
|
|
170
|
+
if sudo -n true 2>/dev/null; then echo "sudo=yes"; S="sudo -n "; else echo "sudo=no"; fi
|
|
171
|
+
fi
|
|
172
|
+
echo "arch=$(uname -m)"
|
|
173
|
+
if [ -r /etc/os-release ]; then . /etc/os-release; echo "os=\${ID:-unknown} \${VERSION_ID:-}"; fi
|
|
174
|
+
d=$(command -v docker 2>/dev/null || true)
|
|
175
|
+
echo "docker_path=$d"
|
|
176
|
+
if [ -n "$d" ]; then
|
|
177
|
+
echo "docker_server=$($S docker version --format '{{.Server.Version}}' 2>/dev/null || true)"
|
|
178
|
+
echo "compose=$($S docker compose version --short 2>/dev/null || true)"
|
|
179
|
+
fi
|
|
180
|
+
echo "systemd=$([ -d /run/systemd/system ] && echo yes || echo no)"
|
|
181
|
+
echo "cron=$([ -d /etc/cron.d ] && echo yes || echo no)"
|
|
182
|
+
echo "disk_kb=$(df -Pk / 2>/dev/null | awk 'NR==2{print $4}')"
|
|
183
|
+
echo "mem_kb=$(awk '/MemTotal/{print $2}' /proc/meminfo 2>/dev/null)"
|
|
184
|
+
if command -v ss >/dev/null 2>&1; then
|
|
185
|
+
echo "listening=$(ss -ltnH 2>/dev/null | awk '{print $4}' | sed 's/.*://' | sort -un | tr '\\n' ' ')"
|
|
186
|
+
else
|
|
187
|
+
l=""; for p in ${ports.join(' ')}; do (exec 3<>/dev/tcp/127.0.0.1/$p) 2>/dev/null && l="$l $p"; done; echo "listening=$l"
|
|
188
|
+
fi
|
|
189
|
+
if command -v ufw >/dev/null 2>&1; then echo "ufw=$($S ufw status 2>/dev/null | head -1 | awk '{print $2}')"; fi
|
|
190
|
+
if command -v firewall-cmd >/dev/null 2>&1; then echo "firewalld=$($S firewall-cmd --state 2>/dev/null || true)"; fi
|
|
191
|
+
echo "addresses=$(hostname -I 2>/dev/null || true)"
|
|
192
|
+
`
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function parseKeyValues(text) {
|
|
196
|
+
const out = {}
|
|
197
|
+
for (const line of text.split('\n')) {
|
|
198
|
+
const at = line.indexOf('=')
|
|
199
|
+
if (at > 0) out[line.slice(0, at).trim()] = line.slice(at + 1).trim()
|
|
200
|
+
}
|
|
201
|
+
return out
|
|
202
|
+
}
|
|
@@ -0,0 +1,366 @@
|
|
|
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 { stringifyAll } from '../yaml.mjs'
|
|
16
|
+
|
|
17
|
+
const SLATEBOX = '/opt/slatebox/bin/slatebox'
|
|
18
|
+
const lastLine = text => text.trim().split('\n').filter(Boolean).pop() || ''
|
|
19
|
+
const PROD = /(^|[^a-z])(prod|production)([^a-z]|$)/i
|
|
20
|
+
|
|
21
|
+
export function kube(ctx, context) {
|
|
22
|
+
return (args, options) => ctx.run('kubectl', ['--context', context, ...args], options)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Which context, and may the installer touch it? */
|
|
26
|
+
export async function chooseContext(ctx, answers, { explicit }) {
|
|
27
|
+
let context = answers.k8s.context
|
|
28
|
+
if (!context) {
|
|
29
|
+
const current = await ctx.run('kubectl', ['config', 'current-context'])
|
|
30
|
+
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.')
|
|
31
|
+
if (current.code !== 0 || !current.stdout.trim()) throw new InstallError(EXIT.PRECONDITION, 'There is no current kube context. Give one with --k8s-context <name>.')
|
|
32
|
+
context = current.stdout.trim()
|
|
33
|
+
}
|
|
34
|
+
if (PROD.test(context) && !explicit) {
|
|
35
|
+
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' })
|
|
36
|
+
}
|
|
37
|
+
return context
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const RESOURCES = answers => [
|
|
41
|
+
['configmaps', ''], ['secrets', ''], ['services', ''], ['persistentvolumeclaims', ''], ['statefulsets', 'apps'],
|
|
42
|
+
...(answers.k8s.route === 'ingress' ? [['ingresses', 'networking.k8s.io']] : []),
|
|
43
|
+
...(answers.k8s.route === 'gateway' ? [['httproutes', 'gateway.networking.k8s.io']] : []),
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
async function preflight(ctx, k, answers, context) {
|
|
47
|
+
const version = await k(['version', '-o', 'json'], { timeout: 30_000 })
|
|
48
|
+
if (version.code !== 0) throw new InstallError(EXIT.PRECONDITION, `The cluster of context "${context}" does not answer: ${lastLine(version.stderr)}`)
|
|
49
|
+
const ns = answers.k8s.namespace
|
|
50
|
+
const nsExists = (await k(['get', 'namespace', ns, '-o', 'name'])).code === 0
|
|
51
|
+
const checks = [
|
|
52
|
+
...(nsExists ? [] : [['create', 'namespaces', '']]),
|
|
53
|
+
...RESOURCES(answers).flatMap(([resource, group]) => [['create', resource, group], ['patch', resource, group]]),
|
|
54
|
+
// Reading the Secret is how the key encryption key is kept: without it the installer would make a new one.
|
|
55
|
+
['get', 'secrets', ''], ['get', 'pods', ''], ['delete', 'pods', ''], ['create', 'pods/exec', ''],
|
|
56
|
+
]
|
|
57
|
+
const denied = []
|
|
58
|
+
for (const [verb, resource, group] of checks) {
|
|
59
|
+
const result = await k(['auth', 'can-i', verb, group ? `${resource}.${group}` : resource, ...(resource === 'namespaces' ? [] : ['-n', ns])])
|
|
60
|
+
if (result.stdout.trim() !== 'yes') denied.push(`${verb} ${group ? `${resource}.${group}` : resource}${resource === 'namespaces' ? '' : ` in ${ns}`}`)
|
|
61
|
+
}
|
|
62
|
+
if (denied.length) {
|
|
63
|
+
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 })
|
|
64
|
+
}
|
|
65
|
+
const notes = []
|
|
66
|
+
if (answers.k8s.storageClass) {
|
|
67
|
+
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}".`)
|
|
68
|
+
} else {
|
|
69
|
+
const classes = await k(['get', 'storageclass', '-o', 'json'])
|
|
70
|
+
const items = classes.code === 0 ? JSON.parse(classes.stdout).items : []
|
|
71
|
+
const preferred = items.find(item => item.metadata.annotations?.['storageclass.kubernetes.io/is-default-class'] === 'true')
|
|
72
|
+
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'}).`)
|
|
73
|
+
notes.push(`Volumes from the default StorageClass "${preferred.metadata.name}".`)
|
|
74
|
+
}
|
|
75
|
+
if (answers.k8s.tlsIssuer) {
|
|
76
|
+
const { kind, name } = answers.k8s.tlsIssuer
|
|
77
|
+
const args = kind === 'Issuer' ? ['get', 'issuers.cert-manager.io', name, '-n', ns] : ['get', 'clusterissuers.cert-manager.io', name]
|
|
78
|
+
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.`)
|
|
79
|
+
}
|
|
80
|
+
if (answers.k8s.route === 'gateway') {
|
|
81
|
+
const [gns, gname] = answers.k8s.gatewayRef.split('/')
|
|
82
|
+
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}".`)
|
|
83
|
+
}
|
|
84
|
+
if (answers.k8s.route === 'ingress' && answers.k8s.ingressClass) {
|
|
85
|
+
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}".`)
|
|
86
|
+
}
|
|
87
|
+
return { nsExists, notes }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* A registry reference the cluster can pull, pinned when this computer can tell
|
|
92
|
+
* the digest. For an upgrade (refresh) a tag is fetched here first, because a
|
|
93
|
+
* tag string that did not change says nothing about the bytes behind it; if
|
|
94
|
+
* no digest can be found that way the upgrade is refused rather than called
|
|
95
|
+
* "nothing to change".
|
|
96
|
+
*/
|
|
97
|
+
export async function clusterImage(ctx, ref, { refresh = false } = {}) {
|
|
98
|
+
const wanted = ref || DEFAULT_IMAGE
|
|
99
|
+
if (wanted.includes('@sha256:')) return { ref: wanted, pinned: wanted, local: false }
|
|
100
|
+
let pullError = null
|
|
101
|
+
if (refresh && isTag(wanted)) {
|
|
102
|
+
const pulled = await ctx.run('docker', ['pull', wanted], { timeout: 60 * 60_000 })
|
|
103
|
+
if (pulled.code !== 0) pullError = pulled.stderr.trim().split('\n').pop() || 'docker pull failed'
|
|
104
|
+
}
|
|
105
|
+
const inspected = await ctx.run('docker', ['image', 'inspect', '--format', '{{json .}}', wanted])
|
|
106
|
+
const info = inspected.code === 0 ? JSON.parse(inspected.stdout) : null
|
|
107
|
+
const repository = wanted.replace(/:[^/:]+$/, '')
|
|
108
|
+
const digest = info && (info.RepoDigests || []).find(item => item.startsWith(`${repository}@`))
|
|
109
|
+
if (refresh && isTag(wanted) && (pullError || !digest)) {
|
|
110
|
+
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>.`)
|
|
111
|
+
}
|
|
112
|
+
if (info) return { ref: wanted, pinned: hasRegistry(wanted) && digest ? digest : wanted, local: true, id: info.Id, architecture: info.Architecture || null }
|
|
113
|
+
return { ref: wanted, pinned: wanted, local: false }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function checkNodeArch(k, image, context) {
|
|
117
|
+
if (!image.architecture) return
|
|
118
|
+
const nodes = await k(['get', 'nodes', '-o', 'jsonpath={.items[*].metadata.labels.kubernetes\\.io/arch}'])
|
|
119
|
+
if (nodes.code !== 0 || !nodes.stdout.trim()) return // nodes may not be listable with namespace rights
|
|
120
|
+
checkArch(image, nodes.stdout.trim().split(/\s+/), `the nodes of "${context}"`)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function capabilities(ctx, image, warnings) {
|
|
124
|
+
if (image.local) {
|
|
125
|
+
try { return await probeImage((args, o) => ctx.run('docker', args, o), image.id || image.ref) } catch { /* fall through */ }
|
|
126
|
+
}
|
|
127
|
+
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).`)
|
|
128
|
+
return FALLBACK_CAPABILITIES
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The Secret's values; {} only when it does not exist. Any other failure stops the run: a guess would make a new key. */
|
|
132
|
+
async function existingSecret(k, answers) {
|
|
133
|
+
const result = await k(['get', 'secret', names(answers).secret, '-n', answers.k8s.namespace, '-o', 'json'])
|
|
134
|
+
if (result.code !== 0) {
|
|
135
|
+
if (/NotFound|not found/.test(result.stderr)) return {}
|
|
136
|
+
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.`)
|
|
137
|
+
}
|
|
138
|
+
const data = JSON.parse(result.stdout).data || {}
|
|
139
|
+
return Object.fromEntries(Object.entries(data).map(([key, value]) => [key, Buffer.from(value, 'base64').toString('utf8')]))
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function currentImage(k, answers) {
|
|
143
|
+
const result = await k(['get', 'statefulset', names(answers).set, '-n', answers.k8s.namespace, '-o', 'jsonpath={.spec.template.spec.containers[0].image}'])
|
|
144
|
+
return result.code === 0 ? result.stdout.trim() || null : null
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function rollout(ctx, k, answers) {
|
|
148
|
+
const n = names(answers)
|
|
149
|
+
const status = await k(['rollout', 'status', `statefulset/${n.set}`, '-n', answers.k8s.namespace, `--timeout=${ctx.healthTimeout}s`], { timeout: (ctx.healthTimeout + 60) * 1000 })
|
|
150
|
+
if (status.code !== 0) return { ok: false, why: lastLine(status.stderr) || 'rollout did not finish' }
|
|
151
|
+
const deep = await k(['exec', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'health', '--deep', '--wait', '60'], { timeout: 120_000 })
|
|
152
|
+
if (deep.code !== 0) return { ok: false, why: lastLine(deep.stderr) || 'slatebox health failed' }
|
|
153
|
+
if (answers.k8s.route !== 'none') {
|
|
154
|
+
try {
|
|
155
|
+
const response = await ctx.fetch(`${answers.address.url}/readyz`, { signal: AbortSignal.timeout(8000) })
|
|
156
|
+
if (!response.ok) return { ok: true, warning: `${answers.address.url}/readyz answered HTTP ${response.status} from here; check the route and DNS.` }
|
|
157
|
+
} catch (error) {
|
|
158
|
+
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}.` }
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return { ok: true }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const apply = (k, objects) => k(['apply', '--server-side', `--field-manager=${MANAGER}`, '-f', '-'], { input: stringifyAll(objects), timeout: 120_000 })
|
|
165
|
+
|
|
166
|
+
export async function applyK8s(ctx, answers, { record, planOnly = false, imageRef, explicitContext, refresh = false }) {
|
|
167
|
+
const { out } = ctx
|
|
168
|
+
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>.')
|
|
169
|
+
const context = await chooseContext(ctx, answers, { explicit: explicitContext })
|
|
170
|
+
answers.k8s.context = context
|
|
171
|
+
const k = kube(ctx, context)
|
|
172
|
+
out.step('preflight', 'start', `Checking kube context "${context}"`)
|
|
173
|
+
const facts = await preflight(ctx, k, answers, context)
|
|
174
|
+
out.step('preflight', 'ok', `Context "${context}", namespace ${answers.k8s.namespace}${facts.nsExists ? '' : ' (new)'}`)
|
|
175
|
+
|
|
176
|
+
const warnings = []
|
|
177
|
+
const image = await clusterImage(ctx, imageRef || answers.image, { refresh })
|
|
178
|
+
await checkNodeArch(k, image, context)
|
|
179
|
+
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.`)
|
|
180
|
+
const caps = await capabilities(ctx, image, warnings)
|
|
181
|
+
const settings = settingsFor(answers, caps)
|
|
182
|
+
const stored = await existingSecret(k, answers)
|
|
183
|
+
const previous = await currentImage(k, answers)
|
|
184
|
+
if (settings.secrets.SLATEBOX_KEY_ENCRYPTION_KEY === 'generate' && !stored.SLATEBOX_KEY_ENCRYPTION_KEY && !ctx.flags['new-encryption-key']) {
|
|
185
|
+
const pvc = (await k(['get', 'pvc', `data-${names(answers).set}-0`, '-n', answers.k8s.namespace, '-o', 'name'])).code === 0
|
|
186
|
+
if (previous || pvc) {
|
|
187
|
+
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' })
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
const { values, generated } = await secretValues(ctx, settings.secrets, stored)
|
|
191
|
+
const secretsHash = createHash('sha256').update(JSON.stringify(values)).digest('hex')
|
|
192
|
+
const imageChanged = Boolean(previous && previous !== image.pinned)
|
|
193
|
+
|
|
194
|
+
const n = names(answers)
|
|
195
|
+
const nextRecord = {
|
|
196
|
+
...answers, image: image.ref, installedVersion: ctx.version, imageRef: image.ref, imageDigest: image.pinned,
|
|
197
|
+
previousImageDigest: imageChanged ? previous : record?.previousImageDigest ?? null,
|
|
198
|
+
secretRefs: settings.secrets, secretsLocation: `Secret ${answers.k8s.namespace}/${n.secret} in context ${context}`,
|
|
199
|
+
installedAt: record?.installedAt || new Date().toISOString(), state: 'installed',
|
|
200
|
+
}
|
|
201
|
+
const objects = renderK8s(answers, { image: image.pinned, env: settings.env, secretsHash, record: recordText(nextRecord) })
|
|
202
|
+
const secret = renderSecret(answers, values)
|
|
203
|
+
|
|
204
|
+
// Server-side diff: the same answers applied twice change nothing.
|
|
205
|
+
const all = [objects[0], secret, ...objects.slice(1)]
|
|
206
|
+
const diff = previous ? await k(['diff', '--server-side', `--field-manager=${MANAGER}`, '-f', '-'], { input: stringifyAll(all), timeout: 120_000 }) : { code: 1 }
|
|
207
|
+
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'
|
|
208
|
+
const plan = emptyPlan({
|
|
209
|
+
action: nothing ? 'nothing' : previous ? (imageChanged ? 'upgrade' : 'change') : 'install', target: 'k8s', name: answers.name,
|
|
210
|
+
where: `kube context "${context}", namespace ${answers.k8s.namespace}`, address: answers.address.url,
|
|
211
|
+
image: { ref: image.ref, pinned: image.pinned, previous: previous || undefined },
|
|
212
|
+
secretsLocation: nextRecord.secretsLocation, warnings: [...warnings, ...settings.warnings], notes: [...facts.notes, ...settings.notes],
|
|
213
|
+
objects: [...objects.slice(0, 1), secret, ...objects.slice(1)].map(object => `${object.kind}/${object.metadata.name}`),
|
|
214
|
+
})
|
|
215
|
+
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')}`)
|
|
216
|
+
plan.commands.push(`kubectl --context ${context} apply --server-side --field-manager=${MANAGER} -f - (the objects above, on standard input)`,
|
|
217
|
+
`kubectl rollout status statefulset/${n.set} -n ${answers.k8s.namespace}`, `kubectl exec ${n.pod} -c slatebox -- slatebox health --deep`)
|
|
218
|
+
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.`)
|
|
219
|
+
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.')
|
|
220
|
+
ctx.emitPlan(plan)
|
|
221
|
+
if (planOnly) return { planned: true, plan }
|
|
222
|
+
if (nothing) {
|
|
223
|
+
nextRecord.lastHealthy = new Date().toISOString()
|
|
224
|
+
ctx.recordFile = writeRecord(ctx.home, nextRecord)
|
|
225
|
+
return {
|
|
226
|
+
address: answers.address.url, name: answers.name, target: 'k8s', version: null, imageDigest: image.pinned,
|
|
227
|
+
installRecord: ctx.recordFile, secretsFile: nextRecord.secretsLocation, nothingToChange: true, keyGenerated: false, fresh: false,
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
await ctx.confirm(plan)
|
|
231
|
+
|
|
232
|
+
let preUpgrade = null
|
|
233
|
+
if (imageChanged) {
|
|
234
|
+
preUpgrade = join(installDir(ctx.home, answers.name), 'backups', `pre-upgrade-${Date.now()}.gz`)
|
|
235
|
+
mkdirSync(join(preUpgrade, '..'), { recursive: true, mode: 0o700 })
|
|
236
|
+
out.step('backup', 'start', `Backing up before the upgrade to ${preUpgrade}`)
|
|
237
|
+
const backup = await k(['exec', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'backup'], { outputFile: preUpgrade, timeout: 60 * 60_000 })
|
|
238
|
+
if (backup.code !== 0) {
|
|
239
|
+
rmSync(preUpgrade, { force: true })
|
|
240
|
+
throw new InstallError(EXIT.PRECONDITION, `The backup before the upgrade failed, so nothing was changed: ${lastLine(backup.stderr)}`)
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
const previousObjects = previous ? previousState(answers, record, { image: previous, caps, stored, nextRecord }) : null
|
|
244
|
+
|
|
245
|
+
out.step('apply', 'start', `Applying ${objects.length + 1} objects to "${context}"`)
|
|
246
|
+
const applied = await apply(k, all)
|
|
247
|
+
if (applied.code !== 0) throw new InstallError(EXIT.PRECONDITION, `kubectl apply failed: ${lastLine(applied.stderr)}`)
|
|
248
|
+
out.step('apply', 'ok', 'Applied')
|
|
249
|
+
out.step('start', 'start', `Waiting until Slatebox is ready (up to ${ctx.healthTimeout}s)`)
|
|
250
|
+
const result = await rollout(ctx, k, answers)
|
|
251
|
+
if (!result.ok) {
|
|
252
|
+
out.step('start', 'fail', `Slatebox did not become ready: ${result.why}`)
|
|
253
|
+
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}`]
|
|
254
|
+
if (!previousObjects) {
|
|
255
|
+
throw new InstallError(EXIT.ROLLED_BACK, `Slatebox did not become ready (${result.why}). The objects are kept for you to inspect.`, { commands: manual })
|
|
256
|
+
}
|
|
257
|
+
out.step('rollback', 'start', 'Putting the previous version back')
|
|
258
|
+
await apply(k, previousObjects)
|
|
259
|
+
// A StatefulSet does not replace a pod that never became ready; do it here.
|
|
260
|
+
await k(['delete', 'pod', n.pod, '-n', answers.k8s.namespace, '--wait=false'])
|
|
261
|
+
let back = await rollout(ctx, k, answers)
|
|
262
|
+
if (back.ok && preUpgrade) {
|
|
263
|
+
const restored = await k(['exec', '-i', '-n', answers.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'restore'], { inputFile: preUpgrade, timeout: 60 * 60_000 })
|
|
264
|
+
if (restored.code !== 0) back = { ok: false, why: lastLine(restored.stderr) }
|
|
265
|
+
}
|
|
266
|
+
if (!back.ok) {
|
|
267
|
+
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.`, {
|
|
268
|
+
commands: [...manual, ...(preUpgrade ? [`kubectl --context ${context} -n ${answers.k8s.namespace} exec -i ${n.pod} -c slatebox -- slatebox restore < ${preUpgrade}`] : [])],
|
|
269
|
+
})
|
|
270
|
+
}
|
|
271
|
+
throw new InstallError(EXIT.ROLLED_BACK, `The change failed (${result.why}), so the previous version was put back and is ready.`, { commands: manual })
|
|
272
|
+
}
|
|
273
|
+
if (result.warning) out.step('route', 'warn', result.warning)
|
|
274
|
+
out.step('start', 'ok', `Slatebox is ready${answers.k8s.route === 'none' ? ' (port-forward to reach it)' : ` at ${answers.address.url}`}`)
|
|
275
|
+
if (!previous) {
|
|
276
|
+
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.`}`)
|
|
277
|
+
}
|
|
278
|
+
nextRecord.lastHealthy = new Date().toISOString()
|
|
279
|
+
ctx.recordFile = writeRecord(ctx.home, nextRecord)
|
|
280
|
+
ctx.record = nextRecord
|
|
281
|
+
return {
|
|
282
|
+
address: answers.address.url, name: answers.name, target: 'k8s', version: null, imageDigest: image.pinned,
|
|
283
|
+
installRecord: `${ctx.recordFile} (and ConfigMap ${answers.k8s.namespace}/${n.record})`, secretsFile: nextRecord.secretsLocation,
|
|
284
|
+
keyGenerated: generated.includes('SLATEBOX_KEY_ENCRYPTION_KEY'), fresh: !previous,
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* What was running before this change: the previous answers (from the install
|
|
290
|
+
* record) with the previous Secret's values and image, so a rollback puts the
|
|
291
|
+
* settings and keys back too, not only the image.
|
|
292
|
+
*/
|
|
293
|
+
const withoutHealthy = ({ lastHealthy, ...rest }) => rest
|
|
294
|
+
|
|
295
|
+
function previousState(answers, record, { image, caps, stored, nextRecord }) {
|
|
296
|
+
let before = answers
|
|
297
|
+
if (record) {
|
|
298
|
+
const resolved = resolveAnswers(collect({ record }), {})
|
|
299
|
+
if (!resolved.errors.length) before = { ...resolved.answers, k8s: { ...resolved.answers.k8s, context: answers.k8s.context } }
|
|
300
|
+
}
|
|
301
|
+
const settings = settingsFor(before, caps)
|
|
302
|
+
const values = Object.fromEntries(Object.keys(settings.secrets).filter(name => name in stored).map(name => [name, stored[name]]))
|
|
303
|
+
const secretsHash = createHash('sha256').update(JSON.stringify(values)).digest('hex')
|
|
304
|
+
const objects = renderK8s(before, { image, env: settings.env, secretsHash, record: recordText(record ? withoutHealthy(record) : { ...nextRecord, imageDigest: image }) })
|
|
305
|
+
return [objects[0], renderSecret(before, values), ...objects.slice(1)]
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export async function statusK8s(ctx, record) {
|
|
309
|
+
const k = kube(ctx, record.k8s.context)
|
|
310
|
+
const n = names(record)
|
|
311
|
+
const pod = await k(['get', 'pod', n.pod, '-n', record.k8s.namespace, '-o', 'json'])
|
|
312
|
+
const info = pod.code === 0 ? JSON.parse(pod.stdout) : null
|
|
313
|
+
const ready = info?.status?.containerStatuses?.find(item => item.name === 'slatebox')?.ready
|
|
314
|
+
const version = ready ? await k(['exec', '-n', record.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'version']) : null
|
|
315
|
+
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
|
|
316
|
+
return {
|
|
317
|
+
name: record.name, target: 'k8s', where: `context ${record.k8s.context}, namespace ${record.k8s.namespace}`, address: record.address.url,
|
|
318
|
+
running: Boolean(info), health: ready ? 'healthy' : info ? info.status.phase : 'missing',
|
|
319
|
+
version: version?.code === 0 ? JSON.parse(version.stdout) : null, imageDigest: record.imageDigest,
|
|
320
|
+
ai: record.ai.mode === 'none' ? 'off' : record.ai.providers.map(provider => provider.id).join(', '),
|
|
321
|
+
sso: record.sso.enabled ? 'on' : 'off', lastBackup: backups?.stdout.trim() || null,
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export async function backupK8s(ctx, record, { to }) {
|
|
326
|
+
const k = kube(ctx, record.k8s.context)
|
|
327
|
+
const n = names(record)
|
|
328
|
+
const dir = to ? (to.startsWith('/') ? to : join(process.cwd(), to)) : join(installDir(ctx.home, record.name), 'backups')
|
|
329
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
330
|
+
const file = join(dir, `slatebox-${new Date().toISOString().replace(/[-:]/g, '').replace(/\..*/, '').replace('T', '-')}.gz`)
|
|
331
|
+
const result = await k(['exec', '-n', record.k8s.namespace, n.pod, '-c', 'slatebox', '--', SLATEBOX, 'backup'], { outputFile: file, timeout: 60 * 60_000 })
|
|
332
|
+
if (result.code !== 0) { rmSync(file, { force: true }); throw new InstallError(EXIT.PRECONDITION, `The backup failed: ${lastLine(result.stderr)}`) }
|
|
333
|
+
return { file, where: 'this computer' }
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
export async function restoreK8s(ctx, record, archive) {
|
|
337
|
+
const k = kube(ctx, record.k8s.context)
|
|
338
|
+
const result = await k(['exec', '-i', '-n', record.k8s.namespace, names(record).pod, '-c', 'slatebox', '--', SLATEBOX, 'restore'], { inputFile: archive, timeout: 60 * 60_000 })
|
|
339
|
+
if (result.code !== 0) throw new InstallError(EXIT.PRECONDITION, `The restore failed: ${lastLine(result.stderr)}`)
|
|
340
|
+
return { restored: archive }
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export async function uninstallK8s(ctx, record, { deleteData }) {
|
|
344
|
+
const k = kube(ctx, record.k8s.context)
|
|
345
|
+
const ns = record.k8s.namespace
|
|
346
|
+
const n = names(record)
|
|
347
|
+
const selector = `slatebox.com/install=${record.name}`
|
|
348
|
+
const kinds = ['statefulset', 'service', 'ingress.networking.k8s.io', 'configmap', ...(record.k8s.route === 'gateway' ? ['httproutes.gateway.networking.k8s.io'] : [])]
|
|
349
|
+
for (const kind of kinds) await k(['delete', kind, '-n', ns, '-l', selector, '--ignore-not-found'])
|
|
350
|
+
if (deleteData) {
|
|
351
|
+
await k(['delete', 'pvc,secret', '-n', ns, '-l', selector, '--ignore-not-found'])
|
|
352
|
+
await k(['delete', 'pvc', `data-${n.set}-0`, '-n', ns, '--ignore-not-found'])
|
|
353
|
+
return { dataDeleted: true }
|
|
354
|
+
}
|
|
355
|
+
return { dataDeleted: false, volume: `PersistentVolumeClaims data-${n.set}-0 and ${n.backups} in ${ns}`, secretsFile: `Secret ${ns}/${n.secret}` }
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
export function execNodeK8s(ctx, record, script, args = []) {
|
|
359
|
+
const k = kube(ctx, record.k8s.context)
|
|
360
|
+
return k(['exec', '-i', '-n', record.k8s.namespace, names(record).pod, '-c', 'slatebox', '--', 'node', '--input-type=module', '-', ...args], { input: script, timeout: 120_000 })
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export async function readSecretK8s(ctx, record, name) {
|
|
364
|
+
const k = kube(ctx, record.k8s.context)
|
|
365
|
+
return (await existingSecret(k, record))[name]
|
|
366
|
+
}
|