Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 1x 1x 10x 10x 10x 10x 10x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 6x 6x 6x 6x 6x 6x 6x 6x 6x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 6x 6x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 6x 6x 1x 1x 1x 1x 5x 6x 1x 1x 4x 4x 6x 1x 1x 1x 4x 4x 6x 1x 1x 3x 3x 6x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 9x 9x 6x 6x 3x 3x 3x 3x 3x 3x 9x 9x 9x 9x 3x 3x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* Job Executor - Docker-based job execution
*
* Handles the execution of CI jobs in isolated Docker containers
* with security, resource limits, and progress reporting.
*
* Requirements: 1.1, 1.2, 4.1, 4.2, 4.3, 4.4, 4.5
*/
import { AgentConfig } from './config/types.js';
import { DockerManager } from './docker.js';
import { ArtifactUploader } from './storage/artifactUploader.js';
import { createLogger } from './utils/logger.js';
import { JobSubmissionRequest } from './types.js';
import { promises as fs } from 'fs';
import { join } from 'path';
import { randomUUID } from 'crypto';
import { spawn } from 'child_process';
const logger = createLogger('jobExecutor');
export interface JobExecutionResult {
success: boolean;
exitCode?: number;
logs?: string;
errorMessage?: string;
artifactUrls?: string[];
}
export interface JobProgress {
percentage: number;
currentStep: string;
totalSteps?: number;
currentStepIndex?: number;
estimatedTimeRemaining?: number;
}
export type ProgressCallback = (progress: JobProgress) => void;
export type LogsCallback = (logs: string) => void;
export class JobExecutor {
private config: AgentConfig;
private dockerManager: DockerManager;
private artifactUploader: ArtifactUploader;
private activeJobs = new Map<string, { containerId: string; workDir: string }>();
private workspaceRoot: string;
constructor(config: AgentConfig) {
this.config = config;
this.dockerManager = new DockerManager(config.dockerConfig, config.securityConfig);
this.artifactUploader = new ArtifactUploader(config.storageConfig);
this.workspaceRoot = join(process.cwd(), 'workspaces');
}
/**
* Execute a job in a Docker container
*/
async executeJob(
job: JobSubmissionRequest,
progressCallback: ProgressCallback,
logsCallback: LogsCallback
): Promise<JobExecutionResult> {
const jobId = job.externalId;
const workDir = await this.createWorkspace(jobId);
logger.info(`Executing job ${jobId} in workspace: ${workDir}`);
try {
// Step 1: Validate job requirements
progressCallback({
percentage: 5,
currentStep: 'Validating job requirements',
totalSteps: 8,
currentStepIndex: 1
});
await this.validateJobRequirements(job);
logsCallback(`[INFO] Job requirements validated for ${jobId}`);
// Step 2: Prepare workspace
progressCallback({
percentage: 15,
currentStep: 'Preparing workspace',
totalSteps: 8,
currentStepIndex: 2
});
await this.prepareWorkspace(workDir, job);
logsCallback(`[INFO] Workspace prepared at ${workDir}`);
// Step 3: Pull Docker image
progressCallback({
percentage: 25,
currentStep: 'Pulling Docker image',
totalSteps: 8,
currentStepIndex: 3
});
await this.dockerManager.pullImage(job.dockerImage);
logsCallback(`[INFO] Docker image pulled: ${job.dockerImage}`);
// Step 4: Create container
progressCallback({
percentage: 35,
currentStep: 'Creating container',
totalSteps: 8,
currentStepIndex: 4
});
const containerId = await this.dockerManager.createContainer({
image: job.dockerImage,
workDir: '/workspace',
environment: job.environment || {},
volumeMounts: [
{
hostPath: workDir,
containerPath: '/workspace',
readOnly: false
}
]
});
this.activeJobs.set(jobId, { containerId, workDir });
logsCallback(`[INFO] Container created: ${containerId}`);
// Step 5: Start container
progressCallback({
percentage: 45,
currentStep: 'Starting container',
totalSteps: 8,
currentStepIndex: 5
});
await this.dockerManager.startContainer(containerId);
logsCallback(`[INFO] Container started: ${containerId}`);
// Step 6: Execute build command
progressCallback({
percentage: 55,
currentStep: 'Executing build command',
totalSteps: 8,
currentStepIndex: 6
});
logsCallback(`[INFO] Executing command: ${job.buildCommand}`);
const executionResult = await this.dockerManager.executeCommand(
containerId,
job.buildCommand,
{
timeout: this.config.jobTimeoutMinutes * 60 * 1000,
onOutput: (output) => {
logsCallback(`[BUILD] ${output}`);
}
}
);
// Step 7: Collect artifacts
progressCallback({
percentage: 85,
currentStep: 'Collecting artifacts',
totalSteps: 8,
currentStepIndex: 7
});
const artifactUrls = await this.collectArtifacts(containerId, workDir, job.artifacts || []);
if (artifactUrls.length > 0) {
logsCallback(`[INFO] Collected ${artifactUrls.length} artifacts`);
}
// Step 8: Cleanup
progressCallback({
percentage: 95,
currentStep: 'Cleaning up',
totalSteps: 8,
currentStepIndex: 8
});
await this.cleanupJob(jobId);
logsCallback(`[INFO] Job cleanup completed`);
// Final progress
progressCallback({
percentage: 100,
currentStep: 'Job completed',
totalSteps: 8,
currentStepIndex: 8
});
const success = executionResult.exitCode === 0;
logsCallback(`[INFO] Job ${jobId} ${success ? 'completed successfully' : 'failed'} (exit code: ${executionResult.exitCode})`);
return {
success,
exitCode: executionResult.exitCode,
logs: executionResult.output,
artifactUrls
};
} catch (error) {
logger.error(`Job execution failed for ${jobId}:`, error);
logsCallback(`[ERROR] Job execution failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
// Cleanup on error
await this.cleanupJob(jobId);
return {
success: false,
errorMessage: error instanceof Error ? error.message : 'Unknown error'
};
}
}
/**
* Cancel a running job
*/
async cancelJob(jobId: string): Promise<void> {
const jobInfo = this.activeJobs.get(jobId);
if (!jobInfo) {
logger.warn(`Attempted to cancel non-existent job: ${jobId}`);
return;
}
logger.info(`Cancelling job: ${jobId}`);
try {
// Stop the container
await this.dockerManager.stopContainer(jobInfo.containerId);
logger.info(`Container stopped for job: ${jobId}`);
} catch (error) {
logger.error(`Error stopping container for job ${jobId}:`, error);
}
// Clean up
await this.cleanupJob(jobId);
}
/**
* Clean up resources
*/
async cleanup(): Promise<void> {
logger.info('Cleaning up job executor...');
// Cancel all active jobs
const activeJobIds = Array.from(this.activeJobs.keys());
for (const jobId of activeJobIds) {
await this.cancelJob(jobId);
}
// Clean up Docker manager
await this.dockerManager.cleanup();
}
/**
* Validate job requirements against agent capabilities
*/
private async validateJobRequirements(job: JobSubmissionRequest): Promise<void> {
// Check repository whitelist/blacklist
if (this.config.allowedRepositories && this.config.allowedRepositories.length > 0) {
if (!this.config.allowedRepositories.includes(job.repository)) {
throw new Error(`Repository ${job.repository} is not in the allowed list`);
}
}
if (this.config.blockedRepositories && this.config.blockedRepositories.includes(job.repository)) {
throw new Error(`Repository ${job.repository} is blocked`);
}
// Default Docker image if not provided
if (!job.dockerImage || job.dockerImage.trim() === '') {
job.dockerImage = 'node:20';
logger.info(`No Docker image specified, defaulting to ${job.dockerImage}`);
}
// Validate build command
if (!job.buildCommand || job.buildCommand.trim() === '') {
throw new Error('Build command is required');
}
logger.info(`Job requirements validated for ${job.externalId}`);
}
/**
* Create workspace directory for job
*/
private async createWorkspace(jobId: string): Promise<string> {
const workDir = join(this.workspaceRoot, jobId);
try {
await fs.mkdir(workDir, { recursive: true });
logger.info(`Created workspace: ${workDir}`);
return workDir;
} catch (error) {
logger.error(`Failed to create workspace ${workDir}:`, error);
throw new Error(`Failed to create workspace: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Prepare workspace with job context
*/
private async prepareWorkspace(workDir: string, job: JobSubmissionRequest): Promise<void> {
try {
// Build the clone URL, injecting credentials for private repositories.
// When a githubToken is present we rewrite the HTTPS URL to embed the
// x-access-token convention so no interactive credential prompt is needed.
// The token is intentionally kept out of log lines.
const cloneUrl = job.githubToken
? this.buildAuthenticatedCloneUrl(job.repository, job.githubToken)
: job.repository;
// Disable all interactive git prompts so the process fails fast instead
// of hanging indefinitely when credentials are missing or wrong.
const gitEnv: Record<string, string> = {
GIT_TERMINAL_PROMPT: '0',
};
logger.info(`Cloning repository ${job.repository} (branch: ${job.branch}) into ${workDir}${job.githubToken ? ' [token auth]' : ''}`);
const cloneResult = await this.executeGitCommand([
'clone', cloneUrl,
'--branch', job.branch,
'--single-branch',
'.'
], workDir, gitEnv);
if (cloneResult.exitCode !== 0) {
// Scrub any embedded token from the error message before surfacing it
const safeError = job.githubToken
? (cloneResult.error || cloneResult.output).replace(job.githubToken, '[REDACTED]')
: (cloneResult.error || cloneResult.output);
throw new Error(`Git clone failed: ${safeError}`);
}
// Checkout exact commit if specified and differs from branch HEAD
if (job.commitSha) {
const checkoutResult = await this.executeGitCommand(
['checkout', job.commitSha],
workDir,
gitEnv
);
if (checkoutResult.exitCode !== 0) {
logger.warn(`Could not checkout exact commit ${job.commitSha}, using branch HEAD`);
}
}
logger.info(`Repository cloned successfully for job ${job.externalId}`);
// Create job metadata file
const jobMetadata = {
jobId: job.externalId,
repository: job.repository,
branch: job.branch,
commitSha: job.commitSha,
jobType: job.jobType,
createdAt: new Date().toISOString()
};
await fs.writeFile(
join(workDir, '.buildhive-job.json'),
JSON.stringify(jobMetadata, null, 2)
);
// Create environment file if needed
if (job.environment && Object.keys(job.environment).length > 0) {
const envContent = Object.entries(job.environment)
.map(([key, value]) => `${key}=${value}`)
.join('\n');
await fs.writeFile(join(workDir, '.env'), envContent);
}
logger.info(`Workspace prepared for job ${job.externalId}`);
} catch (error) {
logger.error(`Failed to prepare workspace for job ${job.externalId}:`, error);
throw new Error(`Failed to prepare workspace: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Build an authenticated clone URL from a plain HTTPS repository URL.
*
* Converts https://github.com/user/repo (or https://github.com/user/repo.git)
* to https://x-access-token:{token}@github.com/user/repo using the
* x-access-token convention supported by GitHub App installation tokens,
* fine-grained PATs, and classic PATs.
*
* Only HTTPS URLs are rewritten. SSH URLs (git@github.com:...) are returned
* unchanged because they rely on key-based auth, not token-based.
*
* The token is never written to disk or emitted in log lines.
*/
private buildAuthenticatedCloneUrl(repositoryUrl: string, token: string): string {
try {
const parsed = new URL(repositoryUrl);
// Only inject credentials into HTTPS URLs
if (parsed.protocol !== 'https:') {
return repositoryUrl;
}
parsed.username = 'x-access-token';
parsed.password = token;
return parsed.toString();
} catch {
// Malformed URL — return as-is and let git produce the error
return repositoryUrl;
}
}
/**
* Execute a git command in the given working directory.
*
* @param args - Arguments to pass to the git binary
* @param cwd - Working directory for the git process
* @param env - Additional environment variables merged on top of process.env.
* Use this to pass GIT_ASKPASS, GIT_TERMINAL_PROMPT=0, etc.
* @param timeoutMs - Maximum time to wait before killing the process (default 5 min)
*/
private executeGitCommand(
args: string[],
cwd: string,
env?: Record<string, string>,
timeoutMs: number = 300000
): Promise<{ exitCode: number; output: string; error: string }> {
return new Promise((resolve) => {
const mergedEnv = env
? { ...process.env, ...env } as NodeJS.ProcessEnv
: process.env;
const proc = spawn('git', args, { cwd, env: mergedEnv });
let output = '';
let error = '';
let killed = false;
const timer = setTimeout(() => {
killed = true;
proc.kill('SIGKILL');
resolve({ exitCode: 1, output, error: `Git command timed out after ${timeoutMs / 1000}s` });
}, timeoutMs);
proc.stdout.on('data', (data: Buffer) => { output += data.toString(); });
proc.stderr.on('data', (data: Buffer) => { error += data.toString(); });
proc.on('close', (code: number | null) => {
clearTimeout(timer);
if (!killed) {
resolve({ exitCode: code ?? 1, output, error });
}
});
proc.on('error', (err: Error) => {
clearTimeout(timer);
if (!killed) {
resolve({ exitCode: 1, output: '', error: err.message });
}
});
});
}
/**
* Collect build artifacts from container
*
* MVP.4.2.4: Artifacts are copied from container and uploaded to configured storage
*/
private async collectArtifacts(
containerId: string,
workDir: string,
artifactPaths: string[]
): Promise<string[]> {
if (artifactPaths.length === 0) {
return [];
}
const artifactUrls: string[] = [];
try {
for (const artifactPath of artifactPaths) {
const localPath = join(workDir, 'artifacts', artifactPath);
// Step 1: Copy artifact from container to host
logger.debug(`Copying artifact from container: ${artifactPath}`);
await this.dockerManager.copyFromContainer(
containerId,
`/workspace/${artifactPath}`,
localPath
);
// Step 2: Upload artifact to configured storage (MVP.4.2.4)
logger.debug(`Uploading artifact to storage: ${artifactPath}`);
const result = await this.artifactUploader.uploadArtifact(
localPath,
artifactPath,
{
deleteAfterUpload: this.config.storageConfig.cleanupAfterUpload
}
);
artifactUrls.push(result.url);
logger.debug(`Artifact uploaded successfully`, {
path: artifactPath,
url: result.url,
size: result.size
});
}
logger.info(`Collected and uploaded ${artifactUrls.length} artifacts`);
} catch (error) {
logger.error('Failed to collect artifacts:', error);
// Don't fail the job if artifact collection fails
}
return artifactUrls;
}
/**
* Clean up job resources
*/
private async cleanupJob(jobId: string): Promise<void> {
const jobInfo = this.activeJobs.get(jobId);
if (!jobInfo) {
return;
}
try {
// Remove and clean up container
await this.dockerManager.removeContainer(jobInfo.containerId);
// Clean up workspace (optional, for debugging you might want to keep it)
if (process.env.NODE_ENV === 'production') {
await fs.rm(jobInfo.workDir, { recursive: true, force: true });
logger.info(`Cleaned up workspace: ${jobInfo.workDir}`);
}
} catch (error) {
logger.error(`Error during cleanup for job ${jobId}:`, error);
} finally {
this.activeJobs.delete(jobId);
}
}
/**
* Clean up old artifacts based on retention policy (MVP.4.2.4)
*
* Should be called periodically by the agent to enforce retention policy.
*
* @returns Number of artifacts deleted
*/
async cleanupOldArtifacts(): Promise<number> {
logger.info('Starting artifact retention cleanup');
try {
const deletedCount = await this.artifactUploader.cleanupOldArtifacts();
logger.info(`Artifact retention cleanup complete`, { deletedCount });
return deletedCount;
} catch (error) {
logger.error('Artifact retention cleanup failed:', error);
return 0;
}
}
/**
* Get artifact storage statistics (MVP.4.2.4)
*
* @returns Storage statistics
*/
async getArtifactStorageStats() {
return this.artifactUploader.getStorageStats();
}
} |