| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226 |
- <?php
- namespace App\Module\ThirdParty\Commands;
- use Illuminate\Console\Command;
- use App\Module\ThirdParty\Services\MonitorService;
- use App\Module\ThirdParty\Models\ThirdPartyService;
- /**
- * 第三方服务健康检查命令
- */
- class HealthCheckCommand extends Command
- {
- /**
- * 命令签名
- *
- * @var string
- */
- protected $signature = 'thirdparty:health-check
- {--service= : 指定服务ID或代码}
- {--all : 检查所有服务}
- {--active-only : 只检查激活的服务}
- {--verbose : 显示详细信息}';
- /**
- * 命令描述
- *
- * @var string
- */
- protected $description = '执行第三方服务健康检查';
- /**
- * 执行命令
- *
- * @return int
- */
- public function handle(): int
- {
- $this->info('开始执行第三方服务健康检查...');
- try {
- $serviceId = $this->getServiceId();
- $results = MonitorService::performHealthCheck($serviceId);
- $this->displayResults($results);
- $this->displaySummary($results);
- return Command::SUCCESS;
- } catch (\Exception $e) {
- $this->error("健康检查失败: {$e->getMessage()}");
- return Command::FAILURE;
- }
- }
- /**
- * 获取要检查的服务ID
- *
- * @return int|null
- */
- protected function getServiceId(): ?int
- {
- $serviceOption = $this->option('service');
-
- if (!$serviceOption) {
- return null;
- }
- // 如果是数字,直接返回
- if (is_numeric($serviceOption)) {
- $service = ThirdPartyService::find($serviceOption);
- if (!$service) {
- throw new \Exception("服务ID {$serviceOption} 不存在");
- }
- return (int)$serviceOption;
- }
- // 如果是代码,查找对应的服务
- $service = ThirdPartyService::where('code', $serviceOption)->first();
- if (!$service) {
- throw new \Exception("服务代码 {$serviceOption} 不存在");
- }
- return $service->id;
- }
- /**
- * 显示检查结果
- *
- * @param array $results
- * @return void
- */
- protected function displayResults(array $results): void
- {
- if (empty($results)) {
- $this->warn('没有找到需要检查的服务');
- return;
- }
- $this->info("\n检查结果:");
- $this->line(str_repeat('-', 80));
- foreach ($results as $result) {
- $this->displaySingleResult($result);
- }
- }
- /**
- * 显示单个服务的检查结果
- *
- * @param array $result
- * @return void
- */
- protected function displaySingleResult(array $result): void
- {
- $status = $result['status'];
- $serviceName = $result['service_name'];
- $serviceCode = $result['service_code'];
- // 根据状态选择颜色
- $color = match ($status) {
- 'success' => 'green',
- 'warning' => 'yellow',
- 'error', 'timeout' => 'red',
- default => 'white',
- };
- $this->line("<fg={$color}>[{$status}]</fg> {$serviceName} ({$serviceCode})");
- if ($this->option('verbose')) {
- if ($result['response_time']) {
- $this->line(" 响应时间: {$result['response_time']}ms");
- }
- if ($result['status_code']) {
- $this->line(" HTTP状态码: {$result['status_code']}");
- }
- if ($result['error_message']) {
- $this->line(" 错误信息: {$result['error_message']}");
- }
- if (!empty($result['details'])) {
- $this->line(" 详细信息:");
- foreach ($result['details'] as $key => $value) {
- if (is_array($value)) {
- $value = json_encode($value, JSON_UNESCAPED_UNICODE);
- }
- $this->line(" {$key}: {$value}");
- }
- }
- } else {
- if ($result['error_message']) {
- $this->line(" {$result['error_message']}");
- }
- }
- $this->line('');
- }
- /**
- * 显示检查摘要
- *
- * @param array $results
- * @return void
- */
- protected function displaySummary(array $results): void
- {
- if (empty($results)) {
- return;
- }
- $total = count($results);
- $successful = count(array_filter($results, fn($r) => $r['status'] === 'success'));
- $warnings = count(array_filter($results, fn($r) => $r['status'] === 'warning'));
- $errors = count(array_filter($results, fn($r) => in_array($r['status'], ['error', 'timeout'])));
- $this->line(str_repeat('-', 80));
- $this->info('检查摘要:');
- $this->line("总计: {$total}");
- $this->line("<fg=green>成功: {$successful}</fg>");
-
- if ($warnings > 0) {
- $this->line("<fg=yellow>警告: {$warnings}</fg>");
- }
-
- if ($errors > 0) {
- $this->line("<fg=red>错误: {$errors}</fg>");
- }
- $successRate = $total > 0 ? round(($successful / $total) * 100, 2) : 0;
- $this->line("成功率: {$successRate}%");
- // 如果有失败的服务,给出建议
- if ($errors > 0) {
- $this->line('');
- $this->warn('建议:');
- $this->line('- 检查失败服务的配置和凭证');
- $this->line('- 确认第三方服务是否正常运行');
- $this->line('- 查看详细日志了解具体错误原因');
- }
- }
- /**
- * 获取要检查的服务列表
- *
- * @return \Illuminate\Database\Eloquent\Collection
- */
- protected function getServicesToCheck()
- {
- $query = ThirdPartyService::query();
- if ($this->option('active-only')) {
- $query->where('status', 'ACTIVE');
- }
- if ($this->option('all')) {
- return $query->get();
- }
- // 默认只检查有健康检查URL的激活服务
- return $query->where('status', 'ACTIVE')
- ->whereNotNull('health_check_url')
- ->get();
- }
- }
|