|
| 1 | +import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs"; |
| 2 | +import { tmpdir } from "node:os"; |
| 3 | +import { join, resolve } from "node:path"; |
| 4 | +import { runText } from "../lib/common"; |
| 5 | +import { reconfigureCmd } from "./system"; |
| 6 | + |
| 7 | +const PREFIX = "terrariumctl update"; |
| 8 | +const REPO_DIR = process.env.TERRARIUM_REPO_DIR ?? "/opt/terrarium"; |
| 9 | +const BUNDLE_DIR = process.env.TERRARIUM_BUNDLE_DIR ?? ""; |
| 10 | +const REPO_URL = process.env.TERRARIUM_REPO_URL ?? "https://github.com/terion-name/terrarium.git"; |
| 11 | +const GITHUB_REPO = process.env.TERRARIUM_GITHUB_REPO ?? "terion-name/terrarium"; |
| 12 | +const ANSIBLE_GALAXY_ATTEMPTS = 4; |
| 13 | + |
| 14 | +export type UpdateOptions = { |
| 15 | + ref?: string; |
| 16 | + reconfigure?: boolean; |
| 17 | +}; |
| 18 | + |
| 19 | +function requireRoot(): void { |
| 20 | + if (typeof process.getuid === "function" && process.getuid() !== 0) { |
| 21 | + throw new Error("run as root"); |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +function releaseArch(): string { |
| 26 | + if (process.arch === "x64") { |
| 27 | + return "x64"; |
| 28 | + } |
| 29 | + if (process.arch === "arm64") { |
| 30 | + return "arm64"; |
| 31 | + } |
| 32 | + throw new Error(`unsupported architecture: ${process.arch}`); |
| 33 | +} |
| 34 | + |
| 35 | +function isReleaseRef(ref: string): boolean { |
| 36 | + return /^v?[0-9]+(\.[0-9]+)*([.-][A-Za-z0-9]+)?$/.test(ref); |
| 37 | +} |
| 38 | + |
| 39 | +function localSourcePath(repoUrl: string): string { |
| 40 | + if (repoUrl.startsWith("file://")) { |
| 41 | + return repoUrl.slice("file://".length); |
| 42 | + } |
| 43 | + if (repoUrl.startsWith("/")) { |
| 44 | + return repoUrl; |
| 45 | + } |
| 46 | + return ""; |
| 47 | +} |
| 48 | + |
| 49 | +function syncTree(sourceDir: string, targetDir: string): void { |
| 50 | + if (resolve(sourceDir) === resolve(targetDir)) { |
| 51 | + throw new Error(`refusing to sync Terrarium source onto itself: ${sourceDir}`); |
| 52 | + } |
| 53 | + if (!existsSync(join(sourceDir, "ansible", "site.yml"))) { |
| 54 | + throw new Error(`Terrarium bundle is missing ansible/site.yml: ${sourceDir}`); |
| 55 | + } |
| 56 | + if (!existsSync(join(sourceDir, "dist", "terrariumctl"))) { |
| 57 | + throw new Error(`Terrarium bundle is missing dist/terrariumctl: ${sourceDir}`); |
| 58 | + } |
| 59 | + |
| 60 | + rmSync(targetDir, { recursive: true, force: true }); |
| 61 | + mkdirSync(targetDir, { recursive: true }); |
| 62 | + cpSync(sourceDir, targetDir, { |
| 63 | + recursive: true, |
| 64 | + force: true, |
| 65 | + filter: (source) => { |
| 66 | + const base = source.split("/").at(-1) ?? ""; |
| 67 | + return ![".git", "node_modules"].includes(base); |
| 68 | + } |
| 69 | + }); |
| 70 | + chmodSync(join(targetDir, "dist", "terrariumctl"), 0o755); |
| 71 | +} |
| 72 | + |
| 73 | +async function resolveLatestReleaseRef(arch: string): Promise<string> { |
| 74 | + const script = ` |
| 75 | +import json |
| 76 | +import os |
| 77 | +import sys |
| 78 | +
|
| 79 | +asset = os.environ["TERRARIUM_ASSET"] |
| 80 | +for release in json.load(sys.stdin): |
| 81 | + if release.get("draft") or release.get("prerelease"): |
| 82 | + continue |
| 83 | + if any(item.get("name") == asset for item in release.get("assets", [])): |
| 84 | + print(release.get("tag_name", "")) |
| 85 | + break |
| 86 | +`; |
| 87 | + const releases = await runText(["curl", "-fsSL", `https://api.github.com/repos/${GITHUB_REPO}/releases?per_page=50`], PREFIX); |
| 88 | + const resolved = await runText(["python3", "-c", script], PREFIX, { |
| 89 | + stdin: releases, |
| 90 | + env: { TERRARIUM_ASSET: `terrarium-linux-${arch}.zip` } |
| 91 | + }); |
| 92 | + const ref = resolved.trim(); |
| 93 | + if (!ref) { |
| 94 | + throw new Error("failed to resolve latest Terrarium release tag"); |
| 95 | + } |
| 96 | + return ref; |
| 97 | +} |
| 98 | + |
| 99 | +async function downloadReleaseBundle(ref: string): Promise<string> { |
| 100 | + const arch = releaseArch(); |
| 101 | + const resolvedRef = ref ? ref : await resolveLatestReleaseRef(arch); |
| 102 | + const workDir = mkdtempSync(join(tmpdir(), "terrarium-update-")); |
| 103 | + const assetUrl = `https://github.com/${GITHUB_REPO}/releases/download/${resolvedRef}/terrarium-linux-${arch}.zip`; |
| 104 | + |
| 105 | + try { |
| 106 | + await runText(["curl", "-fsSL", assetUrl, "-o", join(workDir, "terrarium.zip")], PREFIX); |
| 107 | + await runText(["unzip", "-q", join(workDir, "terrarium.zip"), "-d", workDir], PREFIX); |
| 108 | + return workDir; |
| 109 | + } catch (error) { |
| 110 | + rmSync(workDir, { recursive: true, force: true }); |
| 111 | + throw error; |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +async function syncSourceCheckout(ref: string): Promise<void> { |
| 116 | + if (!existsSync(join(REPO_DIR, ".git"))) { |
| 117 | + throw new Error("source update requires an existing git checkout in /opt/terrarium; use install.sh --update for release-bundle installs"); |
| 118 | + } |
| 119 | + await runText(["git", "-C", REPO_DIR, "fetch", "--tags", "origin"], PREFIX); |
| 120 | + await runText(["git", "-C", REPO_DIR, "checkout", ref], PREFIX); |
| 121 | + await runText(["git", "-C", REPO_DIR, "pull", "--ff-only", "origin", ref], PREFIX); |
| 122 | + const bun = existsSync("/opt/bun/bin/bun") ? "/opt/bun/bin/bun" : "bun"; |
| 123 | + await runText([bun, "install", "--frozen-lockfile"], PREFIX, { cwd: REPO_DIR }); |
| 124 | + await runText([bun, "scripts/build.ts"], PREFIX, { cwd: REPO_DIR }); |
| 125 | +} |
| 126 | + |
| 127 | +async function installAnsibleCollections(): Promise<void> { |
| 128 | + let lastOutput = ""; |
| 129 | + for (let attempt = 1; attempt <= ANSIBLE_GALAXY_ATTEMPTS; attempt += 1) { |
| 130 | + const result = Bun.spawn({ |
| 131 | + cmd: ["ansible-galaxy", "collection", "install", "-r", "requirements.yml"], |
| 132 | + cwd: join(REPO_DIR, "ansible"), |
| 133 | + stdout: "pipe", |
| 134 | + stderr: "pipe" |
| 135 | + }); |
| 136 | + const [exitCode, stdout, stderr] = await Promise.all([ |
| 137 | + result.exited, |
| 138 | + result.stdout ? new Response(result.stdout).text() : Promise.resolve(""), |
| 139 | + result.stderr ? new Response(result.stderr).text() : Promise.resolve("") |
| 140 | + ]); |
| 141 | + if (exitCode === 0) { |
| 142 | + return; |
| 143 | + } |
| 144 | + |
| 145 | + lastOutput = `${stdout}\n${stderr}`.trim(); |
| 146 | + if (attempt < ANSIBLE_GALAXY_ATTEMPTS) { |
| 147 | + console.warn(`${PREFIX}: ansible-galaxy collection install failed on attempt ${attempt}/${ANSIBLE_GALAXY_ATTEMPTS}; retrying`); |
| 148 | + await Bun.sleep(attempt * 5000); |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + throw new Error(`ansible-galaxy collection install failed after ${ANSIBLE_GALAXY_ATTEMPTS} attempts${lastOutput ? `\n${lastOutput}` : ""}`); |
| 153 | +} |
| 154 | + |
| 155 | +async function ensureUpdateDependencies(): Promise<void> { |
| 156 | + await runText(["apt-get", "-o", "DPkg::Lock::Timeout=900", "update", "-y"], PREFIX); |
| 157 | + await runText(["apt-get", "-o", "DPkg::Lock::Timeout=900", "install", "-y", "ca-certificates", "curl", "git", "ansible", "python3", "jq", "unzip"], PREFIX); |
| 158 | +} |
| 159 | + |
| 160 | +export async function updateCmd(options: UpdateOptions = {}): Promise<void> { |
| 161 | + requireRoot(); |
| 162 | + await ensureUpdateDependencies(); |
| 163 | + |
| 164 | + const requestedRef = options.ref ?? ""; |
| 165 | + const sourcePath = localSourcePath(REPO_URL); |
| 166 | + let downloadedBundle = ""; |
| 167 | + |
| 168 | + try { |
| 169 | + if (BUNDLE_DIR && existsSync(join(BUNDLE_DIR, "ansible", "site.yml"))) { |
| 170 | + console.log(`${PREFIX}: installing Terrarium release bundle into ${REPO_DIR}`); |
| 171 | + syncTree(BUNDLE_DIR, REPO_DIR); |
| 172 | + } else if (sourcePath && existsSync(join(sourcePath, "ansible", "site.yml"))) { |
| 173 | + console.log(`${PREFIX}: syncing local Terrarium source from ${sourcePath}`); |
| 174 | + syncTree(sourcePath, REPO_DIR); |
| 175 | + } else if (requestedRef && !isReleaseRef(requestedRef)) { |
| 176 | + await syncSourceCheckout(requestedRef); |
| 177 | + } else { |
| 178 | + downloadedBundle = await downloadReleaseBundle(requestedRef); |
| 179 | + console.log(`${PREFIX}: installing Terrarium release bundle into ${REPO_DIR}`); |
| 180 | + syncTree(downloadedBundle, REPO_DIR); |
| 181 | + } |
| 182 | + |
| 183 | + await installAnsibleCollections(); |
| 184 | + |
| 185 | + if (options.reconfigure !== false) { |
| 186 | + await reconfigureCmd({ applyHardening: false }); |
| 187 | + } |
| 188 | + } finally { |
| 189 | + if (downloadedBundle) { |
| 190 | + rmSync(downloadedBundle, { recursive: true, force: true }); |
| 191 | + } |
| 192 | + } |
| 193 | +} |
0 commit comments