80, // percentage 'ram' => 90, // percentage 'disk' => 90, // percentage ]; /** * Cool-down period in minutes to prevent spamming notifications. */ protected $cooldownMinutes = 30; /** * Execute the console command. */ public function handle(SystemMonitoringService $monitor, TelegramService $telegram) { $this->info('Starting System Health Check...'); $issues = []; $metrics = []; // 1. Check Database Connectivity try { DB::connection()->getPdo(); $metrics[] = '✅ Database: Connected'; } catch (\Exception $e) { $issues[] = '❌ DATABASE DOWN: Unable to connect to the database. Error: '.$e->getMessage(); } // 2. Check CPU Usage $cpu = $monitor->getCpuUsage(); $metrics[] = "📊 CPU Usage: {$cpu}%"; if ($cpu >= $this->thresholds['cpu']) { $issues[] = "⚠️ High CPU Usage: {$cpu}% (Threshold: {$this->thresholds['cpu']}%)"; } // 3. Check RAM Usage $ram = $monitor->getRamUsage(); $metrics[] = "📊 RAM Usage: {$ram}%"; if ($ram >= $this->thresholds['ram']) { $issues[] = "⚠️ High RAM Usage: {$ram}% (Threshold: {$this->thresholds['ram']}%)"; } // 4. Check Disk Usage $disk = $monitor->getDiskUsage(); $metrics[] = "📊 Disk Usage: {$disk}%"; if ($disk >= $this->thresholds['disk']) { $issues[] = "⚠️ High Disk Usage: {$disk}% (Threshold: {$this->thresholds['disk']}%)"; } // Output to console foreach ($metrics as $metric) { $this->line($metric); } if (empty($issues)) { $this->info('System health is optimal. No issues detected.'); return 0; } $this->error(count($issues).' issue(s) detected!'); // Check for cool-down $cacheKey = 'system_health_alert_last_sent'; if (Cache::has($cacheKey) && ! $this->option('force')) { $this->warn('Issues detected, but notification is in cool-down period. Use --force to override.'); return 0; } // Prepare Telegram Message $hostname = gethostname(); $ip = request()->server('SERVER_ADDR') ?? gethostbyname($hostname); $time = now()->format('Y-m-d H:i:s'); $message = "🚨 SYSTEM HEALTH ALERT 🚨\n"; $message .= "--------------------------------\n"; $message .= "Host: {$hostname} ({$ip})\n"; $message .= "Time: {$time}\n"; $message .= "--------------------------------\n\n"; $message .= implode("\n", $issues)."\n\n"; $message .= 'Please check the system dashboard for more details.'; // Send Notification if ($telegram->sendMessage($message)) { $this->info('Alert notification sent to Telegram.'); Cache::put($cacheKey, true, now()->addMinutes($this->cooldownMinutes)); } else { $this->error('Failed to send Telegram notification. Check laravel.log for details.'); } return 0; } }