|
| 1 | +import { NextResponse } from 'next/server' |
| 2 | +import { eq } from 'drizzle-orm' |
| 3 | +import { getDb } from '@/lib/db' |
| 4 | +import { adminServers } from '@sandchest/db/schema' |
| 5 | +import { decrypt } from '@/lib/encryption' |
| 6 | +import { createSshConnection, execCommand } from '@/lib/ssh' |
| 7 | +import { PROVISION_STEPS, type StepResult } from '@/lib/provisioner' |
| 8 | + |
| 9 | +export async function POST( |
| 10 | + _request: Request, |
| 11 | + { params }: { params: Promise<{ serverId: string }> }, |
| 12 | +) { |
| 13 | + const { serverId } = await params |
| 14 | + const db = getDb() |
| 15 | + const serverIdBuf = Buffer.from(serverId, 'hex') as unknown as Uint8Array |
| 16 | + |
| 17 | + const [server] = await db |
| 18 | + .select() |
| 19 | + .from(adminServers) |
| 20 | + .where(eq(adminServers.id, serverIdBuf)) |
| 21 | + .limit(1) |
| 22 | + |
| 23 | + if (!server) { |
| 24 | + return NextResponse.json({ error: 'Server not found' }, { status: 404 }) |
| 25 | + } |
| 26 | + |
| 27 | + if (server.provisionStatus !== 'failed') { |
| 28 | + return NextResponse.json({ error: 'Can only retry from failed state' }, { status: 409 }) |
| 29 | + } |
| 30 | + |
| 31 | + // Find the failed step index (PlanetScale may return JSON columns as strings) |
| 32 | + const raw = server.provisionSteps |
| 33 | + const steps: StepResult[] = Array.isArray(raw) |
| 34 | + ? raw as StepResult[] |
| 35 | + : typeof raw === 'string' |
| 36 | + ? JSON.parse(raw) as StepResult[] |
| 37 | + : [] |
| 38 | + const failedIndex = steps.findIndex((s) => s.status === 'failed') |
| 39 | + if (failedIndex === -1) { |
| 40 | + return NextResponse.json({ error: 'No failed step found' }, { status: 400 }) |
| 41 | + } |
| 42 | + |
| 43 | + // Decrypt SSH key |
| 44 | + let sshKey: string |
| 45 | + try { |
| 46 | + sshKey = decrypt(server.sshKeyEncrypted, server.sshKeyIv, server.sshKeyTag) |
| 47 | + } catch { |
| 48 | + return NextResponse.json({ error: 'Failed to decrypt SSH key' }, { status: 500 }) |
| 49 | + } |
| 50 | + |
| 51 | + // Reset failed and subsequent steps to pending |
| 52 | + for (let i = failedIndex; i < steps.length; i++) { |
| 53 | + steps[i] = { id: steps[i]!.id, status: 'pending' } |
| 54 | + } |
| 55 | + |
| 56 | + await db |
| 57 | + .update(adminServers) |
| 58 | + .set({ |
| 59 | + provisionStatus: 'provisioning', |
| 60 | + provisionStep: PROVISION_STEPS[failedIndex]!.id, |
| 61 | + provisionSteps: steps, |
| 62 | + provisionError: null, |
| 63 | + updatedAt: new Date(), |
| 64 | + }) |
| 65 | + .where(eq(adminServers.id, serverIdBuf)) |
| 66 | + |
| 67 | + // Run remaining steps in background |
| 68 | + retryProvisioning(serverId, server.ip, server.sshPort, server.sshUser, sshKey, steps, failedIndex).catch( |
| 69 | + () => {}, |
| 70 | + ) |
| 71 | + |
| 72 | + return NextResponse.json({ status: 'provisioning', retry_from: PROVISION_STEPS[failedIndex]!.id }) |
| 73 | +} |
| 74 | + |
| 75 | +async function retryProvisioning( |
| 76 | + serverId: string, |
| 77 | + ip: string, |
| 78 | + port: number, |
| 79 | + username: string, |
| 80 | + privateKey: string, |
| 81 | + stepResults: StepResult[], |
| 82 | + startIndex: number, |
| 83 | +) { |
| 84 | + const db = getDb() |
| 85 | + const serverIdBuf = Buffer.from(serverId, 'hex') as unknown as Uint8Array |
| 86 | + |
| 87 | + let conn |
| 88 | + try { |
| 89 | + conn = await createSshConnection({ host: ip, port, username, privateKey }) |
| 90 | + } catch (err) { |
| 91 | + await db |
| 92 | + .update(adminServers) |
| 93 | + .set({ |
| 94 | + provisionStatus: 'failed', |
| 95 | + provisionError: `SSH connection failed: ${err instanceof Error ? err.message : String(err)}`, |
| 96 | + updatedAt: new Date(), |
| 97 | + }) |
| 98 | + .where(eq(adminServers.id, serverIdBuf)) |
| 99 | + return |
| 100 | + } |
| 101 | + |
| 102 | + for (let i = startIndex; i < PROVISION_STEPS.length; i++) { |
| 103 | + const step = PROVISION_STEPS[i]! |
| 104 | + |
| 105 | + stepResults[i] = { id: step.id, status: 'running' } |
| 106 | + await db |
| 107 | + .update(adminServers) |
| 108 | + .set({ |
| 109 | + provisionStep: step.id, |
| 110 | + provisionSteps: [...stepResults], |
| 111 | + updatedAt: new Date(), |
| 112 | + }) |
| 113 | + .where(eq(adminServers.id, serverIdBuf)) |
| 114 | + |
| 115 | + const fullCommand = step.commands.join(' && ') |
| 116 | + |
| 117 | + try { |
| 118 | + const result = await execCommand(conn, fullCommand) |
| 119 | + const output = result.stdout + (result.stderr ? `\n${result.stderr}` : '') |
| 120 | + |
| 121 | + if (result.code !== 0) { |
| 122 | + stepResults[i] = { id: step.id, status: 'failed', output: output.trim() } |
| 123 | + await db |
| 124 | + .update(adminServers) |
| 125 | + .set({ |
| 126 | + provisionStatus: 'failed', |
| 127 | + provisionStep: step.id, |
| 128 | + provisionSteps: [...stepResults], |
| 129 | + provisionError: `Step "${step.name}" failed with exit code ${result.code}`, |
| 130 | + updatedAt: new Date(), |
| 131 | + }) |
| 132 | + .where(eq(adminServers.id, serverIdBuf)) |
| 133 | + conn.end() |
| 134 | + return |
| 135 | + } |
| 136 | + |
| 137 | + let fullOutput = output |
| 138 | + if (step.validate) { |
| 139 | + const valResult = await execCommand(conn, step.validate) |
| 140 | + if (valResult.code !== 0) { |
| 141 | + stepResults[i] = { id: step.id, status: 'failed', output: `Validation failed: ${valResult.stderr || valResult.stdout}`.trim() } |
| 142 | + await db |
| 143 | + .update(adminServers) |
| 144 | + .set({ |
| 145 | + provisionStatus: 'failed', |
| 146 | + provisionStep: step.id, |
| 147 | + provisionSteps: [...stepResults], |
| 148 | + provisionError: `Validation for "${step.name}" failed`, |
| 149 | + updatedAt: new Date(), |
| 150 | + }) |
| 151 | + .where(eq(adminServers.id, serverIdBuf)) |
| 152 | + conn.end() |
| 153 | + return |
| 154 | + } |
| 155 | + fullOutput += `\nValidation: ${valResult.stdout.trim()}` |
| 156 | + } |
| 157 | + |
| 158 | + stepResults[i] = { id: step.id, status: 'completed', output: fullOutput.trim() } |
| 159 | + } catch (err) { |
| 160 | + stepResults[i] = { id: step.id, status: 'failed', output: `Error: ${err instanceof Error ? err.message : String(err)}` } |
| 161 | + await db |
| 162 | + .update(adminServers) |
| 163 | + .set({ |
| 164 | + provisionStatus: 'failed', |
| 165 | + provisionStep: step.id, |
| 166 | + provisionSteps: [...stepResults], |
| 167 | + provisionError: `Step "${step.name}" threw: ${err instanceof Error ? err.message : String(err)}`, |
| 168 | + updatedAt: new Date(), |
| 169 | + }) |
| 170 | + .where(eq(adminServers.id, serverIdBuf)) |
| 171 | + conn.end() |
| 172 | + return |
| 173 | + } |
| 174 | + |
| 175 | + await db |
| 176 | + .update(adminServers) |
| 177 | + .set({ |
| 178 | + provisionSteps: [...stepResults], |
| 179 | + updatedAt: new Date(), |
| 180 | + }) |
| 181 | + .where(eq(adminServers.id, serverIdBuf)) |
| 182 | + } |
| 183 | + |
| 184 | + conn.end() |
| 185 | + await db |
| 186 | + .update(adminServers) |
| 187 | + .set({ |
| 188 | + provisionStatus: 'completed', |
| 189 | + provisionSteps: [...stepResults], |
| 190 | + updatedAt: new Date(), |
| 191 | + }) |
| 192 | + .where(eq(adminServers.id, serverIdBuf)) |
| 193 | +} |
0 commit comments