1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\UptimeMonitor; |
4
|
|
|
|
5
|
|
|
use Generator; |
6
|
|
|
use GuzzleHttp\Client; |
7
|
|
|
use GuzzleHttp\Exception\RequestException; |
8
|
|
|
use GuzzleHttp\Promise\EachPromise; |
9
|
|
|
use Illuminate\Support\Collection; |
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
11
|
|
|
use Spatie\UptimeMonitor\Helpers\ConsoleOutput; |
12
|
|
|
use Spatie\UptimeMonitor\Models\Monitor; |
13
|
|
|
|
14
|
|
|
class MonitorCollection extends Collection |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @return static |
18
|
|
|
*/ |
19
|
|
|
public function sortByHost() |
20
|
|
|
{ |
21
|
|
|
return $this->sortBy(function (Monitor $monitor) { |
22
|
|
|
return $monitor->url->getHost(); |
23
|
|
|
}); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function checkUptime() |
27
|
|
|
{ |
28
|
|
|
$this->resetItemKeys(); |
29
|
|
|
|
30
|
|
|
(new EachPromise($this->getPromises(), [ |
31
|
|
|
'concurrency' => config('laravel-uptime-monitor.uptime_check.concurrent_checks'), |
32
|
|
|
'fulfilled' => function (ResponseInterface $response, $index) { |
33
|
|
|
$monitor = $this->getMonitorAtIndex($index); |
34
|
|
|
|
35
|
|
|
ConsoleOutput::info("Could reach {$monitor->url}"); |
36
|
|
|
|
37
|
|
|
$monitor->uptimeRequestSucceeded($response->getBody()); |
38
|
|
|
}, |
39
|
|
|
|
40
|
|
|
'rejected' => function (RequestException $exception, $index) { |
41
|
|
|
$monitor = $this->getMonitorAtIndex($index); |
42
|
|
|
|
43
|
|
|
ConsoleOutput::error("Could not reach {$monitor->url} error: `{$exception->getMessage()}`"); |
44
|
|
|
|
45
|
|
|
$monitor->uptimeRequestFailed($exception->getMessage()); |
46
|
|
|
}, |
47
|
|
|
]))->promise()->wait(); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
protected function getPromises(): Generator |
51
|
|
|
{ |
52
|
|
|
$client = new Client([ |
53
|
|
|
'headers' => [ |
54
|
|
|
'User-Agent' => config('laravel-uptime-monitor.uptime_check.user_agent'), |
55
|
|
|
], |
56
|
|
|
]); |
57
|
|
|
|
58
|
|
|
foreach ($this->items as $monitor) { |
59
|
|
|
ConsoleOutput::info("checking {$monitor->url}"); |
60
|
|
|
$promise = $client->requestAsync( |
61
|
|
|
$monitor->uptime_check_method, |
62
|
|
|
$monitor->url, |
63
|
|
|
['connect_timeout' => config('laravel-uptime-monitor.uptime_check.timeout_per_site')] |
64
|
|
|
); |
65
|
|
|
|
66
|
|
|
yield $promise; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* In order to make use of Guzzle promises we have to make sure the |
72
|
|
|
* keys of the collection are in a consecutive order without gaps. |
73
|
|
|
*/ |
74
|
|
|
protected function resetItemKeys() |
75
|
|
|
{ |
76
|
|
|
$this->items = $this->values()->all(); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
protected function getMonitorAtIndex(int $index): Monitor |
80
|
|
|
{ |
81
|
|
|
return $this->items[$index]; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|