Files
2026-01-17 16:42:43 +02:00

106 lines
3.0 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Jobs\CheckHealthEndpoint;
use App\Models\HealthCheck;
use App\Models\Site;
use Illuminate\Console\Command;
class MonitorHealth extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'monitor:health
{--health-check= : Specific health check ID to monitor}
{--site= : Monitor all health checks for a specific site ID}
{--sync : Run checks synchronously instead of queuing}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Monitor application health endpoints';
/**
* Execute the console command.
*/
public function handle(): int
{
$this->info('Starting health endpoint monitoring...');
$query = HealthCheck::with('site')->where('is_active', true);
// Filter by specific health check
if ($healthCheckId = $this->option('health-check')) {
$query->where('id', $healthCheckId);
}
// Filter by site
if ($siteId = $this->option('site')) {
$query->where('site_id', $siteId);
}
$healthChecks = $query->get();
if ($healthChecks->isEmpty()) {
$this->warn('No active health checks found.');
return self::SUCCESS;
}
$this->info("Found {$healthChecks->count()} active health check(s).");
$bar = $this->output->createProgressBar($healthChecks->count());
$bar->start();
$dispatched = 0;
$errors = 0;
foreach ($healthChecks as $healthCheck) {
try {
if ($this->option('sync')) {
// Run synchronously
CheckHealthEndpoint::dispatchSync($healthCheck);
$this->newLine();
$this->line(" ✓ Checked: {$healthCheck->site->name} - {$healthCheck->endpoint}");
} else {
// Queue the job
CheckHealthEndpoint::dispatch($healthCheck);
}
$dispatched++;
} catch (\Exception $e) {
$errors++;
$this->newLine();
$this->error(" ✗ Error checking {$healthCheck->site->name} - {$healthCheck->endpoint}: {$e->getMessage()}");
}
$bar->advance();
}
$bar->finish();
$this->newLine(2);
// Summary
$this->info("Health monitoring completed!");
$this->table(
['Metric', 'Count'],
[
['Total Health Checks', $healthChecks->count()],
['Successfully Dispatched', $dispatched],
['Errors', $errors],
]
);
if (!$this->option('sync')) {
$this->comment('Jobs have been queued. Run the queue worker to process them.');
}
return self::SUCCESS;
}
}