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 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 | #!/usr/bin/env node /** * BuildHive Agent CLI * * Command-line interface for managing the BuildHive agent. * Provides commands for registration, starting/stopping the agent, and status checks. * * Requirements: MVP.4.1.1, MVP.4.1.2, MVP.4.3.3 */ import { Command } from 'commander'; import inquirer from 'inquirer'; import { BuildHiveAgent } from './agent.js'; import { loadConfig } from './config/index.js'; import { AgentRegistration } from './registration/index.js'; import { createLogger } from './utils/logger.js'; import { promises as fs } from 'fs'; import { join } from 'path'; import os from 'os'; const logger = createLogger('cli'); const program = new Command(); // Package info const VERSION = '1.0.0'; program .name('buildhive-agent') .description('BuildHive CI Agent - Distributed build execution agent') .version(VERSION); /** * Init command - One-liner setup wizard (Task 2.1.1) * Guides the user through full agent setup in a single interactive flow. */ program .command('init') .description('Initialize and set up the BuildHive agent (one-liner setup)') .option('-y, --yes', 'Accept all defaults without prompting') .action(async (options) => { console.log('=== BuildHive Agent Setup ===\n'); console.log('This wizard will guide you through setting up the BuildHive agent.\n'); try { // Step 1: Gather configuration via prompts let serverUrl = 'http://localhost:3001'; let agentName = `agent-${os.hostname()}`; if (!options.yes) { const answers = await inquirer.prompt([ { type: 'input', name: 'serverUrl', message: 'BuildHive server URL:', default: serverUrl, validate: (input: string) => { try { new URL(input); return true; } catch { return 'Please enter a valid URL (e.g. http://localhost:3001)'; } }, }, { type: 'input', name: 'agentName', message: 'Agent name:', default: agentName, }, ]); serverUrl = answers.serverUrl; agentName = answers.agentName; } // Step 2: Scan installed SDKs console.log('\n[1/5] Scanning installed SDKs...'); const { scanInstalledSDKs, generateTagsFromSDKs } = await import('./utils/sdkScanner.js'); const sdkResult = await scanInstalledSDKs(); const sdkTags = generateTagsFromSDKs(sdkResult); const detectedTools = Object.keys(sdkResult).filter(k => (sdkResult as Record<string, unknown>)[k] !== undefined); console.log(` Detected ${detectedTools.length} tool(s): ${detectedTools.join(', ')}`); if (sdkTags.length > 0) { console.log(` Generated ${sdkTags.length} capability tag(s): ${sdkTags.join(', ')}`); } // Step 3: Validate Docker is running console.log('\n[2/5] Checking Docker...'); try { const { execSync } = await import('child_process'); execSync('docker info', { stdio: 'pipe' }); console.log(' Docker is running.'); } catch { console.error(' Docker does not appear to be running.'); console.error(' Please start Docker and re-run: npx buildhive-agent init'); process.exit(1); } // Step 4: Test server connectivity console.log(`\n[3/5] Connecting to server at ${serverUrl}...`); const { BuildHiveApiClient } = await import('./registration/apiClient.js'); const apiClient = new BuildHiveApiClient(serverUrl); const connected = await apiClient.testConnection(); if (!connected) { console.error(` Cannot reach server at ${serverUrl}.`); console.error(' Please verify the server is running and the URL is correct.'); process.exit(1); } console.log(' Server is reachable.'); // Step 5: Register the agent (generates agentId + apiKey) console.log('\n[4/5] Registering agent...'); const registration = new AgentRegistration(serverUrl); const config = await registration.registerAgent({ platformUrl: serverUrl, name: agentName, tags: ['docker', ...sdkTags], maxConcurrentJobs: 1, }); console.log(` Agent registered. ID: ${config.agentId}`); // Step 5: Write config file const configDir = join(os.homedir(), '.buildhive'); const configPath = join(configDir, 'config.json'); await fs.mkdir(configDir, { recursive: true }); await fs.writeFile( configPath, JSON.stringify( { serverUrl, agentId: config.agentId, apiKey: config.apiKey, agentName, }, null, 2 ), 'utf-8' ); console.log(` Config saved to ${configPath}`); // Step 6: Send first heartbeat to verify end-to-end console.log('\n[5/5] Sending first heartbeat...'); try { await apiClient.sendHeartbeat( { agentId: config.agentId, status: 'ONLINE', currentLoad: 0, activeJobs: 0, }, config.apiKey ); console.log(' Heartbeat sent successfully.'); } catch { // Non-fatal — agent is set up, heartbeat can be retried at runtime console.warn(' Heartbeat failed (non-fatal). The agent will retry on start.'); } console.log('\n=== Setup complete! ==='); console.log(` Agent name : ${agentName}`); console.log(` Agent ID : ${config.agentId}`); console.log(` Server : ${serverUrl}`); console.log(` Config : ${configPath}`); console.log('\nNext steps:'); console.log(' Start the agent : buildhive-agent start'); console.log(' Check status : buildhive-agent status'); console.log(' View logs : buildhive-agent logs\n'); } catch (error) { console.error('\n[ERROR] Setup failed:', error instanceof Error ? error.message : error); process.exit(1); } }); /** * Register command - Interactive agent registration */ program .command('register') .description('Register agent with BuildHive platform') .option('-u, --url <url>', 'Platform URL') .option('-n, --name <name>', 'Agent name') .option('-t, --tags <tags>', 'Comma-separated tags') .option('-j, --jobs <number>', 'Maximum concurrent jobs', '1') .option('-c, --config <path>', 'Configuration file path') .option('-y, --yes', 'Skip confirmation prompts') .action(async (options) => { try { console.log('=== BuildHive Agent Registration ===\n'); let platformUrl = options.url; let agentName = options.name; let tags = options.tags ? options.tags.split(',').map((t: string) => t.trim()) : []; let maxJobs = parseInt(options.jobs); // Interactive prompts if options not provided if (!options.yes) { const answers = await inquirer.prompt([ { type: 'input', name: 'platformUrl', message: 'BuildHive Platform URL:', default: platformUrl || 'http://localhost:3001', when: !platformUrl, }, { type: 'input', name: 'agentName', message: 'Agent name:', default: agentName || `agent-${os.hostname()}`, when: !agentName, }, { type: 'input', name: 'tags', message: 'Tags (comma-separated):', default: tags.length > 0 ? tags.join(',') : 'docker,linux', when: tags.length === 0, }, { type: 'number', name: 'maxJobs', message: 'Maximum concurrent jobs:', default: maxJobs || 1, when: !maxJobs, }, { type: 'confirm', name: 'confirm', message: 'Proceed with registration?', default: true, }, ]); if (answers.confirm === false) { console.log('Registration cancelled.'); process.exit(0); } platformUrl = platformUrl || answers.platformUrl; agentName = agentName || answers.agentName; tags = tags.length > 0 ? tags : answers.tags.split(',').map((t: string) => t.trim()); maxJobs = maxJobs || answers.maxJobs; } // Perform registration console.log('\nRegistering agent...'); const registration = new AgentRegistration(platformUrl); const config = await registration.registerAgent({ platformUrl, name: agentName, tags, maxConcurrentJobs: maxJobs, configPath: options.config, }); console.log('\n✓ Agent registered successfully!'); console.log(` Agent ID: ${config.agentId}`); console.log(` Name: ${config.name}`); console.log(` Platform: ${config.platformUrl}`); console.log( ` Config saved to: ${ options.config || join(os.homedir(), '.buildhive', 'buildhive-agent.json') }` ); console.log('\nYou can now start the agent with: buildhive-agent start'); } catch (error) { console.error('\n✗ Registration failed:', error instanceof Error ? error.message : error); process.exit(1); } }); /** * Start command - Start the agent */ program .command('start') .description('Start the BuildHive agent') .option('-c, --config <path>', 'Configuration file path') .option('-d, --daemon', 'Run as daemon (background process)') .action(async (options) => { try { console.log('Starting BuildHive Agent...\n'); // Load configuration const config = await loadConfig(); console.log(`Agent: ${config.name}`); console.log(`Platform: ${config.platformUrl}\n`); // Create PID file directory const pidDir = join(os.homedir(), '.buildhive'); await fs.mkdir(pidDir, { recursive: true }); // Write PID file const pidFile = join(pidDir, 'agent.pid'); await fs.writeFile(pidFile, process.pid.toString(), 'utf-8'); // Create and start agent const agent = await BuildHiveAgent.create(config); // Handle graceful shutdown const shutdown = async (signal: string) => { console.log(`\nReceived ${signal}, shutting down gracefully...`); try { await agent.stop(); // Remove PID file try { await fs.unlink(pidFile); } catch (error) { logger.error('Failed to remove PID file:', error); } console.log('Agent stopped successfully'); process.exit(0); } catch (error) { console.error('Error during shutdown:', error); process.exit(1); } }; process.on('SIGINT', () => shutdown('SIGINT')); process.on('SIGTERM', () => shutdown('SIGTERM')); process.on('SIGQUIT', () => shutdown('SIGQUIT')); // Handle uncaught exceptions process.on('uncaughtException', (error) => { logger.error('Uncaught exception:', error); shutdown('uncaughtException').catch(() => process.exit(1)); }); process.on('unhandledRejection', (reason, promise) => { logger.error('Unhandled rejection at:', promise, 'reason:', reason); shutdown('unhandledRejection').catch(() => process.exit(1)); }); // Start the agent await agent.start(); console.log('BuildHive Agent started successfully'); console.log(`PID: ${process.pid}`); console.log('Press Ctrl+C to stop\n'); // Keep process alive if (!options.daemon) { setInterval(() => { // Keep alive }, 1000); } } catch (error) { console.error('\n✗ Failed to start agent:', error instanceof Error ? error.message : error); process.exit(1); } }); /** * Stop command - Stop the agent (for daemon mode) */ program .command('stop') .description('Stop the BuildHive agent daemon') .action(async () => { try { const pidFile = join(os.homedir(), '.buildhive', 'agent.pid'); // Check if PID file exists try { await fs.access(pidFile); } catch { console.error('Agent is not running (PID file not found)'); process.exit(1); } // Read PID from file const pidContent = await fs.readFile(pidFile, 'utf-8'); const pid = parseInt(pidContent.trim()); if (isNaN(pid)) { console.error('Invalid PID file content'); await fs.unlink(pidFile); // Clean up invalid PID file process.exit(1); } // Check if process exists try { process.kill(pid, 0); // Signal 0 checks if process exists } catch (error: any) { if (error.code === 'ESRCH') { console.log('Agent process not found, cleaning up PID file'); await fs.unlink(pidFile); process.exit(0); } throw error; } // Send SIGTERM to gracefully stop the agent console.log(`Stopping BuildHive Agent (PID: ${pid})...`); process.kill(pid, 'SIGTERM'); // Wait for process to stop let attempts = 0; const maxAttempts = 30; // Wait up to 15 seconds while (attempts < maxAttempts) { try { process.kill(pid, 0); await new Promise(resolve => setTimeout(resolve, 500)); attempts++; } catch (error: any) { if (error.code === 'ESRCH') { // Process stopped await fs.unlink(pidFile); console.log('✓ Agent stopped successfully'); process.exit(0); } } } // If still running after timeout, force kill console.warn('Agent did not stop gracefully, forcing shutdown...'); process.kill(pid, 'SIGKILL'); await fs.unlink(pidFile); console.log('✓ Agent stopped (forced)'); } catch (error) { console.error('\n✗ Failed to stop agent:', error instanceof Error ? error.message : error); process.exit(1); } }); /** * Status command - Show agent status */ program .command('status') .description('Show agent status') .option('-c, --config <path>', 'Configuration file path') .action(async (options) => { try { const config = await loadConfig(); console.log('=== BuildHive Agent Status ===\n'); console.log(`Name: ${config.name}`); console.log(`Agent ID: ${config.agentId}`); console.log(`Platform: ${config.platformUrl}`); console.log(`Max Concurrent Jobs: ${config.maxConcurrentJobs}`); console.log(`Tags: ${config.tags.join(', ')}`); console.log('\nConfiguration:'); console.log(` Heartbeat Interval: ${config.heartbeatInterval}s`); console.log(` Job Timeout: ${config.jobTimeoutMinutes}m`); console.log(` Log Level: ${config.logLevel}`); console.log(` Metrics Enabled: ${config.enableMetrics ? 'Yes' : 'No'}`); // Check if agent is running const pidFile = join(os.homedir(), '.buildhive', 'agent.pid'); let isRunning = false; let pid: number | null = null; try { const pidContent = await fs.readFile(pidFile, 'utf-8'); pid = parseInt(pidContent.trim()); if (!isNaN(pid)) { try { process.kill(pid, 0); // Check if process exists isRunning = true; } catch (error: any) { if (error.code === 'ESRCH') { // Process not found, clean up stale PID file await fs.unlink(pidFile); } } } } catch (error) { // PID file doesn't exist or couldn't be read } console.log(`\nRunning: ${isRunning ? `Yes (PID: ${pid})` : 'No'}`); if (!isRunning) { console.log('\nTo start the agent, run: buildhive-agent start'); } } catch (error) { console.error('\n✗ Failed to get status:', error instanceof Error ? error.message : error); process.exit(1); } }); /** * Config command - Show or edit configuration */ program .command('config') .description('Show configuration') .option('-c, --config <path>', 'Configuration file path') .option('--show', 'Show full configuration (default)') .action(async (options) => { try { const configPath = options.config || join(os.homedir(), '.buildhive', 'buildhive-agent.json'); // Check if config exists try { await fs.access(configPath); } catch { console.error(`Configuration file not found: ${configPath}`); console.log('\nRegister the agent first with: buildhive-agent register'); process.exit(1); } // Read and display config const configContent = await fs.readFile(configPath, 'utf8'); const config = JSON.parse(configContent); console.log('=== BuildHive Agent Configuration ===\n'); console.log(`Config file: ${configPath}\n`); // Mask sensitive fields const displayConfig = { ...config }; if (displayConfig.apiKey) { displayConfig.apiKey = '****' + displayConfig.apiKey.slice(-4); } console.log(JSON.stringify(displayConfig, null, 2)); } catch (error) { console.error('\n✗ Failed to read configuration:', error instanceof Error ? error.message : error); process.exit(1); } }); /** * Test command - Test connection to platform */ program .command('test') .description('Test connection to BuildHive platform') .option('-c, --config <path>', 'Configuration file path') .action(async (options) => { try { console.log('Testing connection to BuildHive platform...\n'); const config = await loadConfig(); const { BuildHiveApiClient } = await import('./registration/apiClient.js'); const apiClient = new BuildHiveApiClient(config.platformUrl); const connected = await apiClient.testConnection(); if (connected) { console.log('✓ Successfully connected to BuildHive platform'); console.log(` URL: ${config.platformUrl}`); } else { console.error('✗ Failed to connect to BuildHive platform'); console.error(` URL: ${config.platformUrl}`); process.exit(1); } } catch (error) { console.error('\n✗ Connection test failed:', error instanceof Error ? error.message : error); process.exit(1); } }); /** * Logs command - View agent logs */ program .command('logs') .description('View BuildHive agent logs') .option('-f, --follow', 'Follow log output (like tail -f)') .option('-n, --lines <number>', 'Number of lines to show', '50') .action(async (options) => { try { const logFile = join(os.homedir(), '.buildhive', 'logs', 'buildhive-agent.log'); // Check if log file exists try { await fs.access(logFile); } catch { console.error(`Log file not found: ${logFile}`); console.log('\nThe agent may not have been started yet.'); process.exit(1); } const numLines = parseInt(options.lines); if (options.follow) { // Follow mode: Use tail -f equivalent console.log(`Following logs from: ${logFile}`); console.log('Press Ctrl+C to stop\n'); const { spawn } = await import('child_process'); const tail = spawn('tail', ['-f', '-n', numLines.toString(), logFile]); tail.stdout.on('data', (data) => { process.stdout.write(data); }); tail.stderr.on('data', (data) => { process.stderr.write(data); }); tail.on('close', (code) => { process.exit(code || 0); }); // Handle Ctrl+C process.on('SIGINT', () => { tail.kill(); process.exit(0); }); } else { // Show last N lines const logContent = await fs.readFile(logFile, 'utf-8'); const lines = logContent.split('\n'); const displayLines = lines.slice(-numLines); console.log(`Last ${numLines} lines from: ${logFile}\n`); displayLines.forEach(line => { if (line.trim()) { console.log(line); } }); } } catch (error) { console.error('\n✗ Failed to read logs:', error instanceof Error ? error.message : error); process.exit(1); } }); // Parse command line arguments program.parse(); // Show help if no command provided if (!process.argv.slice(2).length) { program.outputHelp(); } |