1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\UptimeMonitor\Checker; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Promise\EachPromise; |
6
|
|
|
use GuzzleHttp\Promise\Promise; |
7
|
|
|
use GuzzleHttp\Psr7\Response; |
8
|
|
|
use Spatie\UptimeMonitor\Helpers\ConsoleOutput; |
9
|
|
|
use Spatie\UptimeMonitor\MonitorCollection; |
10
|
|
|
|
11
|
|
|
class DatabaseChecker extends Checker |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* {@inheritdoc} |
15
|
|
|
*/ |
16
|
|
|
public function check(MonitorCollection $monitors) |
17
|
|
|
{ |
18
|
|
|
$monitors->resetItemKeys(); |
19
|
|
|
$this->monitors = $monitors; |
20
|
|
|
(new EachPromise($this->getPromises($monitors), [ |
21
|
|
|
'concurrency' => config('laravel-uptime-monitor.uptime_check.concurrent_checks'), |
22
|
|
|
'fulfilled' => function ($monitor, $index) { |
23
|
|
|
$monitor = $this->monitors->getMonitorAtIndex($index); |
24
|
|
|
ConsoleOutput::info("Could reach {$monitor->url}"); |
25
|
|
|
}, |
26
|
|
|
'rejected' => function ($exception, $index) { |
27
|
|
|
$monitor = $this->monitors->getMonitorAtIndex($index); |
28
|
|
|
ConsoleOutput::error("Could not reach {$monitor->url} error: `{$exception->getMessage()}`"); |
29
|
|
|
}, |
30
|
|
|
]))->promise()->wait(); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
protected function getPromises($monitors): \Generator |
34
|
|
|
{ |
35
|
|
|
foreach ($monitors as $monitor) { |
36
|
|
|
$promise = with(new Promise())->then(null, function () use (&$promise, $monitor) { |
37
|
|
|
$urlSegments = explode('://', $monitor->url); |
38
|
|
|
$protocol = $urlSegments[0]; |
39
|
|
|
$hostSegments = explode(':', $urlSegments[1]); |
40
|
|
|
$host = $hostSegments[0]; |
41
|
|
|
$port = (array_key_exists(1, $hostSegments)) ? $hostSegments[1] : 3306; |
42
|
|
|
ConsoleOutput::info("Checking {$monitor->url}"); |
43
|
|
|
\Config::set("database.connections.{$monitor->id}", [ |
44
|
|
|
'driver' => $protocol, |
45
|
|
|
'host' => $host, |
46
|
|
|
'port' => $port, |
47
|
|
|
'database' => 'monitorDB', |
48
|
|
|
'username' => 'monitorUser', |
49
|
|
|
'password' => '', |
50
|
|
|
'charset' => 'utf8', |
51
|
|
|
'collation' => 'utf8_unicode_ci', |
52
|
|
|
'prefix' => '', |
53
|
|
|
'strict' => true, |
54
|
|
|
'engine' => null, |
55
|
|
|
'options' => [ |
56
|
|
|
\PDO::ATTR_TIMEOUT => config('laravel-uptime-monitor.uptime_check.timeout_per_connection'), |
57
|
|
|
], |
58
|
|
|
]); |
59
|
|
|
try { |
60
|
|
|
\DB::connection($monitor->id)->reconnect(); |
61
|
|
|
$monitor->uptimeRequestSucceeded(new Response(200, [], "Could reach {$monitor->url}")); |
62
|
|
|
} catch (\Exception $exception) { |
63
|
|
|
if (str_contains($exception->getMessage(), 'time')) { |
64
|
|
|
$monitor->uptimeRequestFailed($exception->getMessage()); |
65
|
|
|
} else { |
66
|
|
|
$monitor->uptimeRequestSucceeded(new Response(200, [], "Could reach {$monitor->url}")); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
}); |
70
|
|
|
yield $promise; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|