-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathHealthController.php
More file actions
98 lines (84 loc) · 2.7 KB
/
Copy pathHealthController.php
File metadata and controls
98 lines (84 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class HealthController extends Controller
{
public function ping(): Response
{
return response('pong!', 200)
->header('Content-Type', 'text/plain');
}
public function health(): JsonResponse
{
$checks = [
'database' => $this->checkDatabase(),
'redis' => $this->checkRedis(),
'disk' => $this->checkDisk(),
];
$healthy = collect($checks)->every(fn ($check) => $check['status'] === 'ok');
return response()->json([
'status' => $healthy ? 'healthy' : 'unhealthy',
'checks' => $checks,
'timestamp' => now()->toIso8601String(),
], $healthy ? 200 : 503);
}
private function checkDatabase(): array
{
try {
DB::connection()->getPdo();
DB::select('SELECT 1');
return ['status' => 'ok'];
} catch (\Exception $e) {
return [
'status' => 'error',
'message' => $e->getMessage(),
];
}
}
private function checkRedis(): array
{
try {
$response = Redis::ping();
if ($response === true || $response == 'PONG' || (is_object($response) && method_exists($response, 'getPayload') && $response->getPayload() === 'PONG')) {
return ['status' => 'ok'];
}
return [
'status' => 'error',
'message' => 'Unexpected response from Redis',
];
} catch (\Exception $e) {
return [
'status' => 'error',
'message' => $e->getMessage(),
];
}
}
private function checkDisk(): array
{
try {
$path = storage_path();
$freeBytes = disk_free_space($path);
$totalBytes = disk_total_space($path);
if ($freeBytes === false || $totalBytes === false) {
return [
'status' => 'error',
'message' => 'Unable to read disk space',
];
}
$usedPercent = round((($totalBytes - $freeBytes) / $totalBytes) * 100, 1);
$status = $usedPercent > 95 ? 'error' : ($usedPercent > 85 ? 'warning' : 'ok');
return [
'status' => $status,
'used_percent' => $usedPercent,
];
} catch (\Exception $e) {
return [
'status' => 'error',
'message' => $e->getMessage(),
];
}
}
}