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 | const fs = require('fs').promises; const path = require('path'); const logger = require('./logger'); const MetricsCollector = require('./metricsCollector'); const LogCollector = require('./logCollector'); const Uploader = require('./uploader'); const Scheduler = require('./scheduler'); class LogVistaAgent { constructor() { this.config = null; this.metricsCollector = null; this.logCollector = null; this.uploader = null; this.scheduler = null; this.isRunning = false; } async init() { try { logger.info('Initializing LogVista Agent...'); // Load configuration await this.loadConfig(); // Initialize components this.metricsCollector = new MetricsCollector(); this.logCollector = new LogCollector(); this.uploader = new Uploader(this.config); this.scheduler = new Scheduler( this.metricsCollector, this.logCollector, this.uploader, this.config ); // Test connection to central system const connected = await this.uploader.testConnection(); if (!connected) { logger.warn('Unable to connect to central system. Agent will continue and retry periodically.'); } logger.info('LogVista Agent initialized successfully'); } catch (error) { logger.error('Failed to initialize LogVista Agent:', error); throw error; } } async loadConfig() { try { let configPath; // Priority order for config files: // 1. Environment variable (set by CLI) // 2. Local project .logvista/config.json // 3. Legacy config/agent.config.json // 4. Global config if (process.env.LOGVISTA_CONFIG_PATH) { configPath = process.env.LOGVISTA_CONFIG_PATH; } else { const localConfigPath = path.join(process.cwd(), '.logvista', 'config.json'); const legacyConfigPath = path.join(__dirname, '../config/agent.config.json'); const os = require('os'); const globalConfigPath = path.join( os.platform() === 'win32' ? path.join(os.homedir(), 'AppData', 'Roaming', 'LogVista') : path.join(os.homedir(), '.logvista'), 'agent.config.json' ); if (await fs.access(localConfigPath).then(() => true).catch(() => false)) { configPath = localConfigPath; } else if (await fs.access(legacyConfigPath).then(() => true).catch(() => false)) { configPath = legacyConfigPath; } else if (await fs.access(globalConfigPath).then(() => true).catch(() => false)) { configPath = globalConfigPath; } else { throw new Error('No configuration file found. Run "logvista init" to create one.'); } } logger.info(`Loading configuration from: ${configPath}`); const configContent = await fs.readFile(configPath, 'utf8'); this.config = JSON.parse(configContent); // Validate required configuration this.validateConfig(); logger.info('Configuration loaded successfully'); logger.debug('Config:', { projects: this.config.projects.length, interval: this.config.collection?.interval || this.config.agent?.collection_interval || 30, centralUrl: this.config.central_system.url }); } catch (error) { logger.error('Failed to load configuration:', error); throw new Error(`Configuration error: ${error.message}`); } } validateConfig() { // Flexible validation for both old and new config formats const required = ['central_system', 'projects']; for (const field of required) { if (!this.config[field]) { throw new Error(`Missing required configuration: ${field}`); } } if (!this.config.central_system.url) { throw new Error('Missing central_system.url in configuration'); } if (!this.config.central_system.token) { logger.warn('Missing central_system.token in configuration - you may need to set this'); } // Ensure collection config exists (support both old and new format) if (!this.config.collection && !this.config.agent) { this.config.collection = { interval: 30, batch_size: 100, retry_attempts: 3, retry_delay: 5000 }; } if (!Array.isArray(this.config.projects) || this.config.projects.length === 0) { throw new Error('At least one project must be configured'); } // Validate each project for (const project of this.config.projects) { if (!project.project_name) { throw new Error('Missing project_name in project configuration'); } if (!project.pwd_path) { throw new Error('Missing pwd_path in project configuration'); } } } async start() { try { if (this.isRunning) { logger.warn('Agent is already running'); return; } logger.info('Starting LogVista Agent...'); // Start log watching await this.logCollector.startWatching(this.config.projects); // Start scheduler this.scheduler.start(); this.isRunning = true; logger.info('LogVista Agent started successfully'); // Log agent status this.logStatus(); } catch (error) { logger.error('Failed to start LogVista Agent:', error); throw error; } } async stop() { try { if (!this.isRunning) { logger.warn('Agent is not running'); return; } logger.info('Stopping LogVista Agent...'); // Stop scheduler if (this.scheduler) { this.scheduler.stop(); } // Stop log watching if (this.logCollector) { this.logCollector.stopWatching(); } this.isRunning = false; logger.info('LogVista Agent stopped successfully'); } catch (error) { logger.error('Error stopping LogVista Agent:', error); throw error; } } logStatus() { const status = { isRunning: this.isRunning, scheduler: this.scheduler ? this.scheduler.getStatus() : null, projects: this.config.projects.filter(p => p.enabled).map(p => ({ name: p.project_name, path: p.pwd_path, logPaths: p.custom_log_paths?.length || 0 })), config: { collectionInterval: this.config.agent.collection_interval, batchSize: this.config.agent.batch_size, centralUrl: this.config.central_system.url } }; logger.info('Agent Status:', status); } async getStatus() { return { isRunning: this.isRunning, scheduler: this.scheduler ? this.scheduler.getStatus() : null, projects: this.config?.projects?.filter(p => p.enabled) || [], uptime: process.uptime(), memory: process.memoryUsage(), version: require('../package.json').version }; } } // Main execution async function main() { const agent = new LogVistaAgent(); try { await agent.init(); await agent.start(); // Graceful shutdown handlers const gracefulShutdown = async (signal) => { logger.info(`Received ${signal}, shutting down gracefully...`); try { await agent.stop(); process.exit(0); } catch (error) { logger.error('Error during shutdown:', error); process.exit(1); } }; process.on('SIGINT', () => gracefulShutdown('SIGINT')); process.on('SIGTERM', () => gracefulShutdown('SIGTERM')); // Handle uncaught exceptions process.on('uncaughtException', (error) => { logger.error('Uncaught Exception:', error); gracefulShutdown('uncaughtException'); }); process.on('unhandledRejection', (reason, promise) => { logger.error('Unhandled Rejection at:', promise, 'reason:', reason); gracefulShutdown('unhandledRejection'); }); } catch (error) { logger.error('Failed to start agent:', error); process.exit(1); } } // Export for potential use as module module.exports = LogVistaAgent; // Run if this file is executed directly if (require.main === module) { main(); } |