1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\UptimeMonitor\Services\PingMonitors; |
4
|
|
|
|
5
|
|
|
use Spatie\UptimeMonitor\Models\PingMonitor; |
6
|
|
|
use Cache; |
7
|
|
|
use Generator; |
8
|
|
|
use GuzzleHttp\Client; |
9
|
|
|
use GuzzleHttp\Exception\RequestException; |
10
|
|
|
use GuzzleHttp\Promise\EachPromise; |
11
|
|
|
use Illuminate\Support\Collection; |
12
|
|
|
use Log; |
13
|
|
|
use Psr\Http\Message\ResponseInterface; |
14
|
|
|
|
15
|
|
|
class UptimeMonitorCollection extends Collection |
16
|
|
|
{ |
17
|
|
|
public function check() |
18
|
|
|
{ |
19
|
|
|
$this->resetItemKeys(); |
20
|
|
|
|
21
|
|
|
Log::info("Start checking for {$this->count()} monitors..."); |
22
|
|
|
|
23
|
|
|
(new EachPromise($this->getPromises(), [ |
24
|
|
|
'concurrency' => 100, |
25
|
|
|
'fulfilled' => function (ResponseInterface $response, $index) { |
26
|
|
|
$uptimeMonitor = $this->items[$index]; |
27
|
|
|
|
28
|
|
|
$this->log('fulfilled ping', $uptimeMonitor); |
29
|
|
|
|
30
|
|
|
$uptimeMonitor->pingSucceeded($response->getBody()); |
31
|
|
|
}, |
32
|
|
|
|
33
|
|
|
'rejected' => function (RequestException $exception, $index) { |
34
|
|
|
$uptimeMonitor = $this->items[$index]; |
35
|
|
|
|
36
|
|
|
$this->log("rejected ping because: {$exception->getMessage()}", $uptimeMonitor); |
37
|
|
|
|
38
|
|
|
$uptimeMonitor->pingFailed($exception->getMessage()); |
39
|
|
|
}, |
40
|
|
|
]))->promise()->wait(); |
41
|
|
|
|
42
|
|
|
Log::info('Checking done!'); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
protected function getPromises() : Generator |
46
|
|
|
{ |
47
|
|
|
$client = new Client([ |
48
|
|
|
'headers' => [ |
49
|
|
|
'User-Agent' => 'spatie/laravel-uptime-monitor uptime checker', |
50
|
|
|
], |
51
|
|
|
]); |
52
|
|
|
|
53
|
|
|
foreach ($this->items as $uptimeMonitor) { |
54
|
|
|
$this->log('checking', $uptimeMonitor); |
55
|
|
|
|
56
|
|
|
$promise = $client->requestAsync( |
57
|
|
|
$uptimeMonitor->getPingRequestMethod(), |
58
|
|
|
$uptimeMonitor->url, |
59
|
|
|
['connect_timeout' => 10] |
60
|
|
|
); |
61
|
|
|
|
62
|
|
|
yield $promise; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Make sure the keys are in consecutive order without gaps. |
68
|
|
|
*/ |
69
|
|
|
protected function resetItemKeys() |
70
|
|
|
{ |
71
|
|
|
$this->items = $this->values()->all(); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
public function log($message, PingMonitor $pingMonitor) |
75
|
|
|
{ |
76
|
|
|
Log::info("$message (url: {$pingMonitor->url} id: {$pingMonitor->id})"); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|