-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck.php
More file actions
executable file
·228 lines (191 loc) · 7.58 KB
/
check.php
File metadata and controls
executable file
·228 lines (191 loc) · 7.58 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
#!/usr/bin/env php
<?php
/**
* Check4Fail - Main cron script
*
* This script checks configured sites for availability and performance issues.
* It should be run via cron at regular intervals (e.g., every minute).
*
* @package Check4Fail
* @author Check4Fail Contributors
* @license MIT License
* @link https://github.com/yourusername/check4fail
*
* Usage: php check.php [--config=/path/to/config.toml]
*/
// Set error reporting
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
// Base directory
define('BASE_DIR', __DIR__);
define('DATA_DIR', BASE_DIR . '/data');
define('LOCK_DIR', BASE_DIR . '/var/lock');
define('LOG_DIR', BASE_DIR . '/var/log');
// Ensure required directories exist
foreach ([DATA_DIR, LOCK_DIR, LOG_DIR] as $dir) {
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
}
// Set up logging
$logFile = LOG_DIR . '/check4fail_' . date('Y-m-d') . '.log';
ini_set('error_log', $logFile);
// Load classes
require_once BASE_DIR . '/src/ConfigParser.php';
require_once BASE_DIR . '/src/Lock.php';
require_once BASE_DIR . '/src/SiteChecker.php';
require_once BASE_DIR . '/src/StatisticsStorage.php';
require_once BASE_DIR . '/src/AnomalyDetector.php';
require_once BASE_DIR . '/src/EmailNotifier.php';
/**
* Log message to file and stdout
*/
function logMessage(string $level, string $message): void {
$timestamp = date('Y-m-d H:i:s');
$logLine = "[{$timestamp}] [{$level}] {$message}\n";
error_log("[{$level}] {$message}");
echo $logLine;
}
/**
* Main execution function
*/
function main(): int {
$startTime = microtime(true);
logMessage('INFO', 'Check4Fail started');
// Parse command line arguments
$configFile = BASE_DIR . '/config.toml';
$options = getopt('', ['config:']);
if (isset($options['config'])) {
$configFile = $options['config'];
}
// Check if config exists
if (!file_exists($configFile)) {
logMessage('ERROR', "Configuration file not found: {$configFile}");
logMessage('INFO', 'Please copy config.toml.example to config.toml and configure your sites');
return 1;
}
// Acquire lock to prevent race conditions
$lock = new Lock(LOCK_DIR . '/check4fail.lock', 3600);
if (!$lock->acquire()) {
$lockInfo = $lock->getLockInfo();
logMessage('WARNING', 'Another instance is already running');
if ($lockInfo) {
logMessage('WARNING', sprintf(
'Lock held by PID %d since %s (age: %d seconds)',
$lockInfo['pid'],
$lockInfo['started_at'],
$lockInfo['age_seconds']
));
}
return 2;
}
try {
// Load configuration
logMessage('INFO', "Loading configuration from: {$configFile}");
$config = ConfigParser::parse($configFile);
// Validate configuration
if (empty($config['sites'])) {
logMessage('ERROR', 'No sites configured in config.toml');
return 1;
}
$settings = $config['settings'] ?? [];
$anomalyThresholds = $config['anomaly_thresholds'] ?? [];
$sites = $config['sites'];
logMessage('INFO', sprintf('Found %d site(s) to monitor', count($sites)));
// Initialize components
$storage = new StatisticsStorage(
DATA_DIR,
$settings['retention_days'] ?? 7,
$settings['compression_threshold_days'] ?? 1
);
$checker = new SiteChecker($settings['timeout_per_site'] ?? 30);
$detector = new AnomalyDetector($storage, $anomalyThresholds);
$notifier = new EmailNotifier();
// Check all sites in parallel
logMessage('INFO', 'Starting parallel site checks...');
$allMetrics = $checker->checkSitesParallel($sites);
// Process each result
$anomalyCount = 0;
foreach ($allMetrics as $index => $metrics) {
$siteConfig = $sites[$index];
$siteName = $siteConfig['name'] ?? $siteConfig['url'];
logMessage('INFO', sprintf(
'Site: %s | Status: %d | Time: %s ms | Size: %s bytes',
$siteName,
$metrics['http_code'],
$metrics['response_time'],
$metrics['size_download']
));
// Store metrics
$storage->store($metrics);
// Detect anomalies
$analysis = $detector->detectAnomalies($metrics, $siteConfig);
if ($analysis['has_anomalies']) {
$anomalyCount++;
logMessage('WARNING', sprintf(
'Anomalies detected for %s: %d issue(s)',
$siteName,
count($analysis['anomalies'])
));
// Check if there are any critical/error level anomalies (not just warnings)
$hasHardError = false;
foreach ($analysis['anomalies'] as $anomaly) {
logMessage('WARNING', sprintf(
' - [%s] %s',
$anomaly['severity'],
$anomaly['message']
));
// Critical or error severity = hard error that needs notification
if (in_array($anomaly['severity'], ['critical', 'error'])) {
$hasHardError = true;
}
}
// Only send notification for hard errors (critical/error), not warnings
if ($hasHardError) {
try {
$notificationSent = $notifier->sendAnomalyNotification($analysis, $siteConfig);
if ($notificationSent) {
logMessage('INFO', "Notification sent to {$siteConfig['notification_email']}");
} else {
logMessage('ERROR', "Failed to send notification to {$siteConfig['notification_email']}");
}
} catch (Exception $e) {
logMessage('ERROR', "Error sending notification: {$e->getMessage()}");
}
} else {
logMessage('INFO', "Only warnings detected for {$siteName}, skipping email notification");
}
}
}
// Maintenance tasks
logMessage('INFO', 'Running maintenance tasks...');
// Compress old data
$compressed = $storage->compressOldData();
if ($compressed > 0) {
logMessage('INFO', "Compressed {$compressed} old data file(s)");
}
// Cleanup old data beyond retention
$deleted = $storage->cleanupOldData();
if ($deleted > 0) {
logMessage('INFO', "Deleted {$deleted} file(s) beyond retention period");
}
$endTime = microtime(true);
$duration = round($endTime - $startTime, 2);
logMessage('INFO', sprintf(
'Check4Fail completed in %s seconds | Sites: %d | Anomalies: %d',
$duration,
count($sites),
$anomalyCount
));
return 0;
} catch (Exception $e) {
logMessage('ERROR', 'Fatal error: ' . $e->getMessage());
logMessage('ERROR', 'Stack trace: ' . $e->getTraceAsString());
return 1;
} finally {
$lock->release();
}
}
// Execute main function
exit(main());