| 10943a1 | | | 1 | import { spawn, execFileSync } from "child_process"; |
| 10943a1 | | | 2 | import { mkdirSync, rmSync } from "fs"; |
| 80fafdf | | | 3 | import { |
| 80fafdf | | | 4 | createCipheriv, |
| 80fafdf | | | 5 | createDecipheriv, |
| 80fafdf | | | 6 | randomBytes, |
| 80fafdf | | | 7 | createHash, |
| 80fafdf | | | 8 | } from "crypto"; |
| 80fafdf | | | 9 | import type Database from "better-sqlite3"; |
| 80fafdf | | | 10 | import { parse as parseYaml } from "yaml"; |
| 80fafdf | | | 11 | import { minimatch } from "minimatch"; |
| 5bcd5db | | | 12 | import type { CanopyEventBus } from "./canopy-events.js"; |
| 80fafdf | | | 13 | |
| 80fafdf | | | 14 | interface PipelineConfig { |
| 80fafdf | | | 15 | name: string; |
| 80fafdf | | | 16 | on: { |
| 80fafdf | | | 17 | push?: { branches?: string[]; paths?: string[] }; |
| 80fafdf | | | 18 | }; |
| f60476c | | | 19 | checkout?: boolean; |
| 409bc79 | | | 20 | concurrency?: number; |
| 409bc79 | | | 21 | order?: number; |
| 80fafdf | | | 22 | env?: Record<string, string>; |
| 80fafdf | | | 23 | steps: StepConfig[]; |
| 80fafdf | | | 24 | } |
| 80fafdf | | | 25 | |
| 80fafdf | | | 26 | interface StepConfig { |
| 80fafdf | | | 27 | name: string; |
| 80fafdf | | | 28 | image: string; |
| 80fafdf | | | 29 | run: string; |
| 80fafdf | | | 30 | env?: Record<string, string>; |
| 80fafdf | | | 31 | timeout?: number; |
| 7422c65 | | | 32 | volumes?: string[]; |
| 80fafdf | | | 33 | } |
| 80fafdf | | | 34 | |
| 80fafdf | | | 35 | export interface PushEvent { |
| 80fafdf | | | 36 | repo: string; |
| 80fafdf | | | 37 | branch: string; |
| 80fafdf | | | 38 | oldCommitId: string; |
| 80fafdf | | | 39 | newCommitId: string; |
| 80fafdf | | | 40 | } |
| 80fafdf | | | 41 | |
| 80fafdf | | | 42 | export class CanopyRunner { |
| 80fafdf | | | 43 | private running = new Map<number, AbortController>(); |
| 80fafdf | | | 44 | |
| 80fafdf | | | 45 | constructor( |
| 80fafdf | | | 46 | private db: Database.Database, |
| 80fafdf | | | 47 | private bridgeUrl: string, |
| 80fafdf | | | 48 | private workspaceDir: string, |
| 1e64dbc | | | 49 | private workspaceHostDir: string, |
| 80fafdf | | | 50 | private jwtSecret: string, |
| 5bcd5db | | | 51 | private logger: { info: (...args: any[]) => void; error: (...args: any[]) => void }, |
| 5bcd5db | | | 52 | private eventBus?: CanopyEventBus |
| 80fafdf | | | 53 | ) { |
| 80fafdf | | | 54 | mkdirSync(workspaceDir, { recursive: true }); |
| 7422c65 | | | 55 | this.recoverOrphanedRuns(); |
| 7422c65 | | | 56 | } |
| 7422c65 | | | 57 | |
| 7422c65 | | | 58 | /** |
| 7422c65 | | | 59 | * On startup, mark any "running" pipeline runs/steps as failed. |
| 7422c65 | | | 60 | * These are orphans from a previous process crash (e.g. deploy step |
| 7422c65 | | | 61 | * restarted grove-api before the callback could fire). |
| 7422c65 | | | 62 | */ |
| 7422c65 | | | 63 | private recoverOrphanedRuns(): void { |
| 7422c65 | | | 64 | const steps = this.db |
| 7422c65 | | | 65 | .prepare( |
| 7422c65 | | | 66 | `UPDATE pipeline_steps SET status = 'failed', finished_at = datetime('now') WHERE status = 'running'` |
| 7422c65 | | | 67 | ) |
| 7422c65 | | | 68 | .run(); |
| 7422c65 | | | 69 | const runs = this.db |
| 7422c65 | | | 70 | .prepare( |
| 7422c65 | | | 71 | `UPDATE pipeline_runs SET status = 'failed', finished_at = datetime('now') WHERE status = 'running'` |
| 7422c65 | | | 72 | ) |
| 7422c65 | | | 73 | .run(); |
| 7422c65 | | | 74 | if (steps.changes > 0 || runs.changes > 0) { |
| 7422c65 | | | 75 | this.logger.info( |
| 7422c65 | | | 76 | `Recovered ${runs.changes} orphaned pipeline run(s), ${steps.changes} step(s)` |
| 7422c65 | | | 77 | ); |
| 7422c65 | | | 78 | } |
| 80fafdf | | | 79 | } |
| 80fafdf | | | 80 | |
| 5bcd5db | | | 81 | private getRunRow(runId: number): Record<string, unknown> | undefined { |
| 5bcd5db | | | 82 | return this.db.prepare(`SELECT * FROM pipeline_runs WHERE id = ?`).get(runId) as any; |
| 5bcd5db | | | 83 | } |
| 5bcd5db | | | 84 | |
| 5bcd5db | | | 85 | private getStepRow(stepId: number): Record<string, unknown> | undefined { |
| 5bcd5db | | | 86 | return this.db.prepare(`SELECT * FROM pipeline_steps WHERE id = ?`).get(stepId) as any; |
| 5bcd5db | | | 87 | } |
| 5bcd5db | | | 88 | |
| 791afd4 | | | 89 | private ensureRepo(repoName: string): number | null { |
| 791afd4 | | | 90 | const existing = this.db |
| 791afd4 | | | 91 | .prepare(`SELECT id FROM repos WHERE name = ?`) |
| 791afd4 | | | 92 | .get(repoName) as any; |
| 791afd4 | | | 93 | if (existing) return existing.id; |
| 791afd4 | | | 94 | |
| 791afd4 | | | 95 | try { |
| 791afd4 | | | 96 | // Ensure a placeholder user exists for FK constraint |
| 791afd4 | | | 97 | this.db |
| 791afd4 | | | 98 | .prepare( |
| 791afd4 | | | 99 | `INSERT OR IGNORE INTO users (id, username, display_name) VALUES (0, '_system', 'System')` |
| 791afd4 | | | 100 | ) |
| 791afd4 | | | 101 | .run(); |
| 791afd4 | | | 102 | const result = this.db |
| 791afd4 | | | 103 | .prepare(`INSERT INTO repos (name, owner_id) VALUES (?, 0)`) |
| 791afd4 | | | 104 | .run(repoName); |
| 791afd4 | | | 105 | return Number(result.lastInsertRowid); |
| 791afd4 | | | 106 | } catch { |
| 791afd4 | | | 107 | return null; |
| 791afd4 | | | 108 | } |
| 791afd4 | | | 109 | } |
| 791afd4 | | | 110 | |
| 37f6938 | | | 111 | private ensurePipeline(repoId: number, name: string, file: string): number { |
| 37f6938 | | | 112 | const existing = this.db |
| 37f6938 | | | 113 | .prepare(`SELECT id FROM pipelines WHERE repo_id = ? AND name = ?`) |
| 37f6938 | | | 114 | .get(repoId, name) as any; |
| 37f6938 | | | 115 | if (existing) { |
| 37f6938 | | | 116 | this.db |
| 37f6938 | | | 117 | .prepare(`UPDATE pipelines SET file = ? WHERE id = ?`) |
| 37f6938 | | | 118 | .run(file, existing.id); |
| 37f6938 | | | 119 | return existing.id; |
| 37f6938 | | | 120 | } |
| 37f6938 | | | 121 | const result = this.db |
| 37f6938 | | | 122 | .prepare(`INSERT INTO pipelines (repo_id, name, file) VALUES (?, ?, ?)`) |
| 37f6938 | | | 123 | .run(repoId, name, file); |
| 37f6938 | | | 124 | return Number(result.lastInsertRowid); |
| 37f6938 | | | 125 | } |
| 37f6938 | | | 126 | |
| 191af2a | | | 127 | async onPush(event: PushEvent, pipelineFilter?: string): Promise<void> { |
| 791afd4 | | | 128 | const repoId = this.ensureRepo(event.repo); |
| 791afd4 | | | 129 | if (!repoId) return; |
| 80fafdf | | | 130 | |
| 791afd4 | | | 131 | const configs = await this.readPipelineConfigs(event.repo, event.branch); |
| 80fafdf | | | 132 | if (configs.length === 0) return; |
| 80fafdf | | | 133 | |
| 80fafdf | | | 134 | let changedFiles: string[] | null = null; |
| 80fafdf | | | 135 | if (event.oldCommitId && event.oldCommitId !== event.newCommitId) { |
| 80fafdf | | | 136 | changedFiles = await this.getChangedFiles( |
| 80fafdf | | | 137 | event.repo, |
| 80fafdf | | | 138 | event.oldCommitId, |
| 80fafdf | | | 139 | event.newCommitId |
| 80fafdf | | | 140 | ); |
| 80fafdf | | | 141 | } |
| 80fafdf | | | 142 | |
| 818dc90 | | | 143 | // Fetch commit message from bridge |
| 818dc90 | | | 144 | const commitMessage = await this.getCommitMessage(event.repo, event.newCommitId); |
| 818dc90 | | | 145 | |
| 409bc79 | | | 146 | const matched = configs |
| d948b49 | | | 147 | .filter(({ file, config }) => this.matchesTrigger(config, file, event.branch, changedFiles)) |
| 191af2a | | | 148 | .filter(({ config }) => !pipelineFilter || config.name === pipelineFilter) |
| 409bc79 | | | 149 | .sort((a, b) => (a.config.order ?? 0) - (b.config.order ?? 0)); |
| c98936c | | | 150 | if (matched.length === 0) return; |
| 409bc79 | | | 151 | |
| c98936c | | | 152 | type QueuedRun = { |
| c98936c | | | 153 | order: number; |
| c98936c | | | 154 | runId: number; |
| c98936c | | | 155 | config: PipelineConfig; |
| c98936c | | | 156 | }; |
| 409bc79 | | | 157 | |
| c98936c | | | 158 | const queuedRuns: QueuedRun[] = []; |
| c98936c | | | 159 | for (const { file, config } of matched) { |
| c98936c | | | 160 | // Cancel in-progress runs of this pipeline if concurrency is limited |
| c98936c | | | 161 | if (config.concurrency != null && config.concurrency >= 1) { |
| c98936c | | | 162 | const pipelineId = this.ensurePipeline(repoId, config.name, file); |
| c98936c | | | 163 | const active = this.db |
| c98936c | | | 164 | .prepare( |
| c98936c | | | 165 | `SELECT id FROM pipeline_runs |
| c98936c | | | 166 | WHERE pipeline_id = ? AND status IN ('pending', 'running') |
| c98936c | | | 167 | ORDER BY id` |
| c98936c | | | 168 | ) |
| c98936c | | | 169 | .all(pipelineId) as any[]; |
| 603c6c9 | | | 170 | |
| c98936c | | | 171 | const toCancel = active.slice(0, Math.max(0, active.length - config.concurrency + 1)); |
| c98936c | | | 172 | for (const row of toCancel) { |
| c98936c | | | 173 | this.cancelRun(row.id); |
| c98936c | | | 174 | this.db |
| 409bc79 | | | 175 | .prepare( |
| c98936c | | | 176 | `UPDATE pipeline_runs SET status = 'cancelled', finished_at = datetime('now') WHERE id = ? AND status IN ('pending', 'running')` |
| 409bc79 | | | 177 | ) |
| c98936c | | | 178 | .run(row.id); |
| c98936c | | | 179 | this.db |
| c98936c | | | 180 | .prepare( |
| c98936c | | | 181 | `UPDATE pipeline_steps SET status = 'skipped' WHERE run_id = ? AND status IN ('pending', 'running')` |
| c98936c | | | 182 | ) |
| c98936c | | | 183 | .run(row.id); |
| 5bcd5db | | | 184 | this.eventBus?.publish({ |
| 5bcd5db | | | 185 | type: "run:cancelled", |
| 5bcd5db | | | 186 | runId: row.id, |
| 5bcd5db | | | 187 | repoId, |
| 5bcd5db | | | 188 | status: "cancelled", |
| 5bcd5db | | | 189 | run: this.getRunRow(row.id), |
| 5bcd5db | | | 190 | ts: new Date().toISOString(), |
| 5bcd5db | | | 191 | }); |
| 409bc79 | | | 192 | } |
| c98936c | | | 193 | } |
| 80fafdf | | | 194 | |
| c98936c | | | 195 | const runId = this.createRun( |
| c98936c | | | 196 | repoId, |
| c98936c | | | 197 | config.name, |
| c98936c | | | 198 | file, |
| c98936c | | | 199 | "push", |
| c98936c | | | 200 | event.branch, |
| c98936c | | | 201 | event.newCommitId, |
| c98936c | | | 202 | commitMessage, |
| c98936c | | | 203 | config.steps |
| c98936c | | | 204 | ); |
| c98936c | | | 205 | queuedRuns.push({ order: config.order ?? 0, runId, config }); |
| c98936c | | | 206 | } |
| c98936c | | | 207 | |
| c98936c | | | 208 | // Execute queued runs in the background so push handling can return quickly. |
| c98936c | | | 209 | // Order groups are still respected: same order runs in parallel, higher orders |
| c98936c | | | 210 | // wait for lower-order groups to finish. |
| c98936c | | | 211 | void (async () => { |
| c98936c | | | 212 | const groups = new Map<number, QueuedRun[]>(); |
| c98936c | | | 213 | for (const run of queuedRuns) { |
| c98936c | | | 214 | if (!groups.has(run.order)) groups.set(run.order, []); |
| c98936c | | | 215 | groups.get(run.order)!.push(run); |
| c98936c | | | 216 | } |
| 80fafdf | | | 217 | |
| c98936c | | | 218 | for (const [, group] of [...groups.entries()].sort(([a], [b]) => a - b)) { |
| c98936c | | | 219 | await Promise.all( |
| c98936c | | | 220 | group.map((run) => |
| c98936c | | | 221 | this.executePipeline(run.runId, run.config, event.repo, event.branch).catch( |
| c98936c | | | 222 | (err) => this.logger.error({ err, runId: run.runId }, "Pipeline execution failed") |
| c98936c | | | 223 | ) |
| 603c6c9 | | | 224 | ) |
| 603c6c9 | | | 225 | ); |
| 603c6c9 | | | 226 | } |
| c98936c | | | 227 | })().catch((err) => |
| c98936c | | | 228 | this.logger.error( |
| c98936c | | | 229 | { err, repo: event.repo, branch: event.branch, commit: event.newCommitId }, |
| c98936c | | | 230 | "Queued push execution failed" |
| c98936c | | | 231 | ) |
| c98936c | | | 232 | ); |
| 80fafdf | | | 233 | } |
| 80fafdf | | | 234 | |
| 818dc90 | | | 235 | private async getCommitMessage(repo: string, commitId: string): Promise<string | null> { |
| 818dc90 | | | 236 | try { |
| 818dc90 | | | 237 | const res = await fetch( |
| 818dc90 | | | 238 | `${this.bridgeUrl}/repos/${repo}/commit/${commitId}/history?limit=1` |
| 818dc90 | | | 239 | ); |
| 818dc90 | | | 240 | if (!res.ok) return null; |
| 818dc90 | | | 241 | const data = await res.json(); |
| 818dc90 | | | 242 | const commit = data.commits?.[0]; |
| 818dc90 | | | 243 | if (!commit?.message) return null; |
| 818dc90 | | | 244 | return commit.message.split("\n")[0]; |
| 818dc90 | | | 245 | } catch { |
| 818dc90 | | | 246 | return null; |
| 818dc90 | | | 247 | } |
| 818dc90 | | | 248 | } |
| 818dc90 | | | 249 | |
| 80fafdf | | | 250 | // --- Pipeline config reading --- |
| 80fafdf | | | 251 | |
| 80fafdf | | | 252 | private async readPipelineConfigs( |
| 80fafdf | | | 253 | repo: string, |
| 791afd4 | | | 254 | ref: string |
| 80fafdf | | | 255 | ): Promise<Array<{ file: string; config: PipelineConfig }>> { |
| 80fafdf | | | 256 | try { |
| 80fafdf | | | 257 | const treeRes = await fetch( |
| 791afd4 | | | 258 | `${this.bridgeUrl}/repos/${repo}/tree/${ref}/.canopy` |
| 80fafdf | | | 259 | ); |
| 80fafdf | | | 260 | if (!treeRes.ok) return []; |
| 80fafdf | | | 261 | const tree = await treeRes.json(); |
| 80fafdf | | | 262 | |
| 80fafdf | | | 263 | const results: Array<{ file: string; config: PipelineConfig }> = []; |
| 80fafdf | | | 264 | for (const entry of tree.entries) { |
| 80fafdf | | | 265 | if (!entry.name.endsWith(".yml") && !entry.name.endsWith(".yaml")) |
| 80fafdf | | | 266 | continue; |
| 80fafdf | | | 267 | |
| 80fafdf | | | 268 | const blobRes = await fetch( |
| 791afd4 | | | 269 | `${this.bridgeUrl}/repos/${repo}/blob/${ref}/.canopy/${entry.name}` |
| 80fafdf | | | 270 | ); |
| 80fafdf | | | 271 | if (!blobRes.ok) continue; |
| 80fafdf | | | 272 | const blob = await blobRes.json(); |
| 80fafdf | | | 273 | |
| 80fafdf | | | 274 | try { |
| 80fafdf | | | 275 | const config = parseYaml(blob.content) as PipelineConfig; |
| 80fafdf | | | 276 | if (config.name && config.on && config.steps) { |
| 80fafdf | | | 277 | results.push({ file: `.canopy/${entry.name}`, config }); |
| 80fafdf | | | 278 | } |
| 80fafdf | | | 279 | } catch { |
| 80fafdf | | | 280 | /* invalid YAML, skip */ |
| 80fafdf | | | 281 | } |
| 80fafdf | | | 282 | } |
| 80fafdf | | | 283 | return results; |
| 80fafdf | | | 284 | } catch { |
| 80fafdf | | | 285 | return []; |
| 80fafdf | | | 286 | } |
| 80fafdf | | | 287 | } |
| 80fafdf | | | 288 | |
| 80fafdf | | | 289 | // --- Trigger matching --- |
| 80fafdf | | | 290 | |
| 80fafdf | | | 291 | private matchesTrigger( |
| 80fafdf | | | 292 | config: PipelineConfig, |
| d948b49 | | | 293 | file: string, |
| 80fafdf | | | 294 | branch: string, |
| 80fafdf | | | 295 | changedFiles: string[] | null |
| 80fafdf | | | 296 | ): boolean { |
| 80fafdf | | | 297 | const push = config.on.push; |
| 80fafdf | | | 298 | if (!push) return false; |
| 80fafdf | | | 299 | |
| 80fafdf | | | 300 | if (push.branches && push.branches.length > 0) { |
| 80fafdf | | | 301 | const branchMatches = push.branches.some((pattern) => |
| 80fafdf | | | 302 | minimatch(branch, pattern) |
| 80fafdf | | | 303 | ); |
| 80fafdf | | | 304 | if (!branchMatches) return false; |
| 80fafdf | | | 305 | } |
| 80fafdf | | | 306 | |
| 80fafdf | | | 307 | if (push.paths && push.paths.length > 0 && changedFiles !== null) { |
| d948b49 | | | 308 | // Always trigger if the pipeline's own config file was changed |
| d948b49 | | | 309 | const selfChanged = changedFiles.includes(file); |
| d948b49 | | | 310 | if (!selfChanged) { |
| d948b49 | | | 311 | const anyPathMatches = changedFiles.some((f) => |
| d948b49 | | | 312 | push.paths!.some((pattern) => minimatch(f, pattern)) |
| d948b49 | | | 313 | ); |
| d948b49 | | | 314 | if (!anyPathMatches) return false; |
| d948b49 | | | 315 | } |
| 80fafdf | | | 316 | } |
| 80fafdf | | | 317 | |
| 80fafdf | | | 318 | return true; |
| 80fafdf | | | 319 | } |
| 80fafdf | | | 320 | |
| 80fafdf | | | 321 | private async getChangedFiles( |
| 80fafdf | | | 322 | repo: string, |
| 80fafdf | | | 323 | oldId: string, |
| 80fafdf | | | 324 | newId: string |
| 791afd4 | | | 325 | ): Promise<string[] | null> { |
| 80fafdf | | | 326 | try { |
| 80fafdf | | | 327 | const diffRes = await fetch( |
| 80fafdf | | | 328 | `${this.bridgeUrl}/repos/${repo}/diff/${oldId}/${newId}` |
| 80fafdf | | | 329 | ); |
| 791afd4 | | | 330 | if (!diffRes.ok) return null; |
| 80fafdf | | | 331 | const data = await diffRes.json(); |
| 80fafdf | | | 332 | return (data.diffs || []).map((d: any) => d.path); |
| 80fafdf | | | 333 | } catch { |
| 791afd4 | | | 334 | return null; |
| 80fafdf | | | 335 | } |
| 80fafdf | | | 336 | } |
| 80fafdf | | | 337 | |
| 791afd4 | | | 338 | // --- Source checkout via grove-bridge API --- |
| 791afd4 | | | 339 | |
| 791afd4 | | | 340 | private async checkoutFromBridge( |
| 791afd4 | | | 341 | repo: string, |
| 791afd4 | | | 342 | ref: string, |
| 791afd4 | | | 343 | destPath: string |
| 791afd4 | | | 344 | ): Promise<void> { |
| 10943a1 | | | 345 | const url = `${this.bridgeUrl}/repos/${repo}/archive/${ref}`; |
| 10943a1 | | | 346 | const res = await fetch(url); |
| 10943a1 | | | 347 | if (!res.ok) { |
| 10943a1 | | | 348 | throw new Error(`Archive fetch failed: ${res.status} ${res.statusText}`); |
| 10943a1 | | | 349 | } |
| 791afd4 | | | 350 | |
| 10943a1 | | | 351 | mkdirSync(destPath, { recursive: true }); |
| 791afd4 | | | 352 | |
| 10943a1 | | | 353 | const tarData = Buffer.from(await res.arrayBuffer()); |
| 10943a1 | | | 354 | execFileSync("tar", ["xf", "-", "-C", destPath], { input: tarData }); |
| 791afd4 | | | 355 | } |
| 791afd4 | | | 356 | |
| 80fafdf | | | 357 | // --- Run/step record creation --- |
| 80fafdf | | | 358 | |
| 80fafdf | | | 359 | private createRun( |
| 80fafdf | | | 360 | repoId: number, |
| 80fafdf | | | 361 | pipelineName: string, |
| 80fafdf | | | 362 | pipelineFile: string, |
| 80fafdf | | | 363 | triggerType: string, |
| 80fafdf | | | 364 | triggerRef: string, |
| 80fafdf | | | 365 | commitId: string, |
| 818dc90 | | | 366 | commitMessage: string | null, |
| 80fafdf | | | 367 | steps: StepConfig[] |
| 80fafdf | | | 368 | ): number { |
| 37f6938 | | | 369 | const pipelineId = this.ensurePipeline(repoId, pipelineName, pipelineFile); |
| 37f6938 | | | 370 | |
| 80fafdf | | | 371 | const result = this.db |
| 80fafdf | | | 372 | .prepare( |
| 37f6938 | | | 373 | `INSERT INTO pipeline_runs (pipeline_id, repo_id, pipeline_name, pipeline_file, trigger_type, trigger_ref, commit_id, commit_message, status) |
| 37f6938 | | | 374 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')` |
| 80fafdf | | | 375 | ) |
| 37f6938 | | | 376 | .run(pipelineId, repoId, pipelineName, pipelineFile, triggerType, triggerRef, commitId, commitMessage); |
| 80fafdf | | | 377 | |
| 80fafdf | | | 378 | const runId = Number(result.lastInsertRowid); |
| 80fafdf | | | 379 | |
| 80fafdf | | | 380 | const insertStep = this.db.prepare( |
| 80fafdf | | | 381 | `INSERT INTO pipeline_steps (run_id, step_index, name, image, status) |
| 80fafdf | | | 382 | VALUES (?, ?, ?, ?, 'pending')` |
| 80fafdf | | | 383 | ); |
| 80fafdf | | | 384 | |
| 80fafdf | | | 385 | for (let i = 0; i < steps.length; i++) { |
| 80fafdf | | | 386 | insertStep.run(runId, i, steps[i].name, steps[i].image); |
| 80fafdf | | | 387 | } |
| 80fafdf | | | 388 | |
| 5bcd5db | | | 389 | this.eventBus?.publish({ |
| 5bcd5db | | | 390 | type: "run:created", |
| 5bcd5db | | | 391 | runId, |
| 5bcd5db | | | 392 | repoId, |
| 5bcd5db | | | 393 | status: "pending", |
| 5bcd5db | | | 394 | run: this.getRunRow(runId), |
| 5bcd5db | | | 395 | ts: new Date().toISOString(), |
| 5bcd5db | | | 396 | }); |
| 5bcd5db | | | 397 | |
| 80fafdf | | | 398 | return runId; |
| 80fafdf | | | 399 | } |
| 80fafdf | | | 400 | |
| 80fafdf | | | 401 | // --- Pipeline execution --- |
| 80fafdf | | | 402 | |
| 80fafdf | | | 403 | private async executePipeline( |
| 80fafdf | | | 404 | runId: number, |
| 80fafdf | | | 405 | config: PipelineConfig, |
| 80fafdf | | | 406 | repoName: string, |
| 791afd4 | | | 407 | ref: string |
| 80fafdf | | | 408 | ): Promise<void> { |
| 80fafdf | | | 409 | const abort = new AbortController(); |
| 80fafdf | | | 410 | this.running.set(runId, abort); |
| 80fafdf | | | 411 | |
| 5bcd5db | | | 412 | const repoRow = this.db |
| 5bcd5db | | | 413 | .prepare(`SELECT id FROM repos WHERE name = ?`) |
| 5bcd5db | | | 414 | .get(repoName) as any; |
| 5bcd5db | | | 415 | const repoId = repoRow?.id ?? 0; |
| 5bcd5db | | | 416 | |
| 80fafdf | | | 417 | this.db |
| 80fafdf | | | 418 | .prepare( |
| 80fafdf | | | 419 | `UPDATE pipeline_runs SET status = 'running', started_at = datetime('now') WHERE id = ?` |
| 80fafdf | | | 420 | ) |
| 80fafdf | | | 421 | .run(runId); |
| 80fafdf | | | 422 | |
| 5bcd5db | | | 423 | this.eventBus?.publish({ |
| 5bcd5db | | | 424 | type: "run:started", |
| 5bcd5db | | | 425 | runId, |
| 5bcd5db | | | 426 | repoId, |
| 5bcd5db | | | 427 | status: "running", |
| 5bcd5db | | | 428 | run: this.getRunRow(runId), |
| 5bcd5db | | | 429 | ts: new Date().toISOString(), |
| 5bcd5db | | | 430 | }); |
| 5bcd5db | | | 431 | |
| 80fafdf | | | 432 | const workspacePath = `${this.workspaceDir}/${runId}`; |
| 791afd4 | | | 433 | const srcPath = `${workspacePath}/src`; |
| 791afd4 | | | 434 | mkdirSync(srcPath, { recursive: true }); |
| 80fafdf | | | 435 | |
| f60476c | | | 436 | if (config.checkout !== false) { |
| f60476c | | | 437 | try { |
| f60476c | | | 438 | await this.checkoutFromBridge(repoName, ref, srcPath); |
| f60476c | | | 439 | } catch (err) { |
| f60476c | | | 440 | this.logger.error({ err, runId }, "Failed to checkout repo for pipeline"); |
| f60476c | | | 441 | this.db |
| f60476c | | | 442 | .prepare( |
| f60476c | | | 443 | `UPDATE pipeline_runs SET status = 'failed', finished_at = datetime('now') WHERE id = ?` |
| f60476c | | | 444 | ) |
| f60476c | | | 445 | .run(runId); |
| 5bcd5db | | | 446 | this.eventBus?.publish({ |
| 5bcd5db | | | 447 | type: "run:completed", |
| 5bcd5db | | | 448 | runId, |
| 5bcd5db | | | 449 | repoId, |
| 5bcd5db | | | 450 | status: "failed", |
| 5bcd5db | | | 451 | run: this.getRunRow(runId), |
| 5bcd5db | | | 452 | ts: new Date().toISOString(), |
| 5bcd5db | | | 453 | }); |
| f60476c | | | 454 | this.running.delete(runId); |
| f60476c | | | 455 | return; |
| f60476c | | | 456 | } |
| 80fafdf | | | 457 | } |
| 80fafdf | | | 458 | |
| 80fafdf | | | 459 | const secrets = repoRow ? this.loadSecrets(repoRow.id) : {}; |
| 80fafdf | | | 460 | |
| 80fafdf | | | 461 | const steps = this.db |
| 80fafdf | | | 462 | .prepare( |
| 80fafdf | | | 463 | `SELECT * FROM pipeline_steps WHERE run_id = ? ORDER BY step_index` |
| 80fafdf | | | 464 | ) |
| 80fafdf | | | 465 | .all(runId) as any[]; |
| 80fafdf | | | 466 | let allPassed = true; |
| 80fafdf | | | 467 | |
| 80fafdf | | | 468 | for (const step of steps) { |
| 80fafdf | | | 469 | if (abort.signal.aborted || !allPassed) { |
| 80fafdf | | | 470 | this.db |
| 80fafdf | | | 471 | .prepare(`UPDATE pipeline_steps SET status = 'skipped' WHERE id = ?`) |
| 80fafdf | | | 472 | .run(step.id); |
| 5bcd5db | | | 473 | this.eventBus?.publish({ |
| 5bcd5db | | | 474 | type: "step:skipped", |
| 5bcd5db | | | 475 | runId, |
| 5bcd5db | | | 476 | repoId, |
| 5bcd5db | | | 477 | stepId: step.id, |
| 5bcd5db | | | 478 | stepIndex: step.step_index, |
| 5bcd5db | | | 479 | status: "skipped", |
| 5bcd5db | | | 480 | step: this.getStepRow(step.id), |
| 5bcd5db | | | 481 | ts: new Date().toISOString(), |
| 5bcd5db | | | 482 | }); |
| 80fafdf | | | 483 | continue; |
| 80fafdf | | | 484 | } |
| 80fafdf | | | 485 | |
| 80fafdf | | | 486 | const stepConfig = config.steps[step.step_index]; |
| 80fafdf | | | 487 | const mergedEnv = { ...config.env, ...stepConfig.env }; |
| 80fafdf | | | 488 | const resolvedEnv = this.resolveSecrets(mergedEnv, secrets); |
| 80fafdf | | | 489 | |
| 80fafdf | | | 490 | const passed = await this.executeStep( |
| 5bcd5db | | | 491 | runId, |
| 5bcd5db | | | 492 | repoId, |
| 80fafdf | | | 493 | step.id, |
| 5bcd5db | | | 494 | step.step_index, |
| 80fafdf | | | 495 | stepConfig, |
| 80fafdf | | | 496 | resolvedEnv, |
| 80fafdf | | | 497 | `${workspacePath}/src`, |
| 80fafdf | | | 498 | abort.signal |
| 80fafdf | | | 499 | ); |
| 80fafdf | | | 500 | if (!passed) allPassed = false; |
| 80fafdf | | | 501 | } |
| 80fafdf | | | 502 | |
| 80fafdf | | | 503 | const run = this.db |
| 80fafdf | | | 504 | .prepare(`SELECT started_at FROM pipeline_runs WHERE id = ?`) |
| 80fafdf | | | 505 | .get(runId) as any; |
| 80fafdf | | | 506 | const durationMs = run?.started_at |
| 80fafdf | | | 507 | ? Date.now() - new Date(run.started_at + "Z").getTime() |
| 80fafdf | | | 508 | : 0; |
| 80fafdf | | | 509 | |
| 5bcd5db | | | 510 | const finalStatus = allPassed ? "passed" : "failed"; |
| 80fafdf | | | 511 | this.db |
| 80fafdf | | | 512 | .prepare( |
| 80fafdf | | | 513 | `UPDATE pipeline_runs SET status = ?, finished_at = datetime('now'), duration_ms = ? WHERE id = ?` |
| 80fafdf | | | 514 | ) |
| 5bcd5db | | | 515 | .run(finalStatus, durationMs, runId); |
| 5bcd5db | | | 516 | |
| 5bcd5db | | | 517 | this.eventBus?.publish({ |
| 5bcd5db | | | 518 | type: "run:completed", |
| 5bcd5db | | | 519 | runId, |
| 5bcd5db | | | 520 | repoId, |
| 5bcd5db | | | 521 | status: finalStatus, |
| 5bcd5db | | | 522 | run: this.getRunRow(runId), |
| 5bcd5db | | | 523 | ts: new Date().toISOString(), |
| 5bcd5db | | | 524 | }); |
| 80fafdf | | | 525 | |
| 80fafdf | | | 526 | try { |
| 80fafdf | | | 527 | rmSync(workspacePath, { recursive: true, force: true }); |
| 80fafdf | | | 528 | } catch {} |
| 80fafdf | | | 529 | this.running.delete(runId); |
| 80fafdf | | | 530 | } |
| 80fafdf | | | 531 | |
| 80fafdf | | | 532 | // --- Step execution (Docker container) --- |
| 80fafdf | | | 533 | |
| 1e64dbc | | | 534 | private toHostPath(containerPath: string): string { |
| 1e64dbc | | | 535 | if (containerPath.startsWith(this.workspaceDir)) { |
| 1e64dbc | | | 536 | return this.workspaceHostDir + containerPath.slice(this.workspaceDir.length); |
| 1e64dbc | | | 537 | } |
| 1e64dbc | | | 538 | return containerPath; |
| 1e64dbc | | | 539 | } |
| 1e64dbc | | | 540 | |
| 80fafdf | | | 541 | private executeStep( |
| 5bcd5db | | | 542 | runId: number, |
| 5bcd5db | | | 543 | repoId: number, |
| 80fafdf | | | 544 | stepId: number, |
| 5bcd5db | | | 545 | stepIndex: number, |
| 80fafdf | | | 546 | step: StepConfig, |
| 80fafdf | | | 547 | env: Record<string, string>, |
| 80fafdf | | | 548 | workspacePath: string, |
| 80fafdf | | | 549 | signal: AbortSignal |
| 80fafdf | | | 550 | ): Promise<boolean> { |
| 80fafdf | | | 551 | return new Promise((resolve) => { |
| 80fafdf | | | 552 | this.db |
| 80fafdf | | | 553 | .prepare( |
| 80fafdf | | | 554 | `UPDATE pipeline_steps SET status = 'running', started_at = datetime('now') WHERE id = ?` |
| 80fafdf | | | 555 | ) |
| 80fafdf | | | 556 | .run(stepId); |
| 80fafdf | | | 557 | |
| 5bcd5db | | | 558 | this.eventBus?.publish({ |
| 5bcd5db | | | 559 | type: "step:started", |
| 5bcd5db | | | 560 | runId, |
| 5bcd5db | | | 561 | repoId, |
| 5bcd5db | | | 562 | stepId, |
| 5bcd5db | | | 563 | stepIndex, |
| 5bcd5db | | | 564 | status: "running", |
| 5bcd5db | | | 565 | step: this.getStepRow(stepId), |
| 5bcd5db | | | 566 | ts: new Date().toISOString(), |
| 5bcd5db | | | 567 | }); |
| 5bcd5db | | | 568 | |
| 80fafdf | | | 569 | const timeout = (step.timeout ?? 600) * 1000; |
| 5f0fbcf | | | 570 | const envArgs = Object.entries({ |
| 5f0fbcf | | | 571 | GROVE_REGISTRY: "localhost:5000", |
| 5f0fbcf | | | 572 | ...env, |
| 5f0fbcf | | | 573 | }).flatMap(([k, v]) => ["-e", `${k}=${v}`]); |
| 80fafdf | | | 574 | |
| 1e64dbc | | | 575 | const hostWorkspacePath = this.toHostPath(workspacePath); |
| 1e64dbc | | | 576 | |
| 7422c65 | | | 577 | const volumeArgs = [ |
| 7422c65 | | | 578 | "-v", `${hostWorkspacePath}:/workspace`, |
| 7422c65 | | | 579 | "-v", "/var/run/docker.sock:/var/run/docker.sock", |
| 7422c65 | | | 580 | "-v", "/opt/grove:/opt/grove:ro", |
| 7422c65 | | | 581 | ...(step.volumes ?? []).flatMap((v) => ["-v", v]), |
| 7422c65 | | | 582 | ]; |
| 7422c65 | | | 583 | |
| 57c315f | | | 584 | const containerName = `canopy-${runId}-${stepIndex}`; |
| 80fafdf | | | 585 | const proc = spawn("docker", [ |
| 80fafdf | | | 586 | "run", |
| 80fafdf | | | 587 | "--rm", |
| 57c315f | | | 588 | "--name", |
| 57c315f | | | 589 | containerName, |
| 7422c65 | | | 590 | ...volumeArgs, |
| 80fafdf | | | 591 | "-w", |
| 80fafdf | | | 592 | "/workspace", |
| 80fafdf | | | 593 | "--network", |
| 80fafdf | | | 594 | "host", |
| 80fafdf | | | 595 | ...envArgs, |
| 80fafdf | | | 596 | step.image, |
| 80fafdf | | | 597 | "sh", |
| 00c0ecf | | | 598 | "-ec", |
| 80fafdf | | | 599 | step.run, |
| 80fafdf | | | 600 | ]); |
| 80fafdf | | | 601 | |
| 80fafdf | | | 602 | const insertLog = this.db.prepare( |
| 80fafdf | | | 603 | `INSERT INTO step_logs (step_id, stream, content) VALUES (?, ?, ?)` |
| 80fafdf | | | 604 | ); |
| 80fafdf | | | 605 | |
| 80fafdf | | | 606 | proc.stdout.on("data", (data: Buffer) => { |
| 5bcd5db | | | 607 | const content = data.toString(); |
| 5bcd5db | | | 608 | insertLog.run(stepId, "stdout", content); |
| 5bcd5db | | | 609 | this.eventBus?.publish({ |
| 5bcd5db | | | 610 | type: "log:append", |
| 5bcd5db | | | 611 | runId, |
| 5bcd5db | | | 612 | repoId, |
| 5bcd5db | | | 613 | stepId, |
| 5bcd5db | | | 614 | stepIndex, |
| 5bcd5db | | | 615 | log: { stream: "stdout", content, created_at: new Date().toISOString() }, |
| 5bcd5db | | | 616 | ts: new Date().toISOString(), |
| 5bcd5db | | | 617 | }); |
| 80fafdf | | | 618 | }); |
| 80fafdf | | | 619 | |
| 80fafdf | | | 620 | proc.stderr.on("data", (data: Buffer) => { |
| 5bcd5db | | | 621 | const content = data.toString(); |
| 5bcd5db | | | 622 | insertLog.run(stepId, "stderr", content); |
| 5bcd5db | | | 623 | this.eventBus?.publish({ |
| 5bcd5db | | | 624 | type: "log:append", |
| 5bcd5db | | | 625 | runId, |
| 5bcd5db | | | 626 | repoId, |
| 5bcd5db | | | 627 | stepId, |
| 5bcd5db | | | 628 | stepIndex, |
| 5bcd5db | | | 629 | log: { stream: "stderr", content, created_at: new Date().toISOString() }, |
| 5bcd5db | | | 630 | ts: new Date().toISOString(), |
| 5bcd5db | | | 631 | }); |
| 80fafdf | | | 632 | }); |
| 80fafdf | | | 633 | |
| 80fafdf | | | 634 | const timer = setTimeout(() => { |
| 80fafdf | | | 635 | proc.kill("SIGTERM"); |
| 80fafdf | | | 636 | insertLog.run( |
| 80fafdf | | | 637 | stepId, |
| 80fafdf | | | 638 | "stderr", |
| 80fafdf | | | 639 | `Step timed out after ${step.timeout ?? 600}s` |
| 80fafdf | | | 640 | ); |
| 80fafdf | | | 641 | }, timeout); |
| 80fafdf | | | 642 | |
| 80fafdf | | | 643 | const abortHandler = () => { |
| 57c315f | | | 644 | spawn("docker", ["kill", containerName]).on("close", () => { |
| 57c315f | | | 645 | proc.kill("SIGTERM"); |
| 57c315f | | | 646 | }); |
| 80fafdf | | | 647 | insertLog.run(stepId, "stderr", "Step cancelled"); |
| 80fafdf | | | 648 | }; |
| 80fafdf | | | 649 | signal.addEventListener("abort", abortHandler, { once: true }); |
| 80fafdf | | | 650 | |
| 80fafdf | | | 651 | proc.on("close", (code) => { |
| 80fafdf | | | 652 | clearTimeout(timer); |
| 80fafdf | | | 653 | signal.removeEventListener("abort", abortHandler); |
| 80fafdf | | | 654 | |
| 80fafdf | | | 655 | const startedAt = this.db |
| 80fafdf | | | 656 | .prepare(`SELECT started_at FROM pipeline_steps WHERE id = ?`) |
| 80fafdf | | | 657 | .get(stepId) as any; |
| 80fafdf | | | 658 | const durationMs = startedAt?.started_at |
| 80fafdf | | | 659 | ? Date.now() - new Date(startedAt.started_at + "Z").getTime() |
| 80fafdf | | | 660 | : 0; |
| 80fafdf | | | 661 | |
| 80fafdf | | | 662 | const passed = code === 0; |
| 5bcd5db | | | 663 | const stepStatus = passed ? "passed" : "failed"; |
| 80fafdf | | | 664 | this.db |
| 80fafdf | | | 665 | .prepare( |
| 80fafdf | | | 666 | `UPDATE pipeline_steps SET status = ?, exit_code = ?, finished_at = datetime('now'), duration_ms = ? WHERE id = ?` |
| 80fafdf | | | 667 | ) |
| 5bcd5db | | | 668 | .run(stepStatus, code, durationMs, stepId); |
| 5bcd5db | | | 669 | |
| 5bcd5db | | | 670 | this.eventBus?.publish({ |
| 5bcd5db | | | 671 | type: "step:completed", |
| 5bcd5db | | | 672 | runId, |
| 5bcd5db | | | 673 | repoId, |
| 5bcd5db | | | 674 | stepId, |
| 5bcd5db | | | 675 | stepIndex, |
| 5bcd5db | | | 676 | status: stepStatus, |
| 5bcd5db | | | 677 | step: this.getStepRow(stepId), |
| 5bcd5db | | | 678 | ts: new Date().toISOString(), |
| 5bcd5db | | | 679 | }); |
| 80fafdf | | | 680 | |
| 80fafdf | | | 681 | resolve(passed); |
| 80fafdf | | | 682 | }); |
| 80fafdf | | | 683 | }); |
| 80fafdf | | | 684 | } |
| 80fafdf | | | 685 | |
| 80fafdf | | | 686 | // --- Secrets --- |
| 80fafdf | | | 687 | |
| 80fafdf | | | 688 | private deriveKey(): Buffer { |
| 80fafdf | | | 689 | return createHash("sha256") |
| 80fafdf | | | 690 | .update(this.jwtSecret + ":canopy-secrets") |
| 80fafdf | | | 691 | .digest(); |
| 80fafdf | | | 692 | } |
| 80fafdf | | | 693 | |
| 80fafdf | | | 694 | encryptSecret(plaintext: string): string { |
| 80fafdf | | | 695 | const key = this.deriveKey(); |
| 80fafdf | | | 696 | const iv = randomBytes(12); |
| 80fafdf | | | 697 | const cipher = createCipheriv("aes-256-gcm", key, iv); |
| 80fafdf | | | 698 | const encrypted = Buffer.concat([ |
| 80fafdf | | | 699 | cipher.update(plaintext, "utf8"), |
| 80fafdf | | | 700 | cipher.final(), |
| 80fafdf | | | 701 | ]); |
| 80fafdf | | | 702 | const tag = cipher.getAuthTag(); |
| 80fafdf | | | 703 | return Buffer.concat([iv, tag, encrypted]).toString("base64"); |
| 80fafdf | | | 704 | } |
| 80fafdf | | | 705 | |
| 80fafdf | | | 706 | private decrypt(encoded: string): string { |
| 80fafdf | | | 707 | const key = this.deriveKey(); |
| 80fafdf | | | 708 | const buf = Buffer.from(encoded, "base64"); |
| 80fafdf | | | 709 | const iv = buf.subarray(0, 12); |
| 80fafdf | | | 710 | const tag = buf.subarray(12, 28); |
| 80fafdf | | | 711 | const data = buf.subarray(28); |
| 80fafdf | | | 712 | const decipher = createDecipheriv("aes-256-gcm", key, iv); |
| 80fafdf | | | 713 | decipher.setAuthTag(tag); |
| 80fafdf | | | 714 | return decipher.update(data).toString("utf8") + decipher.final("utf8"); |
| 80fafdf | | | 715 | } |
| 80fafdf | | | 716 | |
| 80fafdf | | | 717 | private loadSecrets(repoId: number): Record<string, string> { |
| 80fafdf | | | 718 | const rows = this.db |
| 80fafdf | | | 719 | .prepare( |
| 80fafdf | | | 720 | `SELECT name, encrypted_value FROM canopy_secrets WHERE repo_id = ?` |
| 80fafdf | | | 721 | ) |
| 80fafdf | | | 722 | .all(repoId) as any[]; |
| 80fafdf | | | 723 | const secrets: Record<string, string> = {}; |
| 80fafdf | | | 724 | for (const row of rows) { |
| 80fafdf | | | 725 | try { |
| 80fafdf | | | 726 | secrets[row.name] = this.decrypt(row.encrypted_value); |
| 80fafdf | | | 727 | } catch {} |
| 80fafdf | | | 728 | } |
| 80fafdf | | | 729 | return secrets; |
| 80fafdf | | | 730 | } |
| 80fafdf | | | 731 | |
| 80fafdf | | | 732 | private resolveSecrets( |
| 80fafdf | | | 733 | env: Record<string, string>, |
| 80fafdf | | | 734 | secrets: Record<string, string> |
| 80fafdf | | | 735 | ): Record<string, string> { |
| 80fafdf | | | 736 | const resolved: Record<string, string> = {}; |
| 80fafdf | | | 737 | for (const [key, value] of Object.entries(env)) { |
| 80fafdf | | | 738 | resolved[key] = value.replace( |
| 80fafdf | | | 739 | /\$\{\{\s*secrets\.(\w+)\s*\}\}/g, |
| 80fafdf | | | 740 | (_, name) => secrets[name] ?? "" |
| 80fafdf | | | 741 | ); |
| 80fafdf | | | 742 | } |
| 80fafdf | | | 743 | return resolved; |
| 80fafdf | | | 744 | } |
| 80fafdf | | | 745 | |
| 80fafdf | | | 746 | cancelRun(runId: number): void { |
| 80fafdf | | | 747 | const controller = this.running.get(runId); |
| 80fafdf | | | 748 | if (controller) controller.abort(); |
| 80fafdf | | | 749 | } |
| 80fafdf | | | 750 | } |